// Javascript for CSV Tool

SteamingPileOfCrap = navigator.appVersion.indexOf('MSIE') != -1;
IsMSIE  = SteamingPileOfCrap;
IsMSIE7 = navigator.appVersion.indexOf('MSIE 7.0') != -1;

// Gets the name of script/page from a URL
function getScriptName(OverrideURL, IncludeQueryStr, ReturnOnlyQueryStr) {
	UseURL         = (OverrideURL)?OverrideURL:document.location.href;
	UseURL         = UseURL.replace(/#.*/, '');
	QueryStrExists = UseURL.indexOf('?') != -1;
	
	QueryStr = '';

	if (QueryStrExists) {
		QueryStr = UseURL.substr(UseURL.indexOf('?'));
		UseURL   = UseURL.substr(0, UseURL.indexOf('?'));
	}

	if (QueryStrExists && IncludeQueryStr)
		return (ReturnOnlyQueryStr)?QueryStr:UseURL.substr(UseURL.lastIndexOf('/')+1) + QueryStr;
	else
		return (ReturnOnlyQueryStr)?QueryStr:UseURL.substr(UseURL.lastIndexOf('/')+1);
}

// GENERATES A DIV CONTAINING A "PLEASE WAIT..." MESSAGE
function generateWaitDiv(OverrideText, DoNotGenerateDisableDiv, CustomCSSArray, OverrideInnerHTML, OverrideCoverOpac) {

	var NewDiv = document.createElement('div');

	if (!OverrideInnerHTML)
		var ContainedText = document.createTextNode((OverrideText)?OverrideText:'Please Wait');
	
	with (NewDiv.style) {
		width         = '180px';
		position      = 'absolute';
		border        = '1px solid #BCBCFF';
		background    = '#EFEFFF';
		fontWeight    = 'bold';
		textAlign     = 'center';
		verticalAlign = 'middle';
		paddingTop    = '20px';
		paddingBottom = '20px';
		zIndex        = '1';
		
		// Override CSS...
		if (typeof CustomCSSArray == 'object') {
			for (CSSDirective in CustomCSSArray)
				eval(CSSDirective + ' = \'' + CustomCSSArray[CSSDirective] + '\'');
		}		
		
		left = (getWindowDimension('x')/2)-((parseInt(width)+20)/2) + 'px';
		top  = String(parseInt(document.documentElement.scrollTop) + parseInt(getWindowDimension('y')/2)
		       -(parseInt(paddingTop)+parseInt(paddingBottom)+10)) + 'px';
	}
	
	NewDiv.setAttribute('id', 'WaitDiv');
	
	if (!OverrideInnerHTML)
		NewDiv.appendChild(ContainedText);	
	
	if (!DoNotGenerateDisableDiv) {
		var NewDisableDiv = document.createElement('div');
		
		with (NewDisableDiv.style) {
			top		= '0px';
			left		= '0px';
			width		= '100%';
			position	= 'absolute';
			height		= (document.documentElement.scrollTop + getWindowDimension('y')) + 'px';
			background	= '#FFFFFF';
			
			if (IsMSIE) {
				filter = 'alpha(opacity=' + ((OverrideCoverOpac)?OverrideCoverOpac*100:'30') + ')';
				backgroundColor = '#FFFFFF';
				//background = "url('img/space.gif')";
			}
			else {
				toggleSelectMenuVisibility(true, 'hidden');
				setProperty('-moz-opacity', (OverrideCoverOpac)?OverrideCoverOpac:'.30', ''); 
				setProperty('opacity', (OverrideCoverOpac)?OverrideCoverOpac:'.30', '');
			}
		}
	}
	
	NewDisableDiv.setAttribute('id', 'DisableDiv');
	
	if (OverrideInnerHTML)
		NewDiv.innerHTML = OverrideInnerHTML;
	
	document.body.appendChild(NewDiv);
	document.body.appendChild(NewDisableDiv);
}


// DELETES WAIT DIV
function deleteWaitDiv() {
	try {
		document.body.removeChild(document.getElementById('WaitDiv'));
		document.body.removeChild(document.getElementById('DisableDiv'));
		toggleSelectMenuVisibility(true, 'visible');
	}
	
	catch (e) {
		//alert('error deleting waitDiv: ' + e);
	}
}

// GETS WINDOW DIMENSIONS
function getWindowDimension(Dim) {
	if (Dim == 'x')
		return (SteamingPileOfCrap)?document.documentElement.clientWidth:window.innerWidth;
	else
		return (SteamingPileOfCrap)?document.documentElement.clientHeight:window.innerHeight;
}

// TOGGLES VISIBILITY OF ALL SELECT MENUS
function toggleSelectMenuVisibility(OnlyForIE, OverrideVisibility) {
	if (navigator.appName == "Microsoft Internet Explorer" || !OnlyForIE) {
		for (i = 0; i < document.forms.length; i++) {
			for (j = 0; j < document.forms[i].elements.length; j++) {
				Obj       = document.forms[i].elements[j];
				ElmntType = Obj.type;
	
				if (ElmntType == "select-one" || ElmntType == "select-multiple") {					
					if (OverrideVisibility)
						Obj.style.visibility = OverrideVisibility;
					else {
						NoVisibility = (document.forms[i].elements[j].style.visibility == "")?true:false;
						Obj.style.visibility = (NoVisibility)?'hidden':'visible';
					}
				}
			}
		}
	}
}

// CONVERTS FORM DATA TO GET STRING
function convertFormDataToGETStr(formObj, AlternateParentElmntForFields) { 
		
	POSTDataArray = new Array();
	
	// Loop through form fields
	AltCounter = 0;
	ElmntsList = '';
	
	if (AlternateParentElmntForFields)
		LoopInObjectsArray = new Array(formObj.elements,
					       AlternateParentElmntForFields.getElementsByTagName('input'),
					       AlternateParentElmntForFields.getElementsByTagName('textarea'),
					       AlternateParentElmntForFields.getElementsByTagName('select')
					      );

	else
		LoopInObjectsArray = new Array(formObj.elements);
	
 	for (var i in LoopInObjectsArray) {
	
		for (var j = 0; j < LoopInObjectsArray[i].length; j++) {
			
			Elmnt = LoopInObjectsArray[i][j];
	
			Name  = '';
			Value = '';
			
			if (!Elmnt.disabled) {
			
				// Submit different information for various types of fields...
				switch (Elmnt.type) {
					
					// "Normal" field
					default:
						Name  = Elmnt.name;
						Value = Elmnt.value;
					break;
					
					// Radio
					case 'radio':
						if (Elmnt.checked) {
							Name  = Elmnt.name;
							Value = Elmnt.value;
						}
					break;
					
					// Checkbox
					case 'checkbox':
						Name  = Elmnt.name;
						Value = (Elmnt.checked)?Elmnt.value:'';
					break;
				}
				
				if (Name != '' && Name != 'undefined' && Name != undefined && Name != 'null' && Name != null) {
					POSTDataArray[AltCounter] = encodeURIComponent(Name) + '=' + encodeURIComponent(Value);
					AltCounter++;
				}
			}
		}
	}
	
	return POSTDataArray.join('&');
}

// Update action
function UpdateAction(ConfirmOrCancel) {
	ConfirmOrCancel2 = ConfirmOrCancel;
	
	generateWaitDiv(((ConfirmOrCancel)?'Confirming':'Cancel') + ' Update');
	
	AJAX_sendRequest(true,
	
	'?UpdateAction=' + ConfirmOrCancel,
	
	"if (response.substr(0,6) == 'STATS:') { with (document) { getElementById('PreviewActionBtns').style.display = 'none'; stats = response.substr(6).split('|'); " +
	"getElementById('StatsContainer_LastUpdated').innerHTML	= stats[0]; getElementById('StatsContainer_TotalRecords').innerHTML = stats[1]; } " +
	"parent.document.getElementById('IframeLabel').innerHTML = 'Current Database:'; " +
	"if (!ConfirmOrCancel2) { document.getElementById('ProcessingPreviewFrame_ID').src = 'index.php?DefaultIframe'; } } " +
	"else alert(response); deleteWaitDiv();");
}

// RESTRICTS INPUT TO REGEXP AND/OR ARRAY AND MINIMUM LENGTH
function restrictInputChars(FormFieldObj, InputRestriction, AllowCaseChange) {
	if (typeof(InputRestriction) == 'object' && !FormFieldObj.disabled) {
	
		// RegExp objects don't have lengths
		if (InputRestriction.length == 'undefined' || InputRestriction.length == undefined)
			FormFieldObj.value = FormFieldObj.value.replace(InputRestriction, '');
		
		// Array of accepted values	
		else {
			
			if (AllowCaseChange) {
				Needle = FormFieldObj.value.toLowerCase();
				
				for (var i in InputRestriction)
					InputRestriction[i] = InputRestriction[i].toLowerCase();
			}
			else
				Needle = FormFieldObj.value;
			
			// Not in array, clear value and refocus
			if (!in_array(Needle, InputRestriction)) {
				with (FormFieldObj)
					value = '';
			}
		}
	}
}

// Sets a cookie
function setCookie(name_, data, expire, path, domain_) {
	document.cookie =
	name_ + '=' + data + ';' +
	((expire)?' expires=' + expire + ';':'') +
	((path)?' path=' + path + ';':'') +
	((domain_)?'domain=' + domain_:'');
}

// Reads a cookie
function getCookie(name_) {
	CookieDataArray = document.cookie.split(';');
	for (var i = 0; i < CookieDataArray.length; i++) {							
		ThisCookie = CookieDataArray[i].split('=');
		if (ThisCookie[0] == name_)
			return ThisCookie[1];
	}
}

// Function to create image overlay
function enlargeImg(ImgSrc, ImgLabel, ImgText) {
	
	IsYoutubeVideo = ImgSrc.substr(0,9) == 'VIDEOSRC:';

	with (document) {
		NewContainerDiv	= createElement('div');
		NewDisableDiv	= createElement('div');
		NewImg		= createElement('img');
		NewXImg		= createElement('img');
		//ImgTextElmnt	= createTextNode(ImgText);
		NewTextContainerDiv = createElement('div');
	}
	
	with (NewImg) {
		src		= ImgSrc;
		style.margin	= '0px 0px 20px 0px';
		style.cursor	= 'pointer';
		style.display	= 'block';
	
		TmpLabel = ImgLabel + ' [click to close]';		
		setAttribute('alt', TmpLabel);
		setAttribute('title', TmpLabel);
		setAttribute('id', 'MainImg');
	}
	
	with (NewXImg) {
 		src = '../.lib/x.gif';
		
		style.position	= 'absolute';
		style.margin	= '-35px 0px 0px ' + ((IsMSIE7 && IsYoutubeVideo)?'5':NewImg.width+5) + 'px';
		style.cursor	= 'pointer';
		
		setAttribute('width', '30');
		setAttribute('height', '35');
		setAttribute('alt', 'close');
		setAttribute('title', 'close');
		setAttribute('id', 'XImg');
	}
	
	setEvent(NewImg, 'onClick', 'closeMainImg()');
	setEvent(NewXImg, 'onClick', 'closeMainImg()');
	
	if (NewImg.width == 0 && !IsYoutubeVideo) {
		setTimeout('enlargeImg("' + ImgSrc + '", "' + ImgLabel + '", "' + ImgText + '")', 500);
		return;
	}
	else if (IsYoutubeVideo)
		NewImg.width = 425;
	
	NewTextContainerDiv.style.width = NewImg.width + 'px';

	setLeft = (Math.round(document.body.clientWidth / 2)*1)/1 - ((NewImg.width + 10) / 2);
	setLeft = ((String(setLeft).indexOf('.') == -1)?String(setLeft):String(setLeft).substr(0, String(setLeft).lastIndexOf('.'))) + 'px';
	
	setTop = String(document.documentElement.scrollTop + 35) + 'px';
	
	with (NewContainerDiv) {
		setAttribute('id', 'MainImgContainer');
		
		style.position	= 'absolute';
		style.top	= setTop;
		style.left	= setLeft;
		style.zIndex	= '2';
		style.background= '#FFFFFF';
		style.fontFamily= 'Arial';
		style.fontSize	= '12px';
		style.padding   = '20px'; 
	}
	
	with (NewDisableDiv.style) {
		top        = '0px';
		left       = '0px';
		width      = '100%';
		position   = 'absolute';
		height     = String(document.body.scrollHeight) + 'px';
		background = '#000000';
		zIndex     = '1';
		
		if (IsMSIE) {
			//toggleSelectMenuVisibility(true, 'hidden');
			filter = 'alpha(opacity=75)';
		}
		else {
			setProperty('-moz-opacity', '.75', ''); 
			setProperty('opacity', '.75', '');			
		}			
	}
	
	NewDisableDiv.setAttribute('id', 'DisableDiv');
	
	with (document.body) {
		appendChild(NewDisableDiv);
		appendChild(NewContainerDiv);
	}
	
	if (IsYoutubeVideo) {
		NewContainerDiv.innerHTML
		= '<object width="425" height="344" style="margin-bottom: 20px"><param name="movie" value="' + ImgSrc.substr(9) + '"></param>'
		+ '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>'
		+ '<embed src="' + ImgSrc.substr(9) + '" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" '
		+ 'allowfullscreen="true" style="margin-bottom: 20px"></embed></object>';
		
		NewContainerDiv.appendChild(NewXImg);
	}
	else {
		NewContainerDiv.appendChild(NewXImg);
		NewContainerDiv.appendChild(NewImg);
	}
	
	NewContainerDiv.appendChild(NewTextContainerDiv);
	NewTextContainerDiv.innerHTML = ImgText;
}

// Function to close overlay
function closeMainImg() {
	with (NewContainerDiv) {
		removeChild(document.getElementById('MainImg'));
		removeChild(document.getElementById('XImg'));
	}
	
	with (document.body) {
		removeChild(document.getElementById('DisableDiv'));
		removeChild(document.getElementById('MainImgContainer'));
	}
}


// ASSIGNS A JAVASCRIPT EVENT TO A SPECIFIED OBJECT ACCORDING TO THE BROWSER
function setEvent(Obj, Event, Action) {
	
	// For IE, use attachEvent
	if (IsMSIE) {
		eval("Obj.attachEvent('" + Event.toLowerCase() + "', function() { " + Action + " });");
	}
	
	// For proper browsers, simply use setAttribute
	else
		Obj.setAttribute(Event, Action);
}

// CONVERTS FORM DATA TO GET STRING
function convertFormDataToGETStr(formObj, AlternateParentElmntForFields) { 
		
	POSTDataArray = new Array();
	
	// Loop through form fields
	AltCounter = 0;
	ElmntsList = '';
	
	if (AlternateParentElmntForFields)
		LoopInObjectsArray = new Array(formObj.elements,
					       AlternateParentElmntForFields.getElementsByTagName('input'),
					       AlternateParentElmntForFields.getElementsByTagName('textarea'),
					       AlternateParentElmntForFields.getElementsByTagName('select')
					      );

	else
		LoopInObjectsArray = new Array(formObj.elements);
	
 	for (var i in LoopInObjectsArray) {
	
		for (var j = 0; j < LoopInObjectsArray[i].length; j++) {
			
			Elmnt = LoopInObjectsArray[i][j];
	
			Name  = '';
			Value = '';
			
			if (!Elmnt.disabled) {
			
				// Submit different information for various types of fields...
				switch (Elmnt.type) {
					
					// "Normal" field
					default:
						Name  = Elmnt.name;
						Value = Elmnt.value;
					break;
					
					// Radio
					case 'radio':
						if (Elmnt.checked) {
							Name  = Elmnt.name;
							Value = Elmnt.value;
						}
					break;
					
					// Checkbox
					case 'checkbox':
						Name  = Elmnt.name;
						Value = (Elmnt.checked)?Elmnt.value:'';
					break;
				}
				
				if (Name != '' && Name != 'undefined' && Name != undefined && Name != 'null' && Name != null) {
					POSTDataArray[AltCounter] = encodeURIComponent(Name) + '=' + encodeURIComponent(Value);
					AltCounter++;
				}
			}
		}
	}
	
	return POSTDataArray.join('&');
}

// Sets errors next to form fields
function setErrors(ErrorOutput, TopLevelObj) {
	ErrorsArray = ErrorOutput.substr(7).split('|');
	
	// Clear all error containers
	Divs = document.forms[0].getElementsByTagName('div');
	for (i in Divs) {
		try {
			if (Divs[i].id.substr(0,6) == 'ERROR_') {
				Divs[i].innerHTML = '';
				Divs[i].style.display = 'none';
			}
		}
		
		catch (e) {
			// do nothing
		}
	}
	
	for (i in ErrorsArray) {
		Error = ErrorsArray[i].split(':');
		
		try {
			with (document.getElementById('ERROR_' + Error[0])) {
				style.display = 'block';
				innerHTML = Error[1];
			}
		}
		catch (e) {
			// do nothing
		}
	}
	
	document.getElementById('ErrorMsg').style.display = 'block';
// 	document.location.href = document.location.href + '#';
}


function getFormJumperTop() {
	return String(parseInt(document.documentElement.scrollTop) + parseInt(getWindowDimension('y')/2)-10) + 'px';
}

// Form jump thingamabob
function moveFormJumper() {

	MinFormJumpTop = (SteamingPileOfCrap)?885:845;
	MaxFormJumpTop = document.body.offsetHeight - ((SteamingPileOfCrap)?1000:930);
	TestTop = parseInt(getFormJumperTop());
	
	with (document.getElementById('FormJumper').style) {
		
		left = String((getWindowDimension('x')/2)+410) + 'px';
		
		// Minimum from top
		if (TestTop < MinFormJumpTop || MinFormJumpTop > MaxFormJumpTop)
			top = MinFormJumpTop + 'px';
		
		// Maximum from top
		else if (TestTop > MaxFormJumpTop)
			top = MaxFormJumpTop + 'px';
		
		// With scrolling
		else 
			top = TestTop + 'px';
	}
}

// Kill jump divs
function killFormJumpers() {
	document.getElementById('FormJumper').style.display = 'none';
}

// Checks if a value exists in an array and optionally returns the index
function in_array(valueToMatch, arrayToCheck, ReturnIndex, CompareKeysNotValues) {
	
	NewArray = new Array();
	
	for (var i in arrayToCheck) {
		if (valueToMatch == ((CompareKeysNotValues)?i:arrayToCheck[i])) {
			if (ReturnIndex == 'array_values')
				NewArray.push(arrayToCheck[i]);
				
			else if (ReturnIndex == 'array_indexes')
				NewArray.push(i);
				
			else if (ReturnIndex == true)
				return i;
			
			else
				return true;
		}
	}
	
	if ((ReturnIndex != null && typeof ReturnIndex != 'boolean') || NewArray.length > 0)
		return NewArray;
	else
		return false;
}

// STRIPS OUT DUPLICATE VALUES FROM AN ARRAY
function JS_array_unique(PassArray) {

	var ReturnArray = new Array();
	for (var i in PassArray) {
		if (!in_array(PassArray[i], ReturnArray))
			ReturnArray.push(PassArray[i]);
	}
	
	return ReturnArray;
}


// For onClick: change a password that's already set	
function changePW(PWObj) {
	with (PWObj) {
		if (PWObj.value == PWObj.defaultValue) {
			if (!IsMSIE)
				type = 'password';
				
			PWObj.value = '';
			style.color = '#000000';
			style.background = '#FFFFFF';
		}
	}	
}

function resetPW(PWObj, OverrideSet) {
	with (PWObj) {
		if (value == '' || OverrideSet) {
			if (!IsMSIE)
				type = 'text';
			
			value = PWObj.defaultValue;
			style.color = '#A0A0A0';
			style.background = '#E0E0E0';
			blur();
		}
	}
}

function mngDefaultValue(FieldObj, OnOrOff) {
	with (FieldObj) {
		if (value == defaultValue && OnOrOff) {
			value = '';
			style.color = '#000000';
		}
		else if (value == '' && !OnOrOff) {
			value = defaultValue;
			style.color = '#909090';
		}
	}
}

// opacity() and changeOpac() functions from http://brainerror.net/scripts/javascript/blendtrans/
function opacity(id, opacStart, opacEnd, millisec) {
    
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
        
    } else if(opacStart < opacEnd) {
    
        for(i = opacStart; i <= opacEnd; i++) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

// change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}

// REMOVES LEADING ZERO(S) FROM NUMBER
function JS_removeLeadingZeros(number) {
	if (String(number).substr(0, 1) == "0" && String(number).substr(1) != "0")
		return String(number).substr(1);
	else
		return number;
}

// GETS A SPECIFIED GET VARIABLE FROM A GIVEN OR CURRENT URL
function fetchGETVar(GETVar, OverrideURL) {
	
	// Figure out what URL to use and then parse out the unnecessary parts
	UseURL = (OverrideURL)?OverrideURL:document.location.href;
	if (UseURL.indexOf('?') != -1 && UseURL.indexOf(GETVar) != -1) {
		URLArray      = UseURL.split('?');
		QueryStrArray = URLArray[1].split('&');
		
		// Set array of get vars
		GETVarArray = new Array(QueryStrArray.length);
		
		// Set the array values
		for (i in QueryStrArray) {
			CurrentVarSplit = QueryStrArray[i].split('=');
			CurrentVarName  = CurrentVarSplit[0];
			CurrentVarValue = CurrentVarSplit[1];
			eval('GETVarArray[\'' + CurrentVarName + '\'] = CurrentVarValue;');
		}
		
		if (GETVar)
			return GETVarArray[GETVar];
	}
	else
		return null;
}
