<!--// 
//////////////////////////////////////////////////////////////////
// 	This file and all contents herin are property of: 			//
//  	Peters Consulting & ManovrareSoft Software Solutions	//
//  No changes can be made to this software by outside agencies	//
//	without express, written permission of this company. This 	//
//	file or any others can not be used for market research, or	//
//	to reverse engineer											//
//																//
//	Global non-specific js functions							//
//																//
// 	Workflow v1 10/15/2011										//
//////////////////////////////////////////////////////////////////

//'''''''''''''''''''VARIABLES'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''	
var GlobalMethod, GlobalxmlHttp, GlobalAppend = false, timedouturl = "index.php", printView = false;
//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''	

///////////////////////////////////////////////////////////////////
// Basic functions
///////////////////////////////////////////////////////////////////
function pageGo()
{
	clock(); //Instantiates clock on the dashboard
	fancyCall(); //Attaches to all .fancybox links
	checkVersion(); //checks the system's current file version and makes people re-login if the system has been updated.
}


function printPreview(sLink)
{	
	$('.logoandsearchcontainer').slideToggle(500);
	$('.outerTopNav').slideToggle(500);
	$('.footer').slideToggle(500);		
	$('#menu').slideToggle(500);	
	$('.divHide').slideToggle(500);	
	$('.searchQuestionSection').slideToggle(500);	
	$('img').slideToggle(500);
	$('select').slideToggle(500);
	$('input').slideToggle(500);
	$('.blue_class_a').slideToggle(500);
	
	var data = $('.collapsed');
	data.find('td > div').slideToggle('slow');	
	
	if(printView)
	{
		//We probably have a search collapsed section showing, lets collpase it now:
		printView = false;
		$('#searchCollapse').slideToggle('slow');
	}
	else	
		printView = true;	
}

function expandCollapseAll()
{
	$('tr.collapsed').show().find('td').wrapInner('<div />');
	$('tr.collapsed').find('td > div').hide();
  
	$('tr.aExpandLink').click(function(){
		var data = $(this).next('tr.collapsed');
		var img = $(this).find(".imgExpandLink")[0].id;
		
		if($('#' + img).attr("src") == "Images/Icons/twirl_col.png")
			$('#' + img).attr("src", 'Images/Icons/twirl_exp.png')
		else
			$('#' + img).attr("src", 'Images/Icons/twirl_col.png');
			
		data.find('td > div').slideToggle('slow');
	});  
	
	$('.aExpandCollapseAll').click(function(){
		
		var newSrc, newText;
		var img = $(this).find("img")[0];

		if(img.src.search(/twirl_col.png/i)>-1)
			newSrc = (img.src).replace(/twirl_col/i, "twirl_exp");
		else
			newSrc = (img.src).replace(/twirl_exp/i, "twirl_col");
		
		img.src = newSrc;	
		$(".imgExpandLink").attr("src", newSrc);	
			
		var data = $('.collapsed');
		data.find('td > div').slideToggle('slow');
	});
}

function fancyCall()
{
	$('.fancybox').fancybox({ 
		'href'			: 	this.href, 
		'width' 		: 	'98%', 
		'height' 		: 	'98%', 
		'autoScale' 	: 	false, 
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	200, 
		'speedOut'		:	500, 
		'type' 			: 	'iframe' 
	});
}


function checkVersion()
{
	$.get("formAjax.php?Action=getsession&var=SystemVersion", function(SystemVersion)
	{
		$.get("formAjax.php?Action=getsession&var=SyncSystemVersion", function(SyncSystemVersion)
		{
			if(SystemVersion != SyncSystemVersion)
			{		
				$.get("formAjax.php?Action=getsession&var=SyncSystemRequireRestart", function(SyncSystemRequireRestart)
				{
					if(SyncSystemRequireRestart =='true')
					{
						msg = 'The system has been updated from v' + SystemVersion + ' to v' + SyncSystemVersion + '. It is required that you re-login or the system may behave unexpectedly.\n\n\nPress "Ok" to re-login or "Cancel" to continue on this page.';
						result = confirm(msg);	
						if(result)
							window.location = 'index.php?Logout=true';
					}
				});
			}
		});
	});
}



// jCron Control
//	Simple to use plugin based on gentle select and our favorit linux tool crontabs!
function jCron(values, id)
{
	if(null != values && undefined != values && values != '' )
		initVals = values;
	else
		initVals = "0 7 1 * *";	
		
	$('#' + id + 'Holder').hide();
	
    $(document).ready(function() {
        $('#' + id).cron({
            initial: initVals
        });
    });	
	
	$('#' + id + 'Holder').slideToggle('slow');
	
}

///////////////////////////////////////////////////////////////////
// Dynamic Form functions
///////////////////////////////////////////////////////////////////

function handleAutoDrops(obj)
{
	objID = obj.id;
	if(obj.options[obj.selectedIndex].value != "" || objID == "AssignedTo")
	{	
		switch(objID)
		{
			case "Department":
				// Department drop down filters ALL others
				//	Sub-Tenant
				//	Location	
				//	Unit				
				TenantID = getIndexValue("Department");
				AAdvWait('formAjax.php?Action=getsubtenant&Element=Location&TenantID=' + TenantID, 'evalIt');
				AAdvWait('formAjax.php?Action=getproperty&Element=Location&TenantID=' + TenantID, 'evalIt');
				
				PropertyID = getIndexValue("Location");
				UnitID = getIndexValue("Unit"); //We want the current unit because the tenant may have moved out, so we pass it to the script 
												//and if the unit ID exists in the list we build again, then we will select it.
				AAdvWait('formAjax.php?Action=getunit&Element=Location&UnitID=' + UnitID + '&PropertyID=' + PropertyID + '&TenantID=' + TenantID, 'evalIt');

				//If we have a property id, we need to filter out the other three drop downs for techs. 
				//	We don't want anyone selecting anything they shouldn't
				//	Made in to a function
				updateAssignedUsers(PropertyID);
				break;
				
			case "SubTenant":
				// Sub-Tenant drop down filters ALL others
				//	Tenant
				//	Location
				//	Unit			
				SubTenantID = getIndexValue("SubTenant");
				AAdvWait('formAjax.php?Action=gettenant&Element=Location&SubTenantID=' + SubTenantID, 'evalIt');
				
				TenantID = getIndexValue("Department");
				AAdvWait('formAjax.php?Action=getproperty&Element=Location&SubTenantID=' + SubTenantID + '&TenantID=' + TenantID, 'evalIt');
				
				PropertyID = getIndexValue("Location");	
				AAdvWait('formAjax.php?Action=getunit&Element=Location&PropertyID=' + PropertyID + '&TenantID=' + TenantID, 'evalIt');
				
				//If we have a property id, we need to filter out the other three drop downs for techs. 
				//	We don't want anyone selecting anything they shouldn't
				//	Made in to a function
				updateAssignedUsers(PropertyID);
				
				break;
				
			case "Location":
				// Location drop down filters ALL others
				//	Tenant
				//	Sub-Tenant
				//	Unit	
				PropertyID = obj.options[obj.selectedIndex].value;
				AAdvWait('formAjax.php?Action=gettenant&Element=Location&PropertyID=' + PropertyID, 'evalIt');
				AAdvWait('formAjax.php?Action=getsubtenant&Element=Location&PropertyID=' + PropertyID, 'evalIt');
				AAdvWait('formAjax.php?Action=getunit&Element=Location&PropertyID=' + PropertyID, 'evalIt');
				//If we have a property id, we need to filter out the other three drop downs for techs. 
				//	We don't want anyone selecting anything they shouldn't
				//	Made in to a function
				updateAssignedUsers(PropertyID);				
				break;
				
			case "Unit":
				// Unit drop down filters ALL others
				//	Tenant
				//	Sub-Tenant
				//	Location	
				UnitID = obj.options[obj.selectedIndex].value;
				AAdvWait('formAjax.php?Action=getproperty&Element=Location&UnitID=' + UnitID, 'evalIt');
				
				PropertyID = getIndexValue("Location");			
				AAdvWait('formAjax.php?Action=gettenant&Element=Location&UnitID=' + UnitID +'&PropertyID=' + PropertyID, 'evalIt');

				TenantID = getIndexValue("Department");
				AAdvWait('formAjax.php?Action=getsubtenant&Element=Location&UnitID=' + UnitID +'&PropertyID=' + PropertyID+'&TenantID=' + TenantID, 'evalIt');

				//If we have a property id, we need to filter out the other three drop downs for techs. 
				//	We don't want anyone selecting anything they shouldn't
				//	Made in to a function
				updateAssignedUsers(PropertyID);
				break;
			
			case "Severity":
			
				needbyobj = document.getElementById("NeedByDate");
								
				if(null!= needbyobj && undefined != needbyobj.value)
				{
					var now = new Date();
					strDate =  (now.getMonth()+1) + '/' + now.getDate() + '/' + now.getFullYear();
					newDate = (now.getMonth()+1) + '/' + now.getDate() + '/' + now.getFullYear();
				
					switch(obj.options[obj.selectedIndex].value)
					{
						case "1":
							//High + 3 days
							newDate = AddDaysToDate(strDate, 3);
							break;
						case "2":
							//Low + 2 weeks
							newDate = AddDaysToDate(strDate, 14);			
							break;
						case "3":
							//Normal + 1 week
							newDate = AddDaysToDate(strDate, 7);			
							break;
						
						case "4":
							//Normal + 1 week
							newDate = AddDaysToDate(strDate, 0);			
							break;
					}
					needbyobj.value = (newDate.getMonth()+1) + '-' + newDate.getDate() + '-' + newDate.getFullYear();
				}
				break;
				
			case "AssignedTo":
			
				statusObj = document.getElementById("Status");
				sStatusObjVal = getIndexValue("Status");
				
				if(sStatusObjVal == "3" || sStatusObjVal == "5")
				{
					switch(obj.options[obj.selectedIndex].value)
					{
						case "0":
						case "":
							for (x=0; x<statusObj.length; x++)
							{
								if (statusObj[x].value == "3")
									statusObj[x].selected = true;
							}	
							
							//Also need to check to make sure the other fields such as SecondaryStaff and Technician is blanked out, 
							// if not blank them out, we cannot have a technician or secondary staff without a priomary staff member assigned.
							SecondaryObj = document.getElementById("SecondaryStaff");
							TechnicianObj = document.getElementById("Technician");
							// clear them out!
							SecondaryObj.selectedIndex = 0;
							TechnicianObj.selectedIndex = 0;
							
							break;		
						
						default:
							for (x=0; x<statusObj.length; x++)
							{
								if (statusObj[x].value == "5")
									statusObj[x].selected = true;
							}	
							break;
					}
				}
				break;	
				
			case "SecondaryStaff":
			case "Technician":
				//Get and set the values of the AssignedTo obj for processing.
				AssignedToObj = document.getElementById("AssignedTo");
				AssignedToVal = AssignedToObj.options[AssignedToObj.selectedIndex].value;
				//if it falls in to here, everything is all good!
				if((null != AssignedToVal && undefined != AssignedToVal) && AssignedToVal != "0" && AssignedToVal != "")
				{
					
				}
				else
				{
					//tell the user the mistake they had made!
					if(obj.id == "SecondaryStaff")	
						alert("You may not assign Secondary Staff until you have designated a Primary Staff member assigned to the task.\n\nPlease designate a Primary Staff member assigned to this task and try again.");						
					else
						alert("You may not assign a Vendor until you have designated a Primary Staff member assigned to the task.\n\nPlease designate a Primary Staff member assigned to this task and try again.");
					//unselect the object until the errors are cleaned up!
					obj.selectedIndex = 0;
				}
				
				break;
					
			case "Status":
				// All this does is listen for "Reoccurence" status. If it has it selected then it will go ahead
				// show use our cron tab control	

				jCronTab = document.getElementById("jCron");
				StatusVal = obj.options[obj.selectedIndex].value;
				
				if(StatusVal == "6")
				{
					jCron("", "jCron");
				}
				else if(null != jCronTab)
				{
					$('#jCronHolder').hide();			
					jCronTab.innerHTML = "";
				}
				break;				
		}
	}
}



//This is for projects and work orders.  When someone selects a property, tenant, sub tenant, or unit... then we have enough information to filter down the 
//	staffing lists because not everyone can see everything ya know?
function updateAssignedUsers(PropertyID)
{
	if(parseInt(PropertyID) > 0)
	{
		var objAss = document.getElementById('AssignedTo');
		var objSec = document.getElementById('SecondaryStaff');
//	We have to shut off techs right now, but they may be back later?...
//		var objTech = document.getElementById('Technician'); 
	
		if(undefined != objAss && null != objAss)
			AAdvWait('formAjax.php?Action=getAssigned&Element=AssignedTo&PropertyID=' + PropertyID, 'evalIt');
		
		if(undefined != objSec && null != objSec)
			AAdvWait('formAjax.php?Action=getSecondary&Element=SecondaryStaff&PropertyID=' + PropertyID, 'evalIt');

//	Techs can't recieve emails yet.	
//		if(undefined != objTech && null != objTech)
//			AAdvWait('formAjax.php?Action=getTechs&Element=Technician&PropertyID=' + PropertyID, 'evalIt');	
	}
}


function getIndexValue(strID)
{
	intID = 0;
	if(ifExists(strID))
	{
		obj = document.getElementById(strID);
		
		if(obj.selectedIndex > -1)					
			intID = obj.options[obj.selectedIndex].value;
	}
	return intID;
}

function ifExists(strObj)
{
	if (undefined != document.getElementById(strObj) && null != document.getElementById(strObj))
		return true;
	else
		return false;	
}

function addOption(selectbox, text, value)
{
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function CheckDynErrors()
{
	var Form = document.getElementById("myForm");	
	
	if(undefined != Form && null != Form)
	{
		var ErrorMessage = '';		
		var arrID = (Form.ReqdFields.value).split("~");
		var arrTxt = (Form.ReqdText.value).split("~");
		var lngth = (arrID.length-1);
		var firstObject = '';
		
		for (i=0;i<=lngth;i++)
		{
			if(undefined != document.getElementById(arrID[i]) && null != document.getElementById(arrID[i]) )
			{
				if(DetermineValue(document.getElementById(arrID[i]), document.getElementById('type'+arrID[i]).value) == false)
				{				
					if(ErrorMessage == '')
						document.getElementById(arrID[i]).focus();
					
					highlightErrors(document.getElementById(arrID[i]));		
					
					ErrorMessage += "\"" + arrTxt[i] + "\" is not defined or incorrectly formatted.\n";
					
					
				}
				else if(arrID[i] == "ContactCaptcha")
				{
					if(url.search(/localhost/i) > 0 || url.search(/msws1/i) > 0  || url.search(/trunk/i) > 0 || url.search(/pbserver/i) > 0 || url.search(/mspcadmin/i) > 0 )
						AWaitaddon = "";
					else
						AWaitaddon = "/";
					
					AWait(AWaitaddon + "Common/capchaCheck.php?val=" + document.getElementById(arrID[i]).value, "capVal");
					
					if(document.getElementById("capValInput").value != "true")
						ErrorMessage += "\"" + arrTxt[i] + "\" is incorrect.\n";	
				}
			}
			else	
				ErrorMessage += "\"" + arrTxt[i] + "\" is not defined.\n";
			
			
		}
		
		if (ErrorMessage != "")
		{
			alert("The following errors must be corrected before we will accept your request:\n\n" + ErrorMessage + '\nPlease review and make corrections as neccesary.');
			return false;			
		}
		else
			return true;
	}
	else
		alert("An error occured. Please contact us by phone.");	
	
}


function highlightErrors(obj)
{
	obj.style.backgroundColor ='yellow';
}


function DetermineValue(obj, strType)
{

	switch(strType)
	{
		case "select":
		case "selectmultiple":
		case "states":
			return Select(obj);
			break;
			
		case "textbox":	
		case "readonly":	
		case "textarea":	
		case "date":			
		case "captcha":	
			
			return Textbox(obj);
			break;	
			
		case "checkbox":	
			return Checkbox(obj);
			break;

		case "radio":	
			return Radio(obj);
			break;
		
		default: 
			return false;
			break;
	}
	
}

function Textbox(obj)
{
	if(obj.value != "")
	{
		if(obj.id == 'UpdateMins')
		{
			if(parseInt(obj.value))
				return true;
			else
				return false;
		}
		else
			return true;	
	}
	else
		return false;
}

function Radio(obj)
{
	if(!obj)
		return "";
	
	radList = document.getElementsByName(obj.name);
	var radioLength = radList.length;

	for(var i = 0; i < radioLength; i++) 
	{
		if(radList[i].checked) 
			return true;
		
	}
	return "";
}

function Checkbox(obj)
{
	var Selected = false;
	for (var i=0; i < obj.length; i++)
	{
		if (obj[i].checked && Selected == false)
			Selected = true;
	}

	return Selected;
}

function Select(obj)
{
	//if(obj.selectedIndex > 0)
	//{
		if(obj.options[obj.selectedIndex].value != "" && obj.options[obj.selectedIndex] != "")
			return true;
		else
			return false;
	//}
	//else
	//	return false;
}



//Simple JS loop to process forms submitted with AJAX
function CheckAjaxForm(url, element, formName)
{	
	var Form = document.getElementById(formName);
	var params = "";
	var newURL = "";
	var x = 0;	
	
	intFormEl =  url.indexOf("Form=true", 0);
	
	if(intFormEl > 0 )
		url = url.substring(0, intFormEl-1);

	newURL = url + "&Form=true";
	var CurrentCheckGroup = "";
	for(i=0; i<Form.elements.length; i++)
	{
		if((Form.elements[i].id).search(/asmSelect/i) < 0)
		{
			x = 0;
			if(Form.elements[i].type == "text" || Form.elements[i].type == "textarea" || Form.elements[i].type == "hidden"  || Form.elements[i].type == "readonly" )
			{	
				if(Form.elements[i].id =='UpdateMins')
				{
					params += "&" +Form.elements[i].id + "=";
					
					if(parseInt(Form.elements[i].value))
						params += parseInt(Form.elements[i].value);		
					else
						params += 0;	
				}
				else if(Form.elements[i].value != '')
				{
					params += "&" +Form.elements[i].id + "=";
					params += clean(Form.elements[i].value);						
				}
			}
			else if(Form.elements[i].type == "radio")
			{
				if(Form.elements[i].checked)
				{
					params += "&" +Form.elements[i].id + "=";
					params += clean(Form.elements[i].value);
				}
			}
			
			else if(Form.elements[i].type == "checkbox")
			{
				if(Form.elements[i].checked == true)
				{
					if(CurrentCheckGroup == "") // First loop
					{ 
						CurrentCheckGroup = Form.elements[i].id;
						params += "&" +Form.elements[i].id + "="; // Start new param
						chkGroup = 0										
					}
					else if(CurrentCheckGroup == Form.elements[i].id)
					{	
					
					}
					else if(CurrentCheckGroup != Form.elements[i].id)
					{
						CurrentCheckGroup = Form.elements[i].id;
						params += "&" +Form.elements[i].id + "="; // Start new param
						chkGroup = 0					
					}
					
					if(chkGroup > 0)
						params += ',';
					
					params += clean(Form.elements[i].value);	
				
					chkGroup++;
				}
			}		
			else if(Form.elements[i].type == "select-one")
			{
				params += "&" +Form.elements[i].id + "=";
				params += clean(Form.elements[i].options[Form.elements[i].selectedIndex].value);
			}
			else if(Form.elements[i].type == "select-multiple")
			{
				
				tempFrm = Form.elements[i];
				lc = 0;
	
				for (x=0; x<tempFrm.length; x++)
				{
					
					if (((Form.elements[i].type == "select-multiple") && tempFrm[x].selected))
					{
						comma = '';
						if(lc>0)
							comma =',';
						else
							params += "&" +Form.elements[i].id + "=";
							
						params += comma + tempFrm[x].value;
						lc++;	
					}
				}		
			}
		}
	}
	
	
	if(params != "")
	{
		if(newURL.search(/Ajax/i) > 0)	
			AWait(newURL + params, element);
		else
			window.location = newURL + params;
	}


	return false;
} 


///////////////////////////////////////////////////////////////////
// Instant Search functions
///////////////////////////////////////////////////////////////////
function onSearch(obj)
{
	var value;
	value = obj.value;
	
	if(value == 'instant search')
		obj.value = '';
	else if(value == '')
		obj.value = 'instant search';
	
}

function performInstantSearch(txtObj)
{
	obj =  document.getElementById(txtObj);
	if(null != obj)
	{
		if(undefined != obj.value)
		{
			if('instant search' != obj.value)
				doSearch(obj.value);
			else
				alert('Please enter a valid search.');		
		}
		else
			alert('Please enter a valid search.');
	}
	else
		alert('Instant Search has failed, please reload the page to reset search.');		
}

function DoSearch(val)
{
	//I want to make this thick box functionality.	
	//Opens up the iframe onclick.
	//searches the database, results in iFrame.
}

///////////////////////////////////////////////////////////////////
// Expand/Collapse functions
///////////////////////////////////////////////////////////////////

function dynExpandCollapse(objCalling, objTarget)
{
	var currentClass;
	var currentImg;
	var currentTitle;
	currentClass = objTarget.className;
	
	if(currentClass.search(/divShow/) > -1 )
	{
		currentImg = "Images/Icons/twirl_col.png";
		currentTitle = "Click to Expand";		

		currentClass = currentClass.replace(/divShow/i, "divHide");
	}
	else
	{
		currentImg = "Images/Icons/twirl_exp.png";
		currentTitle = "Click to Collapse";
		currentClass = currentClass.replace(/divHide/i, "divShow");
	}
		
	objCalling.src = currentImg;
	objCalling.title = currentTitle;
	objTarget.className = currentClass;
	
}


///////////////////////////////////////////////////////////////////
// Session Timer. Very Simple. Very Easy
///////////////////////////////////////////////////////////////////
function Minutes(data) 
{
	for (var i = 0; i < data.length; i++)
	{
		if (data.substring(i, i + 1) == ":")
			break;
	}
	return (data.substring(0, i));
}

function Seconds(data) 
{
	for (var i = 0; i < data.length; i++)
	{
		if (data.substring(i, i + 1) == ":")
			break;
	}
	return (data.substring(i + 1, data.length));
}

function Display(min, sec) 
{
	var disp;
	if (min <= 9) 
		disp = " 0";
	else 
		disp = " ";
		
	disp += min + ":";
	if (sec <= 9) 
		disp += "0" + sec;
	else 
		disp += sec; 
		
	return (disp);
}

function timeIt() 
{
	Down();
}


///////////////////////////////////////////////////////////////////
// Menu functions (hovers, dropdowns etc.)
///////////////////////////////////////////////////////////////////

function P7_ExpMenu()
{	
	var i, k, g, lg, c;
	var r=/\s*p7hvr/;
	var nn='';
	var cs='p7hvr';
	var bv='p7menubar';

	//Only will count up to ten
	for(i=0;i<10;i++)
	{
		//g is the menubar overall list
		g = document.getElementById(bv+nn);
		
		//Check to see if there is a menu bar here
		if(g)
		{
			//in this class lets get the array of List-Items
			lg = g.getElementsByTagName("LI");
			
			//If there is List-Items
			if(lg)
			{
				//How many are there, lets loop through them all
				for(k=0;k<lg.length;k++)
				{
					//dynamic function simulating the css active/hover on an LI (doesn't exist in IE)
					lg[k].onmouseover=function()
					{
						//Whats the name of the class
						c=this.className;
						//replace is with the class its supposed to be
						cl=(c)?c+' '+cs:cs;
						
						this.className=cl;
					};
						
					//dynamic function simulating the css off active/off hover on an LI (doesn't exist in IE)
					lg[k].onmouseout=function()
					{
						//Whats the name of the class
						c = this.className;
						
						//replace is with the class its supposed to be
						this.className=(c)?c.replace(r,''):'';
					};
				}
			}
		}
		nn=i+1;
	}
}

function Down() 
{ 
	sec--;      
	if (sec == -1) 
		sec = 59; min--; 

	window.status = "Session will time out in: " + Display(min, sec);
	
	if (min == 0 && sec == 0) 
	{
		alert("Your session has timed out.");
		window.location.href = timedouturl;
	}
	else 
		down = setTimeout("Down()", 1000);
}



///////////////////////////////////////////////////////////////////
// AJAX functions
///////////////////////////////////////////////////////////////////

//Cleaning function for URLS
function clean(stringToClean)
{
	stringToClean.replace(/&/i, "|amp|");
	stringToClean.replace(/\?/i, "|ques|");
	return stringToClean;
}

function CleanParams(frmString)	
{
	try
	{			
		if((Left(frmString,1) == "?") || (Left(frmString,1) == "&"))
			frmString = Right(frmString,String(frmString).length-1);	

		return frmString;
	}
	catch(e)
	{

	}
}

function ABasic(strUrl, strElement)
{  
	try
	{	
		var xmlHttp, blnAppend=false;
		xmlHttp = GetXmlHttpObject();
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
				PopulateResponse(xmlHttp.responseText, strElement, false);
		}
					
		if(strUrl.search(/divElement=/i) <= 0)
			strUrl += "&divElement=" + strElement;
			
		if(strUrl.search(/SID=/i) <= 0)
			strUrl += "&SID=" + IDMaker();					
					
		var url = strUrl;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);	
	}
	catch(e)
	{
	}		
}
	
function AWait(strUrl, strElement)
{  
	var xmlHttp, blnAppend=false;
	xmlHttp = GetXmlHttpObject();					
	
	if(strUrl.search(/divElement=/i) <= 0)
		strUrl += "&divElement=" + strElement;
		
	if(strUrl.search(/SID=/i) <= 0)
		strUrl += "&SID=" + IDMaker();	
					
	var url = strUrl;
	xmlHttp.open("GET", url, false);
	xmlHttp.send(null);	
	PopulateResponse(xmlHttp.responseText, strElement, false);
}	

//Advanced Ajax post.  Will eval() javascript.  But you can not mix.
function advPost(strUrl, nvParams, strElement, evalIt)
{	
	nvParams = CleanParams(nvParams);
	try
	{
		var xmlHttp=GetXmlHttpObject();	
		if(null != xmlHttp)
		{			
			if(strUrl.search(/divElement=/i) <= 0)
				strUrl += "&divElement=" + strElement;
				
			if(strUrl.search(/SID=/i) <= 0)
				strUrl += "&SID=" + IDMaker();		
						
			xmlHttp.open("POST", strUrl, true);
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", nvParams.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.onreadystatechange = function()
			{
				if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
					PopulateResponse(xmlHttp.responseText, strElement, evalIt);
					
			};
			xmlHttp.send(nvParams);
			
		}			
	}
	catch(e)
	{
	}
}

//Advanced Ajax post.  Will eval() javascript.  But you can not mix.
function advPostWait(strUrl, nvParams, strElement, evalIt)
{	
	nvParams = CleanParams(nvParams);
	try
	{
		var xmlHttp=GetXmlHttpObject();	
		if(null != xmlHttp)
		{
			if(strUrl.search(/divElement=/i) <= 0)
				strUrl += "&divElement=" + strElement;
				
			if(strUrl.search(/SID=/i) <= 0)
				strUrl += "&SID=" + IDMaker();			
		
			xmlHttp.open("POST", strUrl, false);
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", nvParams.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.onreadystatechange = function()
			{
				if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
					PopulateResponse(xmlHttp.responseText, strElement, evalIt);
					
			};
			xmlHttp.send(nvParams);
			
		}			
	}
	catch(e)
	{
	}
}
	
function AAdv(strUrl, strElement)
{  
	try
	{	
		var xmlHttp, blnAppend=false;
		xmlHttp = GetXmlHttpObject();
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
				PopulateResponse(xmlHttp.responseText, strElement, true);
				
		}
		
		if(strUrl.search(/divElement=/i) <= 0)
			strUrl += "&divElement=" + strElement;
			
		if(strUrl.search(/SID=/i) <= 0)
			strUrl += "&SID=" + IDMaker();
								
		var url = strUrl;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);	
	}
	catch(e)
	{

	}		
}	

function AAdvWait(strUrl, strElement)
{  
	try
	{	
		var xmlHttp, blnAppend=false;
		xmlHttp = GetXmlHttpObject();
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
				PopulateResponse(xmlHttp.responseText, strElement, true);
				
		}
		
		if(strUrl.search(/divElement=/i) <= 0)
			strUrl += "&divElement=" + strElement;
			
		if(strUrl.search(/SID=/i) <= 0)
			strUrl += "&SID=" + IDMaker();
		
		var url = strUrl;
		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);	
	}
	catch(e)
	{

	}		
}

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)	
	{
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				return null;
			}
		}
	}
	return xmlHttp;
}

function Left(str, i)
{
	try
	{
		if(i <= 0)
			return null;	

		else if(i > String(str).length)
			return str;
		
		else
			return String(str).substring(0,i);
		
	}
	catch(e)
	{

	}			
}	
	
function Right(str, i)
{
	try
	{
		if(i <= 0)
			return null;	
		else if(i > String(str).length)
			return str;
		else
			{
				var xLen = String(str).length;			
				return String(str).substring(xLen, xLen - i);
			}
	}
	catch(e)
	{

	}	
}

function IDMaker()
{
	try
	{
		return Left(Math.random(),4);
	}
	catch(e)
	{

	}		
}

function PopulateResponse(TheResponse, Element, evalIt)
{		
	if(evalIt == true)
	{
		try
		{
			eval(TheResponse);
		}
		catch(e)
		{
			//alert("Problem evaluating AJAX returned javascript. Please report this issue and steps to recreate to Support.\n\n" + e.type + '\n\n' + e.description);
		}
	}
	else
	{
		if (null != Element && undefined != Element && Element != "nothing" && Element != "Logout")
		{
			if (Element != "")
			{
				var DOMElement = document.getElementById(Element);
				DOMElement.innerHTML = "";
				var t = document.createElement('div');
				t.innerHTML = TheResponse;
				DOMElement.appendChild(t);			
			
				//We need to eval and script tags returned.
				if(TheResponse.search(/<script/i) > -1)
				{						
					l = 0;
					newStart = 0;
					LookHere = TheResponse;
					intCloseTag = 0;

					while(LookHere.search(/<script/i) > -1)
					{
						
						intStartScript = LookHere.indexOf("<script", newStart);
						intStartCloseBrace = LookHere.indexOf(">", intStartScript);
						intCloseTag =  LookHere.indexOf("</script>", intStartCloseBrace);
						
						if((intStartCloseBrace+1) == intCloseTag)
						{
							newStart = intCloseTag;
							LookHere = LookHere.substring((newStart+9), LookHere.length);								
						}
						else
						{
							//Give us the next piece to look at
							InnerScript = LookHere.substring(intStartCloseBrace+1, intCloseTag);	
							
							//remove that same piece from above so that we don't eval it again.
							LookHere = LookHere.substring(intCloseTag+9, LookHere.length);
							
							//Get rid of pesky html comments
							InnerScript = InnerScript.replace(/<!--/,'');
							InnerScript = InnerScript.replace(/\/\/-->/,'');							
							
							if(InnerScript != '')
							{
								if(InnerScript.search(/src=/i) <= 0 && InnerScript.replace(/ /ig, "") != "")
								{
									if((InnerScript.search(/jQuery/i) > -1 || InnerScript.search(/$\(/i) > -1 ||  InnerScript.search(/.fancybox/i) > -1 || InnerScript.search(/asmSelect/i) > -1)  && (InnerScript.search(/function/i) == -1  || InnerScript.search(/asmSelect/i) > -1) )
										InnerScript = 'window.' + InnerScript;
								
									else if(InnerScript.search(/function/i) > -1)
									{
										stripFuncStart = (InnerScript.indexOf("function ")) + 9;
										stripFuncEnd = InnerScript.indexOf("(",stripFuncStart);	
										functionName = InnerScript.substring(stripFuncStart, stripFuncEnd);
										InnerScript = InnerScript.substring(stripFuncEnd, InnerScript.length);
										InnerScript = 'window.'+functionName+ ' = function' + InnerScript;
									}
									
									if(InnerScript != '' )
										eval(InnerScript);		

								
									InnerScript = "";
									newStart = 0; //Reset position to zero so I can go through the response after I removed the script tag
							
								}
								else
									newStart = 0; //Reset position
								
							}
						}
						l++;
					}
				
					//Call anytime!
					//anytime();				
				}
			}
		}
		else if(Element == "Logout")
			window.location = "Default.php";			
		
		else if(Element != "nothing")
			window.location = window.location;
						
	}
	
}



//expand and collapse divs mostly
function HideShowDiv(sDivName, anchorObj, sOriginalText)
{
	obj = document.getElementById(sDivName);
	if(undefined != obj.id)
	{
		if(obj.className == "divHide")
		{
			obj.className = "divShow";
			anchorObj.innerHTML	= sOriginalText + "<img src='Images/Icons/expanded.gif' alt='Collapse' />";
		}
		else
		{
			obj.className = "divHide";		
			anchorObj.innerHTML	= sOriginalText + " <img src='Images/Icons/collapsed.gif' alt='Expand' />";
		}
	}
}




//expand and collapse divs mostly used for search
function HideShowSearch(sDivName, anchorObj, sOriginalText)
{
	obj = document.getElementById(sDivName);
	if(undefined != obj.id)
	{
		if(obj.className == "divHide")
		{
			$("#"+sDivName).slideToggle('slow');
			anchorObj.innerHTML	= "<img src='Images/LessOpt.png' alt='Collapse Search' />";
		}
		else
		{	
			$("#"+sDivName).slideToggle('slow');
			anchorObj.innerHTML	= "<img src='Images/MoreOpt.png' alt='Expand Search' />";
		}
	}
}

//Grid functions
function onMouseOver(rowId, rowColor)
{
	document.getElementById(rowId).style.background = rowColor;                
}            

function onMouseOut(rowId, rowColor)
{
   	document.getElementById(rowId).style.background = rowColor;                
}            

function onMouseClickRow(unique_prefix, row_id, row_color, row_color_light, row_color_dark)
{
   if((row_id % 2) == 0) row_color_back = row_color_dark;
   else row_color_back = row_color_light;
   if(document.getElementById(unique_prefix+'checkbox_'+row_id))
   {
      if(document.getElementById(unique_prefix+'checkbox_'+row_id).checked == true){
         document.getElementById(unique_prefix+'checkbox_'+row_id).checked = false;
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color_back;                        
      }
	  else
	  {
         document.getElementById(unique_prefix+'checkbox_'+row_id).checked = true;
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;
      }
   }else{
      document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;
   }
}

function onMouseOverRow(unique_prefix, row_id, row_color, row_selected_color_dark)
{
   if(document.getElementById(unique_prefix+'checkbox_'+row_id)){
      if(document.getElementById(unique_prefix+'checkbox_'+row_id).checked != true){
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;
      }else{
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_selected_color_dark;                    
      }
   }else{
      document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;                
   }
}            

function onMouseOutRow(unique_prefix, row_id, row_color, row_color_selected)
{
   if(document.getElementById(unique_prefix+'checkbox_'+row_id)){
      if(document.getElementById(unique_prefix+'checkbox_'+row_id).checked != true){
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;
      }else{
         document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color_selected;
      }
   }else{
      document.getElementById(unique_prefix+'row_'+row_id).style.background = row_color;                
   }
}      



function AddDaysToDate(date, days)
{
	date = new Date(date);
	
	date.setDate(date.getDate() + days)
	return date;
}


function clock() 
{

	var digital = new Date();
	var hours = digital.getHours();
	var minutes = digital.getMinutes();
	var seconds = digital.getSeconds();
	
	var day = digital.getDate();
	var month = digital.getMonth() + 1;
	var year = digital.getFullYear();
		
	var amOrPm = "AM";
	
	if (hours > 11) 
		amOrPm = "PM";
	
	if (hours > 12) 
		hours = hours - 12;
	
	if (hours == 0) 
		hours = 12;
	
	if (minutes <= 9) 
		minutes = "0" + minutes;
	
	if (seconds <= 9) 
		seconds = "0" + seconds;
		
	var divClock = document.getElementById("divClock");	
	var divClock2 = document.getElementById("divClockPrint");	
	
	if(null != divClock && undefined != divClock)
	{
		dispTime = hours + ":" + minutes + ":" + seconds + " " + amOrPm + " " + month + "/" + day + '/' + year;
		divClock.innerHTML = dispTime;
		
		if(null != divClock2 && undefined != divClock2)
			divClock2.innerHTML = dispTime;
		
		setTimeout("clock()", 1000);
	}
}


function checkASM(c)
{
	if(c.type == 'select-multiple')
	{
		$(document).ready(function() {$("select[multiple]").remove(c)})	

		$(document).ready(function() {	
			$("select[multiple]").asmSelect({
				addItemTarget: 'bottom',
				animate: true,
				highlight: true
			});
			})		
	}
}


$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

//-->




