// ===================================================================
// Company: Attendee Interactive
// Author: Jason Daiger
// Website: http://www.attendeeinteractive.com/
// Description: This file contains generic global javascript functions
//	used by the ai-evolution system.
// 	
// NOTICE: You may *NOT* re-distribute this code in any way.
// That means, you cannot include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// ===================================================================

var submitting = 0;

function submitForm( formName ) {
    if( submitting == 0 ) {
        submitting = 1;
        document.getElementById(formName).submit();
    }
}

function openAIEditWindow(url, windowID) {
	var aWindow;
   aWindow = window.open(url, windowID, "top=10,left=10,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=800,height=500");
   aWindow.focus();
}
function openAIPreviewWindow(url, windowID) {
	var aWindow;
   aWindow = window.open(url, windowID, "top=15,left=15,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=800,height=500");
   aWindow.focus();
}
function openAISmallPreviewWindow(url, windowID) {
	var aWindow;
   aWindow = window.open(url, windowID, "top=15,left=15,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=350,height=250");
   aWindow.focus();
}
function redirectAIPage(url) {
	document.location.href = url;
}
function checkLength(formElement,maxLength) {
   //Find the desired element.
   if (document.getElementById(formElement).value.length > maxLength) {
      document.getElementById(formElement).value = document.getElementById(formElement).value.substring(0,maxLength - 1);
      alert("The entered text exceeds the allowable limit.  Only " + maxLength + " characters are allowed.  You must shorten this text before it can be saved.");
      return false;
   }
   else
      return true;
}

function openAINewWindow(url, windowID) {
	var aWindow;
   aWindow = window.open(url, windowID, "status=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1,top=15,left=15,width=1024,height=768");
   aWindow.focus();
}

function heartBeat(){
   var xmlhttp;
   var url = 'index.cfm?do=cnt.publicHeartBeat';
   xmlhttp=null;
   xmlhttp = ( window.XMLHttpRequest ) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") ;
   //build XMLObject
   if (xmlhttp!=null) {      
      xmlhttp.open("GET",url,true);  //build/open server object       
      xmlhttp.send(null);  //send request
   }
}


		
		
	

//loading message div
loadingMessageDivName = ""
function loadingMessage(action){
		//if (loadingMessageDivName == ""){return;}
		if(action == "s"){
				document.getElementById(loadingMessageDivName).innerHTML = '<img src="files/images/loading.gif" alt="Loading Please Wait" />';
				document.getElementById(loadingMessageDivName).style.display = "block";
		}else{
			document.getElementById(loadingMessageDivName).innerHTML = "";
			document.getElementById(loadingMessageDivName).style.display = "none";
		}
}


//Ajax function
// JavaScript Document
			var xmlhttp;
			var listHeight = 20
			var routeArray = new Array();
			var updFunc = "";
			var response =""

		// I build ajax oject and also send a request to server
		function buildXMLObj(url){
					loadingMessage('s');
					xmlhttp=null;
/*					// browser check
					if (window.XMLHttpRequest)
						{// code for Firefox, Opera, IE7, etc.
						xmlhttp=new XMLHttpRequest();
					}
					else if (window.ActiveXObject)
						{// code for IE6, IE5
						xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
					}*/
						xmlhttp = ( window.XMLHttpRequest ) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") ;

					//build XMLObject
					if (xmlhttp!=null)
						{
						//build/open server object
						xmlhttp.open("GET",url,true); 
						//send request
						xmlhttp.send(null); 
						}
					else
						{
						alert("Your browser does not support XMLHTTP.");
						}
			}
			
		// I convert response text into js variable object (coldfusion is returning data in wddx format e.g. r= '<option>test</option>')
		function response2Obj(str){
				eval("var "+str);
				return eval(cleanIt(str));
			}

			// i remove all extra characters from response text
			function cleanIt(str){
					str = str.replace(/\\/g,""); 
					str = str.replace(/\"/g,""); 
					return str.substring(str.search(/\S/g)).split(' ')[0];
			}
			
			// I set the name of functin which is going run after ajax request comes back from server
			function updateObjValue(funcRef){
					updFunc = funcRef
			}

		// I check the ajax state and also runs the function to update HTML obj with ajax response 
		function checkAjaxState(){
				if (xmlhttp.readyState==4 ) // 4 = "loaded"
						{// 4 = "loaded"
						if (xmlhttp.status==200) // 200 = "OK"
							{
								//response = response2Obj(xmlhttp.responseText)
								response = xmlhttp.responseText
								//eval(	updFunc +'()' )
								eval(	updFunc  )
							}
						else
							{
							alert("Problem retrieving data:" + xmlhttp.statusText);
							}
					}
				  loadingMessage('h');
			}			


//called from frm_editAttSignleSteps (build url string to send to XML object) 
function buildTempSummary(productsObjNameArray, objToUpdate, messageDivName){

	document.getElementById(objToUpdate).innerHTML = ""
	loadingMessageDivName = messageDivName
	if(productsObjNameArray.length >0){
	   	urlStr = "index.cfm?do=reg.buildTempSummary&key=" + Math.random() ;
   		sendRequest = false;
      addThisAlso = "" 
			// get All contact information
			addThisAlso = getAllObjectsInDiv("div1")
	
			// set all custom product code
      /*if(document.getElementById("RegistrationTypeID")){
      	addThisAlso += "&RegistrationTypeID=" + document.getElementById("RegistrationTypeID").value
      }*/

      if(document.getElementById("attendeeRegSingleProductIDChooseOne")){
      	addThisAlso += "&attendeeRegSingleProductIDChooseOne=" + document.getElementById("attendeeRegSingleProductIDChooseOne").value
      }

      if(document.getElementById("attendeeRegSingleProductTypesChooseOne")){
      	addThisAlso += "&attendeeRegSingleProductTypesChooseOne=" + document.getElementById("attendeeRegSingleProductTypesChooseOne").value
      }


      if(document.getElementById("attendeeRegSingleProductIDChooseMany")){
      	addThisAlso += "&attendeeRegSingleProductIDChooseMany=" + document.getElementById("attendeeRegSingleProductIDChooseMany").value
      }

      if(document.getElementById("attendeeRegSingleProductTypesChooseMany")){
      	addThisAlso += "&attendeeRegSingleProductTypesChooseMany=" + document.getElementById("attendeeRegSingleProductTypesChooseMany").value
      }

      if(document.getElementById("paymentOptionsIDs")){
      	addThisAlso += "&paymentOptionsIDs=" + document.getElementById("paymentOptionsIDs").value
      }

      if(document.getElementById("formID")){
      	addThisAlso += "&formID=" + document.getElementById("formID").value
      }
			
			

		 // get values for chooseone, choosemany, events and discount qty 
      for(a in eval(productsObjNameArray))  {
      	 objName = productsObjNameArray[a]
         objRef = document.getElementById(productsObjNameArray[a])

           if(objRef){
		      		
		      		objValue = 0;
							//buildUrlStr(productsObjNameArray)
              if(objRef.type == "radio" || objRef.type == "checkbox"  ){
                	//alert(objName + "," + objRef.type + "," + objRef.checked + "," + objValue + "," + objName.search("add_event_product_"))
              
              	if(objRef.checked == true){
	              	objValue = objRef.value

	              	if(objName.search("chooseOneProduct") != -1){
	              		objName = objName.substring(0, objName.length -4);
	              		addThisAlso += "&chooseOneProductQty_" + objValue + "=1"
									}
								/* turning off event conflict checking	*/
								if(objName.search("add_event_") != -1 && objName.search("add_event_product_") <= 0) {
													addEventObj = document.getElementById("add_event_" + objName.substring(10,14))
													if(addEventObj.checked == true){
					              		objValue = objName.substring(10,14)
					              		objName = "add_event" 
					              	}else{
					              		objValue = 0
					              	}
					          }	
					          							
              	}
              	 
              }
              else if(objRef.type == "select-one" || objRef.type == "select-multiple"){
                if (objRef.selectedIndex > 0 ){objValue = objRef.value }
							}
							else{
								objValue = objRef.value
 
								if(objName.search("add_event_product_") != -1){
									addEventObj = document.getElementById("add_event_" + objName.substring(18,22))
									if(addEventObj.checked == true){
	              		addThisAlso += "&add_event=" + objName.substring(18,22)
	              	}else{
	              		objValue = 0
	              	}
	              }
              }
              // build urlstr
            	if(objValue > 0 )
            	{
            		sendRequest = true;  
            		urlStr += "&" + objName + "=" +objRef.value
            	} 
            }
      }
		//alert(urlStr)
		if(sendRequest == true){
   		if(addThisAlso != ""){urlStr += addThisAlso} 

			sendAjaxRequest(urlStr, objToUpdate) 
		}
		else{
			 document.getElementById(objToUpdate).innerHTML = "Nothing to process"
		}
   }
}

function sendAjaxRequest(urlStr,objToUpdate ){
			if(urlStr == ""){alert('Please select all required field'); return;	}
			buildXMLObj(urlStr)
			//updateObjValue('buildResponses(' + objToUpdate + ')')
			updateObjValue('updateResponse("' + objToUpdate +  '")' )
			xmlhttp.onreadystatechange=checkAjaxState;										
}

function updateResponse(objToUpdate){
					//update new values to HTMl object
					document.getElementById(objToUpdate).innerHTML =  response ;
					// update error messages in each step
					for(a=0 ; a<regSteps.length ; a++){
            if(regSteps[a] != ""){

            	regSummaryErrorDiv =  regSteps[a] + "Errors" //e.g. attendeeError
            	regSummaryErrorDivRef = document.getElementById(regSummaryErrorDiv)

            	regStepsErrorDiv = findStepByName(regSteps[a]) + "Errors" //e.g. div1Errors
            	regStepsErrorDivRef = document.getElementById(regStepsErrorDiv)
							
							regStepsLink = findStepByName(regSteps[a]).substring(3)
							regStepsLink = "link" + regStepsLink  //e.g. link1
            	regStepsLinkRef = document.getElementById(regStepsLink)
            	regStepsLinkRef.style.color = "#003263"
             	if(regStepsErrorDivRef){
								regStepsErrorDivRef.innerHTML = ""
            		if(regSummaryErrorDivRef){
										regStepsErrorDivRef.innerHTML = regSummaryErrorDivRef.innerHTML
										markNotComplete(regStepsLink)
            				regStepsLinkRef.style.color = "#FF0000"
            				proceeedToSubmit = false;

            		}
            	} 
            }
         }
         	updatePaymentInfo();
}		





function showOfForm(frm) {

	if(!frm || !frm.elements) {
	
	return;
	
	}

	var elms = frm.elements;
	
	for(var i = 0, maxI = elms.length; i < maxI; ++i) {
	
		var elm = elms[i];
	
		alert("Type: " + elm.type + "\nName: " +
	
		elm.name + "\nId: " + elm.id);
	
	}

}			


function getAllObjectsInDiv(div) {
	returnStr = ""

	if(!div) {
		return;
	}

	div =  document.getElementById(div);

	 elms = div.getElementsByTagName("*");

  maxI = elms.length
  chkDesignation = true
//for(i in eval(elms))  {
	for(i = 0 ; i < maxI; i++) {

		var elm = elms[i];
	
		thisreturnStr = ""
		if(elm.name == "designation" && chkDesignation == true){
		  chkDesignation = false
     objRef = document.AttSingle.designation
     missingValue = true
     designStr = ""
			 for (di = 0; di < objRef.length; di++){
		     if( objRef[di].value !=  "None"  ){
		      if(objRef[di].checked == true){
						designStr +=    objRef[di].value  + ","
						missingValue = false
		      }
				}
			 }
       if(missingValue == false){
       	 thisreturnStr = "&" + elm.name + "=" + designStr.substring(0, designStr.length - 1) 
    	}
		
		}else if(elm.name != "designation") {
			switch(elm.type) {
				case "text":
					thisreturnStr = "&" + elm.name + "=" + elm.value 
				case "textarea":
					thisreturnStr = "&" + elm.name + "=" + elm.value 
				case "hidden":
					thisreturnStr = "&" + elm.name + "=" + elm.value 
				case "password":
					thisreturnStr = "&" + elm.name + "=" + elm.value 
				case "radio":
					thisreturnStr = "&" + elm.name + "=" + elm.checked 
				case "checkbox":
					thisreturnStr = "&" + elm.name + "=" + elm.checked 
				case "select-one":
					thisreturnStr = "&" + elm.name + "=" + elm.value 
				case "select-multiple":
					thisreturnStr = "&" + elm.name + "=" + elm.value
				}	 
		}
		if(thisreturnStr != "" ){
		
			returnStr += thisreturnStr

		}
			/*alert("Type: " + elm.type + "\nName: " +

			elm.name + "\nId: " + elm.id);	*/

	}
	return returnStr;
}			