/************************************************************************
Request manager process ver. 1.00

Copyright (c) 2008, Track-it.info
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are prohibited.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

_________________________________________________________________________

*************************************************************************/
//for the markerTimer we need global viariables
var markerTimer=null;
var request=null;	// the response from an XMLHttpRequest

/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;

// Set-up a multi div-tag direction function
function handleDivTag(divtag)
{
   var divtag;
   return divtag;
}

// Create the Divtag Handler -- Mainly an IE 6 Fix
var divhandler = new handleDivTag(null);


function createRequestObject() {
	
	var req;
	
	if(window.XMLHttpRequest){
	    // Firefox, Safari, Opera...
	    req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
	    // Internet Explorer 5+
	    req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	    // There is an error creating the object,
	    // just as an old browser is being used.
	    alert("There was a problem creating the XMLHttpRequest object");
	}
	
	return req;

}
    
function sendRequest( reqDoc, divtag ) 
{
  var htmlDoc= reqDoc;
  if (markerTimer) clearTimeout(markerTimer);
  // Check if requestobject is initialized, if not do so...
  if( !request )
  {
	  request = createRequestObject();
	}
    // Setup the taghandler to handle the different tags
    
	divhandler.divtag = (divtag==null?"DataContainer":divtag);
   
  // Open PHP script for requests
	request.open("GET", htmlDoc,true);
  
  request.onreadystatechange = handleResponse;
  request.send(null);
  
  }     
  
function postRequest( reqDoc, strSubmit, formDoc ) 
{
  var htmlDoc= reqDoc;
  // Check if requestobject is initialized, if not do so...
  if( !request)
  {
	  request = createRequestObject();
	}
  // Open PHP script for requests
	request.open("POST", htmlDoc,true);
	
	try
	{

	 if( formDoc.encoding == "multipart/form-data") 
	 {
	   request.setRequestHeader("Content-Type", "multipart/form-data");
		}else {
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
	} catch(e)
	{
	  // do nothing
	}
  request.onreadystatechange = handleResponse;
  request.send(strSubmit);
  
} 
    

 
function handleResponse() 
{
  if(request.readyState == 4 && request.status == 200)
	{
	  docType= request.getResponseHeader("Content-Type");
	  
	  switch (docType)
		{ 
			case "text/xml":
		    break;
			default:
       var htmlDoc =request.responseText;
       switch(divhandler.divtag)
       {
         case "GraphBox":         
           document.getElementById(divhandler.divtag).innerHTML = htmlDoc;
           showDiv("Overlay");
           showDiv("GraphBox");
           divhandler.divtag=null; // avoid tag-memory issues!
         break;
         case "graphLabel":
            var xml = request.responseXML;
            var params = xml.documentElement.getElementsByTagName("param");
            //get reference to iFrame
            var gip=document.getElementById("geFrame");

            // clear param selection list
            i=0;
            while( gip.contentWindow.document.graphDetail.parameter_x.options.length>0)
            {
              i = gip.contentWindow.document.graphDetail.parameter_x.options.length-1;
              gip.contentWindow.document.graphDetail.parameter_x.options[i]=null;
            }
            while( gip.contentWindow.document.graphDetail.parameter_y.options.length>0)
            {
              i = gip.contentWindow.document.graphDetail.parameter_y.options.length-1;
              gip.contentWindow.document.graphDetail.parameter_y.options[i]=null;
            }
            for (i = 0; i < params.length; i++)
            {
              var text=params[i].firstChild.nodeValue;
              var value = params[i].getAttribute("value");
              gip.contentWindow.document.graphDetail.parameter_x.options[i] = new Option(text,value);
              gip.contentWindow.document.graphDetail.parameter_y.options[i] = new Option(text,value);
            }
         break;
         case "AlarmBox":
           document.getElementById(divhandler.divtag).innerHTML = htmlDoc;
           showDiv("Overlay");
           showDiv("AlarmBox");
           divhandler.divtag=null; // avoid tag-memory issues!
           if(dataInterval < 60000 || !dataInterval || isNaN(dataInterval)) dataInterval=60000;
           alarmTimer=setTimeout( "getUpdate('/alarmstatus.php?companyID='+CompanyID+'&int='+dataInterval,'AlarmBox')",dataInterval);
           document.getElementById("lastrefresh").value= Date();
         break;
         default:
          document.getElementById('MapContainer').style.visibility='hidden';
          document.getElementById('MapContainer').style.zIndex=0;
          document.getElementById("DataContainer").style.zIndex=1;
          
          document.getElementById("DataContainer").innerHTML = htmlDoc;
          if( !document.getElementById("DTREE"))
          {
            document.getElementById("TreeContainer").innerHTML="";
            if( document.getElementById("TreeContainerData") )
            {
              document.getElementById("TreeContainer").innerHTML=document.getElementById("TreeContainerData").innerHTML;
              document.getElementById("TreeContainerData").innerHTML="";
            }
          }
          
        }
  		}
		}
}
 
function getUpdate()
{
	tmpUrl = ""+document.getElementById("update").innerHTML;
	sendRequest(tmpUrl);
}

function syncLoFlag( docForm )
{
  if( docForm.name=="alarmDetail")
  {
    docForm.redflag_lo.value=docForm.minValue.value;
    docForm.ylwflag_lo.value=docForm.minValue.value;
  }
  // prevent immediate submit
  return false;
}

function syncHiFlag( docForm )
{
  if( docForm.name=="alarmDetail")
  {
    docForm.redflag_hi.value=docForm.maxValue.value;
    docForm.ylwflag_hi.value=docForm.maxValue.value;

  }
  // prevent immediate submit
  return false;
}

function postForm( docForm,htmlDoc)
{
  var validInput = true;
  
  if( docForm.name=="userInfo")
  {
  	
		// check if all fields have valid input
		if( checkUserInfo(docForm)==0)
		{
		  validInput=true;
		} else validInput=false;
		
	} 
	
	if(docForm.name=="companyInfo")
	{
		// check if all fields have valid input
		if( checkCompanyInfo(docForm)==0)
		{
		  validInput=true;
		} else validInput=false;
	}
  if(docForm.name=="paramDetail")
    {
     // check if all fields have valid input
		if( checkParamInfo(docForm)==0)
		{
		  validInput=true;

		} else validInput=false;
    }
	if( validInput)
	{
	  var formData =formData2QueryString(docForm);
	  
	  postRequest( htmlDoc, formData, docForm );
	  
	}

  // prevent form from submitting form.
  return false;
}

function checkUserInfo( docForm )
{
	//A binary shift right is used to test checksum

	var checksum = 127;// binary 1111111 for 7 fields
	var msg = "U heeft de volgende informatie niet opgegeven:\n";
	if( docForm.login.value == "")
	{
	  msg += "U heeft geen loginnaam opgegeven.\n";
	} else {
		checksum>>>=1;
		}
	if( docForm.password.value == "" && docForm.what.value=="new" )
	{
	  msg += "U heeft geen wachtwoord opgegeven\n";
	} else{
		checksum>>>=1;
		}
	if( docForm.confirm.value == "" && docForm.what.value=="new")
	{
	  msg += "U heeft geen bevestigingswachtwoord opgegeven.\n";
	} else{
			checksum>>>=1;
		}
	if( docForm.first_name.value == "")
	{
	  msg += "U heeft geen voornaam opgegeven\n";
	} else{
			checksum>>>=1;
		}
	if( docForm.last_name.value == "")
	{
	  msg += "U heeft geen achternaam opgegeven\n";
	} else{
			checksum>>>=1;
		}
	if( docForm.phone.value == "")
	{
	  msg += "U heeft geen telefoonnummer opgegeven\n";
	} else 
	{
	  if( docForm.phone.value.indexOf(" ")>=0 || docForm.phone.value.indexOf("-")>4 || docForm.phone.value.length<10 || docForm.phone.value.length>11 || docForm.phone.value.indexOf("0")!=0)
	  {
		  msg += "Het telefoonnummer is niet in het formaat \n0123456789, 06-12345678, 012-3456789 of 0123-456789!\n";
		} else{
				checksum>>>=1;		  
			}
	}
	if( docForm.email.value == "")
	{
	  msg += "U heeft geen e-mail adres opgegeven\n";
	} else 
	{ 
	  if( docForm.email.value.lastIndexOf(".")>docForm.email.value.indexOf("@") && docForm.email.value.lastIndexOf(".")!=docForm.email.value.indexOf("@") && docForm.email.value.indexOf("@")>=0)
	  { 
			checksum>>>=1; 	  
		} else 
		{
		 msg += "U heeft een ongeldig e-mail adres opgegeven!\n";
		}
	 
	}
	if( checksum ) alert(msg);
	return checksum;
}
	
function checkCompanyInfo( docForm )
{
	//A binary shift right is used to test checksum
	var checksum = 63; // binary 111111 for 6 fields
	var msg = "U heeft de volgende informatie niet opgegeven:\n";
	if( docForm.company.value == "")
	{
	  msg += "U heeft geen bedrijfsnaam opgegeven\n";
	} else{
	 		checksum>>>=1;
	 	}
	if( docForm.address.value == "")
	{
	  msg += "U heeft geen adres opgegeven\n";
	} else{
		 	checksum>>>=1;
		 }
	if( docForm.zip.value == "")
	{
	  msg += "U heeft geen postcode opgegeven\n";
	} else{
	 		checksum>>>=1;
	 	}
	if( docForm.city.value == "")
	{
	  msg += "U heeft geen plaats opgegeven\n";
	} else{
		 	checksum>>>=1;
		 }
	if( docForm.phone.value == "")
	{
	  msg += "U heeft geen telefoonnummer opgegeven\n";
	} else 
	{
	  if( docForm.phone.value.indexOf(" ")>=0 || docForm.phone.value.indexOf("-")>4 || docForm.phone.value.length<10 || docForm.phone.value.length>11 || docForm.phone.value.indexOf("0")!=0)
	  {
		  msg += "Het telefoonnummer is niet in het formaat \n0123456789, 06-12345678, 012-3456789 of 0123-456789!\n";
		} else{
		 		checksum>>>=1;		  
		 	}
	}
	if( docForm.email.value == "")
	{
	  msg += "U heeft geen e-mail adres opgegeven\n";
	} else 
	{ 
	  if( docForm.email.value.lastIndexOf(".")>docForm.email.value.indexOf("@") && docForm.email.value.lastIndexOf(".")!=docForm.email.value.indexOf("@") && docForm.email.value.indexOf("@")>=0)
	  { 
			checksum>>>=1; 	  
		} else 
		{
		 msg += "U heeft een ongeldig e-mail adres opgegeven!\n";
		}
	 
	}
	return checksum;
}

function checkParamInfo( docForm )
{
	//A binary shift right is used to test checksum
	var checksum = 31; // binary 11111 for 6 fields
	var msg = "U heeft de volgende informatie niet opgegeven:\n";
	if( docForm.paramName.value == "")
	{
	  msg += "U heeft geen parameternaam opgegeven\n";
	} else{
	 		checksum>>>=1;
	 	}
	if( docForm.unit.value == "")
	{
	  msg += "U heeft geen eenheid opgegeven\n";
	} else{
		 	checksum>>>=1;
		 }
	if( docForm.type.value == "")
	{
	  msg += "U heeft geen type opgegeven\n";
	} else{
	 		checksum>>>=1;
	 	}
	if( docForm.colIndex.value == "")
	{
	  msg += "U heeft geen kolomnr opgegeven\n";
	} else{
		 	checksum>>>=1;
		 }
	if( docForm.offset.value == "")
	{
	  msg += "U heeft geen offset opgegeven\n";
	} else
	{
 		checksum>>>=1;
	}
  if( checksum>0) alert(msg);
	return checksum;
}

function onLoad( url ) 
{
	  

			request = createRequestObject();
			
			sendRequest(url);
}

/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Original code by Matthew Eernisse (mde@fleegix.org)
 * Additional bugfixes by Mark Pruett (mark.pruett@comcast.net)
 *
*/

// The var docForm should be a reference to a <form>

function formData2QueryString(docForm) {

  var submitContent = "";
  var formElem;
  var lastElemName = "";
  
  for (i = 0; i < docForm.elements.length; i++) {
    
    formElem = docForm.elements[i];
    switch (formElem.type) {
      // Text fields, hidden form elements
      case "text":
      case "hidden":
      case "password":
      case "textarea":
      case "select-one":
      case "submit":
        submitContent += formElem.name + "=" + escape(formElem.value) + "&";
        break;
        
      // Radio buttons
      case "radio":
        if (formElem.checked) {
          submitContent += formElem.name + "=" + escape(formElem.value) + "&";
        }
        break;
        
      // Checkboxes
      case "checkbox":
        if (formElem.checked) {
          // Continuing multiple, same-name checkboxes
          if (formElem.name == lastElemName) {
            // Strip of end ampersand if there is one
            if (submitContent.lastIndexOf("&") == submitContent.length-1) {
              submitContent = submitContent.substr(0, submitContent.length - 1);
            }
            // Append value as comma-delimited string
            submitContent += "," + escape(formElem.value);
          }
          else {
            submitContent += formElem.name + "=" + escape(formElem.value);
          }
          submitContent += "&";
          lastElemName = formElem.name;
        }
        break;
        
    }
  }
  // Remove trailing separator
  submitContent = submitContent.substr(0, submitContent.length - 1);
  return submitContent;
}

function setFormAction( btn )
{
	document.getElementById("What").value= btn.value;
	return true;
}

function showDiv(obj)
{
	document.getElementById(obj).style.visibility='visible';
}

function closeDiv(obj)
{
	document.getElementById(obj).style.visibility='hidden';
}

function toggleDiv(obj)
{
  switch(document.getElementById(obj).style.visibility)
  {
    case "hidden":
      document.getElementById(obj).style.visibility="visible";
      break;
    default:
      document.getElementById(obj).style.visibility="hidden";
      break;
  }
}

function toggleFuncEdit(obj, name)
{
  var inx = obj.selectedIndex;
  if(obj.options[inx].value==="Function()")
  {
    document.getElementById(name).style.visibility="visible";
  } else document.getElementById(name).style.visibility="hidden";
}

function loadParamList(obj, name)
{
  var inx = obj.selectedIndex;
  var id=obj.options[inx].value;
  sendRequest('/paramlist.php?id='+id,name);
}

function refit()
{
  var wH;
  var wW;
  (typeof window.innerHeight != 'undefined')?wH=window.innerHeight:wH=document.documentElement.clientHeight;
  (typeof window.innerWidth != 'undefined')?wW=window.innerWidth:wW=document.documentElement.clientWidth;
  //var wH = document.getElementById("MAIN").clientHeight;
  var bH = document.getElementById("LogoContainer").clientHeight;
	var fH = document.getElementById("Footer").clientHeight;
	var cH = document.getElementById("MiddleDiv").clientHeight;
	if( wH<730) wH=730;
  //document.getElementById("Footer").style.top= hgt+"px";
  document.getElementById("MiddleDiv").style.height= wH-fH+"px";
  document.getElementById("TreeContainer").style.height = wH-bH-fH+"px"; 
  document.getElementById("DataContainer").style.height = wH-bH-fH+"px"; 
  document.getElementById("GraphBox").style.top=(wH-500)/2+"px";
  document.getElementById("GraphBox").style.left=(wW-650)/2+"px";
  document.getElementById("AlarmBox").style.top=(wH-650)/2+"px";
  document.getElementById("AlarmBox").style.left=(wW-820)/2+"px";
  document.getElementById("Overlay").style.height=wH+"px";
}

function zoomImg( graphId, qstr)
{
  document.getElementById("GraphBox").style.background="url(/images/loading.gif)";
  showDiv("Overlay");
  showDiv("GraphBox");
  imgUrl="/dataview/showgraph.php?graphId="+graphId+qstr;
  document.getElementById("GraphBox").style.background="url("+imgUrl+")";
  document.getElementById("GraphBox").style.backgroundRepeat="no-repeat";
  document.getElementById("GraphBox").style.backgroundPosition="center center";
  document.getElementById("GraphBox").style.backgroundColor="#FFFFFF";
}

function closeZoom()
{
  closeDiv("GraphBox");
  closeDiv("Overlay");
}

function closeAlarm()
{
  closeDiv("AlarmBox");
  closeDiv("Overlay");
  clearTimeout( alarmTimer );
}

function isCookieAllowed()
{
var cookieEnabled=false;
document.cookie="testcookie";
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
if( !cookieEnabled )
{
	
	sendRequest("/notice_nl.htm","GraphBox");
}


}
