
/* ----------- post handler (app specific) ------------- */

	function postHandler(divName) {
		
		switch(divName){
			
			case "TCU_ticketUpdateResults":
				showStatus(divName);
				break;

		}
	}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}


/* NOTE: Everything past this point is abstract and should be included in a common script */

function getHTTPObject() { var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } var http = getHTTPObject(); // We create the HTTP Object

/* ---------------- process form ----------------------- */	

	function processForm(requiredFields,requiredDateFields,requiredNumericFields,requiredPhoneFields,dateTextFields,numericTextFields,stringTextFields,selectFields,bitFields,logFields,processFile,processType,returnDiv,bNewWindow,submitButton,bSilent,bPost,checkBoxFields)	{
		// requiredFields - list of all the generic required fields - they will be checked for "is present"
		// requiredDateFields - list of required date fields - checked for date validity and presence
		// requiredNumericFields - list of required numeric fields - their value has to be a number greater than 0
		// requiredPhoneFields - list of required phone fields - checked for 10 digits - dashes and parentheses are ok
		// dateTextFields - list of date input fields in the form
		// numericTextFields - list of text input fields in the form with numeric values
		// stringTextFields - list of text input fields in the form with varchar values
		// selectFields - list of select fields in the form
		// bitFields - list of checkbox / radio button fields
		// logFields - list of fields that get logged
		// processFile - action file associated with this form
		// returnDiv - ID of div where results are displayed
		// bNewWindow - true if the results should be displayed in a new window
		// submitButton - the submit button to disable
		// bSilent - true if we should suppress errors and "waiting" messages
		// bPost - true if we should use the http "post" rather than get
		// checkBoxFields - list fields that are check boxes. They have a corresponding 'cb_' field with all possible suffix values in it. Ex: if the check box field edit_score has values 1,3,4, the field would be edit_score1/edit_score3/edit_score4. 

		// first disable the submit button to prevent multiple submits
		if (typeof submitButton!='undefined') {
			var submit = document.getElementById(submitButton)
			submitButton.disabled = true;
		}
		
		// check for silent mode
		if (typeof bSilent=='undefined') {
			bSilent = false;
		}
		
		// hide the status message to indicate a change
		if (bSilent) {
			hideStatus(returnDiv);
		} else {
			showStatus(returnDiv);
		}
		
		// add all the required fields to the url so we can do server side validation too,
		var str = requiredFields;
		var fileString = "";
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			requiredFields = str2;
			fileString = fileString + "&requiredFields="+requiredFields;
		}
		str = requiredDateFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			requiredDateFields = str2;
			fileString = fileString + "&requiredDateFields="+requiredDateFields;
		}
		
		str = requiredNumericFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			requiredNumericFields = str2;
			fileString = fileString + "&requiredNumericFields="+requiredNumericFields;
		}
		
		str = requiredPhoneFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			requiredPhoneFields = str2;
			fileString = fileString + "&requiredPhoneFields="+requiredPhoneFields;
		}

		// now validate the form before we do anything else
		var bValid = validateForm(requiredFields,requiredDateFields,requiredNumericFields,requiredPhoneFields,processType);
		if (!bValid) {
			return false;
		}
		
		fileString = processFile+ "?";
				
		var str = dateTextFields;
		if (str.length != 0)	{
			var str2 = replaceString(str,'',processType);
			dateTextFields = str2;
			fileString = fileString + "&dateTextFields="+dateTextFields;
		}

		str = numericTextFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			numericTextFields = str2;
			fileString = fileString + "&numericTextFields="+numericTextFields;
		}
		
		str = stringTextFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			stringTextFields = str2;
			fileString = fileString + "&stringTextFields="+stringTextFields;
		}
		
		str = selectFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			selectFields = str2;
			fileString = fileString + "&selectFields="+selectFields;
		}
		
		str = bitFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			bitFields = str2;
			fileString = fileString + "&bitFields="+bitFields;
		}
		
		str = logFields;
		if (str.length)	{
			str2 = replaceString(str,'',processType);
			logFields = str2;
			fileString = fileString + "&logFields="+logFields;
		}

		var IDobj = "";
		var IDindex = "";
		var IDfield = "";
		var fieldName = "";
		var IDvalue = "";
		var fieldList = "";
		var i=0;
		
		if (dateTextFields.length > 0)	{
			fieldList = dateTextFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				IDobj = document.getElementById(fieldName);
				IDvalue = IDobj.value;
				fileString = fileString + "&" + fieldList[i] + "=" + IDvalue;
			}
		}
		
		if (numericTextFields.length > 0)	{
			fieldList = numericTextFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				IDobj = document.getElementById(fieldName);
				IDvalue = IDobj.value;
				fileString = fileString + "&" + fieldList[i] + "=" + IDvalue;
			}
		}
		
		if (stringTextFields.length > 0)	{
			fieldList = stringTextFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				IDobj = document.getElementById(fieldName);
				// IDvalue = IDobj.value;
				// fileString = fileString + "&" + fieldList[i] + "=" + IDvalue;
				// clean the string and encode it
				var rawString = IDobj.value;
				IDvalue = cleanString(rawString);
				fileString = fileString + "&" + fieldList[i] + "=" + encodeURI(IDvalue);
			}
		}
		
		if (selectFields.length > 0)	{
			fieldList = selectFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				IDobj = document.getElementById(fieldName);
				IDindex = IDobj.selectedIndex;
				IDvalue = IDobj.options[IDindex].value;
				fileString = fileString + "&" + fieldList[i] + "=" + IDvalue;
			}
		}
		
		if (bitFields.length > 0)	{
			fieldList = bitFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				IDobj = document.getElementById(fieldName);
				if (IDobj.checked == true)	{
					IDvalue = 1;
				}	else	{
					IDvalue = 0;
				}
				fileString = fileString + "&" + fieldList[i] + "=" + IDvalue;
			}
		}

		// pass any checkbox values using the field name in a delimited string

		str = checkBoxFields.split(',');
		var j = 0;
		var cbField = '';
		var cbFieldStr = '';
		var cbFieldValStr = '';
		var fieldNameVal = '';
		var fieldStr = '';
		var tempFieldName = '';
		var tempField = '';
		var newfileString = '';
		if (checkBoxFields.length)	{
			// checkboxes are named thusly: [processType]fieldName[checkBoxIDvalue]
			// the suffixes - the checkbox ID values - are in the form in var cb_fieldName
			for (i=0; i<str.length; i=i+1)	{
				fieldNameVal = '';
				cbField = replaceString(str[i],'cb_',processType);
				cbFieldStr = document.getElementById(cbField);
				cbFieldValStr = cbFieldStr.value;
				fieldStr = cbFieldValStr.split(',');

				for (j=0; j<fieldStr.length; j=j+1)	{
					tempFieldName = str[i] + fieldStr[j];
					tempField = document.getElementById(tempFieldName);
					if (tempField.checked == true)	{
						if (fieldNameVal.length)	{
							fieldNameVal = fieldNameVal + ',' + fieldStr[j];
						}else	{
							fieldNameVal = fieldNameVal + fieldStr[j];
						}
					}
				}
				newfileString = newfileString + "&" + processType + replaceString(str[i],'',processType) +"="+fieldNameVal;
			}
			newfileString = newfileString + "&checkBoxFields="+checkBoxFields;
		}
		
		var urlFile = fileString.replace(/\'/g,"*");
		var urlFile2 = newfileString.replace(/\'/g,"*");
		// fileHandler(urlFile, returnDiv); 
		// yeOldefileHandler(urlFile, returnDiv); 

		if (bNewWindow) {
			window.open(urlFile,"_blank");
		} else {
			if(bPost){
				fileHandler(urlFile+urlFile2, returnDiv, bSilent, 'post'); 
			} else {
				fileHandler(urlFile+urlFile2, returnDiv, bSilent, 'get'); 
			}
		}
	}

/* ---------------- file handler ----------------------- */

 	function fileHandler(urlFile, container, bSilent, method) {
		gPars = getURLParams(urlFile);
		var url = getURL(urlFile);
 		var ajax = new Ajax.Updater(container, url,{
			method: method,
			parameters: gPars,
			onFailure: function(){reportError(bSilent)},
			onLoading: function(){statusMsg(container,bSilent)},
			onComplete: function(){postHandler(container)}
		});
 	}
 	
 	function reportError(bSilent) {
 		if(!bSilent){
 			alert('Update Failed: '+ http.status);
 			// wait a second then reload the page
 			// setTimeout(history.go(0), 1000);
 		}
	}
	
	function statusMsg(container,bSilent) {
		if (!bSilent) {
			var statusDiv = $(container);
			statusDiv.innerHTML = "<b>Loading....</b>";
		}
	}
 	
/* ---------------- validate form ----------------------- */

	function validateForm(requiredFields,requiredDateFields,requiredNumericFields,requiredPhoneFields,processType) {
    	var errs=0;
		var fieldName = "";
		var infoName = "";
		var fieldList = "";
		var i=0;
		 
    	// Check generic "is Present" fields
    	if (requiredFields.length > 0)	{
			fieldList = requiredFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				infoName = 'inf_'+fieldList[i];
				if (!validatePresent (document.getElementById(fieldName), infoName)) errs += 1; 
			}
		}
		
		// Check for date fields
		if (requiredDateFields.length > 0)	{
			fieldList = requiredDateFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				infoName = 'inf_'+fieldList[i];
				if (!validateDate (document.getElementById(fieldName), infoName, true)) errs += 1; 
			}
		}
		
    	// Check for numeric fields
		if (requiredNumericFields.length > 0)	{
			fieldList = requiredNumericFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				infoName = 'inf_'+fieldList[i];
				if (!validateNumber (document.getElementById(fieldName), infoName, true, 1)) errs += 1; 
			}
		}
		
		// Check for phone fields
		if (requiredPhoneFields.length > 0)	{
			fieldList = requiredPhoneFields.split(',');
			for (i=0; i<fieldList.length; i=i+1){
				fieldName = processType+fieldList[i];
				infoName = 'inf_'+fieldList[i];
				if (!validateTelnr (document.getElementById(fieldName), infoName, true)) errs += 1; 
			}
		}


		/* --------------------------------------------------------------------------------*/
		/* -------------------------------- custom code -----------------------------------*/
		// On the main inquiry form page the customer must provide either their account number OR their phone number
		if (document.getElementById('TCU_ticketForm'))	{
			if (document.getElementById('edit_account'))	{
				fieldName = 'edit_account';
				infoName = document.getElementById(fieldName);
				i = infoName.value;
				if (i.length ==  0)	{
					fieldName = 'edit_phone';
					infoName = document.getElementById(fieldName);
					i = infoName.value;
					if (i.length ==  0)	{
						errs = errs + 1;
						alert('Please include either your account number or your phone number or both');
					}
				}
			}
		}
		/* ------------------------------- end custom code --------------------------------*/
		/* --------------------------------------------------------------------------------*/

    	
    	// Check to see if there were any errors and alert the user if found
		if (errs>1)  alert('There are fields which need correction before sending');
	    if (errs==1) alert('There is a field which needs correction before sending');

    	if (errs == 0) {
    		return true;
    	} else {
    		return false;
  		}
  	}	
  	
  	function msg(fld, msgtype, message) {
  		var nbsp = 160;		// non-breaking space char
		var dispmessage;
		if (emptyString.test(message)) 
		    dispmessage = String.fromCharCode(nbsp);    
		else  
		    dispmessage = message;
		
		var elem = document.getElementById(fld);
		elem.firstChild.nodeValue = dispmessage;  
		elem.className = msgtype;   
	}

/* ---------------- utilities ----------------------- */

	function replaceString(input,replaceStr,type) {
		var sRet = "";
		myRegEx = new RegExp(type,'g');
		sRet = input.replace(myRegEx,replaceStr);
		return sRet;	
	}
	
	function callSortFormatX() {
		//set the columns to sortable and line colors to alternating
		mySorted = new SortedTable();
		mySorted.colorize = function() {
			if (typeof(this.elements) != 'undefined') {
				for (var i=0;i<this.elements.length;i++) {
					if (i%2){
						this.changeClass(this.elements[i],'even','odd');
					} else {
						this.changeClass(this.elements[i],'odd','even');
					}
				}
			}
		}
		mySorted.onsort = mySorted.colorize;
		mySorted.onmove = mySorted.colorize;
		mySorted.colorize();		
	}
	
	function setupCalendar(inputField, button) {
		Zapatec.Calendar.setup({
		        weekNumbers       : false,
		        range             : [2006.01, 2020.12],
		        electric          : false,
		        inputField        : inputField,
		        button            : button,
		        ifFormat          : "%m/%d/%Y",
		        daFormat          : "%m/%d/%Y",
		        align             : "Tr"
		    });
	}
	
	function showDiv(divName)	{
		var buttonDiv = divName + "Btn";
		var buttonName = document.getElementById(buttonDiv);
		var buttonVal = buttonName.value;
		var tDiv = document.getElementById(divName);
		tDiv.style.display = "";
		buttonName.value = "-";		
	}
	
	function hideStatus(container) {
	  	var tDiv = document.getElementById(container);
		tDiv.style.display = "none";
	}
	
	function showStatus(container) {
	   	var tDiv = document.getElementById(container);
		tDiv.style.display = "";
	}
	
	function reportError() {
		alert('Their was an error during the javascript operation.');
	}
	
	function getURLParams(strUrl){
	  var strReturn = "";
	  if ( strUrl.indexOf("?") > -1 ){
	  	var pos = strUrl.indexOf("?") + 1
	    strReturn = strUrl.substr(pos);
	  }
	  return strReturn;
	}
	  
	function getURL(strUrl){
	  var strReturn = strUrl;
	  if ( strUrl.indexOf("?") > -1 ){
	  	var pos = strUrl.indexOf("?")
	    strReturn = strUrl.substr(0,pos);
	  }
	  return strReturn;
	}
	
	function cleanString(inputString) {
		// we now use a external cleaner that does URL encoding
		var returnString = '';
		if (inputString != '') {
			returnString = encodeURL(inputString,"utf8");
		}
		return returnString;
	}
	//toggle the div
	function toggleDiv(divName)	{
		// get button name and value
		var buttonDiv = divName + "Btn";
		var buttonName = document.getElementById(buttonDiv);
		var buttonVal = buttonName.value;

		// get div to show/hide
		var tDiv = document.getElementById(divName);
		
		if (buttonVal == '+')	{
			tDiv.style.display = "";
			buttonName.value = "-";
		}	else	{
			tDiv.style.display = "none";
			buttonName.value = "+";
		}
	}


	/*-----------------------------------------------------------
    ---------------------------------------------------------*/
	function toggleTab2(currentTab,newTab) {

		var d = document.getElementById(newTab);
		var h = document.getElementById(currentTab);
		
        if (d.style.display == 'none')	{
            d.style.display = 'block';
        } else {
            d.style.display = 'none';
        }

        if (h.style.display == 'block')	{
            h.style.display = 'none';
        } else {
            h.style.display = 'block';
        }

	}
	
    /*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
    Input:     1.The number of the current tab
                    2.The number of tabs
                    3.(optional)The number of the tab to leave open
                    4.(optional)Pass in true or false whether or not to animate the open/close of the tabs
    Output: none 
    ---------------------------------------------------------*/
    function toggleTab(num,numelems,opennum,animate) {
		sTab = 'tabContent'+num
		oTab = document.getElementById(sTab);
	    if (oTab.style.display == 'none'){
	        for (var i=1;i<=numelems;i++){
	            if ((opennum == null) || (opennum != i)){
	                var temph = 'tabHeader'+i;
	                var h = document.getElementById(temph);
	                if (!h){
	                    var h = document.getElementById('tabHeaderActive');
	                    h.id = temph;
	                }
	                var tempc = 'tabContent'+i;
	                var c = document.getElementById(tempc);
	                if(c.style.display != 'none'){
	                        toggleDisp(tempc);
	                }
	            }
	        }
	        var h = document.getElementById('tabHeader'+num);
	        if (h)
	            h.id = 'tabHeaderActive';
	        h.blur();
	        var c = document.getElementById('tabContent'+num);
	        c.style.marginTop = '2px';
	        if (animate || typeof animate == 'undefined'){
	            toggleDisp('tabContent'+num);
	        }
	    }
	}


	/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
	function toggleDisp() {
	    for (var i=0;i<arguments.length;i++){
	        var d = document.getElementById(arguments[i]);
	       if (d.style.display == 'none')
	            d.style.display = 'block';
	        else
	            d.style.display = 'none';
	    }
	}
	
	function limitText(limitField, limitCount, limitNum) {
		if (limitField.value.length > limitNum) {
			limitField.value = limitField.value.substring(0, limitNum);
		} else {
			limitCount.value = limitNum - limitField.value.length;
		}
	}
	


