/*
 Ajax function
 
 include tag : <script type="text/javascript" src="ajax/ajaxFunction.js"></script>
 
*/

/// create XML object ///


function include(destination) {
var e = window.document.createElement('script');
e.setAttribute('src',destination);
window.document.body.appendChild(e);
}



var ajaxHTTPStatus = "";
var ajaxResponseText = "";

function ajaxRequestObject()
{
	var ajaxRequest;
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} 
	catch (e)
	{
		// Internet Explorer Browsers
		try
		{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) 
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e)
			{
				alert("Deze website gebruikt een Ajax interface om gegevens op te vragen vanaf de webserver, deze wordt echter niet ondersteunt door jou browser.");
				return false;
			}
		}
	}
	return ajaxRequest;
}


/*

this function handles the placement of a text into a div
stringUrl, contains the url that have to be called 
contentDivID, id of the div that needs to be filled with the
replying content.

*/
function ajaxPlaceContentInDiv(stringUrl,contentDivID)
{
	var http = ajaxRequestObject();
			
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
		}
		
		if(http.readyState == 4 && http.status == 200)
		{
			if(http.responseText.length > 0)
			{
				ajaxInnerXHTML(contentDivID,http.responseText);
			}
			else
			{
			  document.getElementById(""+contentDivID).innerHTML = "";
			}		
		}
	}
	
	http.open('get',stringUrl,true);
	http.send(null);
	return true;
}

function ajaxSubmitFormGET(urlToPost,formObjectID,returnFunction)
{
	var http = ajaxRequestObject();
	
	http.onreadystatechange = function()
	{		
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
			
			eval(""+ returnFunction +"(http.status,http.responseText);");
		}
	}
	
	postContent = ajaxFormUrlEncode(formObjectID);
	http.open('get','?'+ postContent,true);
	http.send(null);
}	

function ajaxSubmitFormPOST(urlToPost,formObjectID,returnFunction,passThroughValue,submitButton)
{
	var http = ajaxRequestObject();
	
	http.onreadystatechange = function()
	{		
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
			
			if(typeof(passThroughValue) != 'undefined')
			{
				eval(""+ returnFunction +"(http.status,http.responseText,passThroughValue);");
			}
			else
			{
				eval(""+ returnFunction +"(http.status,http.responseText);");
			}	
		}
	}
	
	postContent = ajaxFormUrlEncode(formObjectID,submitButton);
	http.open('POST', urlToPost, true);
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", postContent.length);
  http.setRequestHeader("Connection", "close");
  http.send(postContent);
}	

function ajaxPostData(urlToPost,postContent,returnFunction,passThroughValue)
{
	var http = ajaxRequestObject();
	
	http.onreadystatechange = function()
	{		
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
			
			if(typeof(passThroughValue) != 'undefined')
			{
				eval(""+ returnFunction +"(http.status,http.responseText,passThroughValue);");
			}
			else
			{
				eval(""+ returnFunction +"(http.status,http.responseText);");
			}		
		}
	}
	
	if(postContent.length > 0)
	{
		http.open('POST', urlToPost, true);
	  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  http.setRequestHeader("Content-length", postContent.length);
	  http.setRequestHeader("Connection", "close");
	  http.send(postContent);
	}
	else
	{
		http.open('get',urlToPost,true);
		http.send(null);
	}	
}	


/*
Deze functie selecteerd een element dmv de ID, vervolgens worden alle
input en select elementen doorlopen binnen deze ID om ze fetchen in een
GET method string.
*/

function ajaxFormUrlEncode(objectID,submitButton) 
{
      var getstr = "";
      var inputTags = "";
      var selectTags = "";
      obj = document.getElementById(""+objectID);
     
      if(obj)
      {
	      inputTags = obj.getElementsByTagName("input");
	      for (i=0; i< inputTags.length; i++) 
	      {
	          if (inputTags[i].type == "text" || inputTags[i].type == "hidden" || inputTags[i].type == "button")
            {
               getstr += inputTags[i].name + "=" + encodeURIComponent(inputTags[i].value) + "&";
            }
            
            if(submitButton)
            {
            	if(inputTags[i].name == submitButton)
            	{
            		 getstr += inputTags[i].name + "=" + encodeURIComponent(inputTags[i].value) + "&";
            	}	
            }
            else
            {
            	if(inputTags[i].type == "submit")
            	{
            		 getstr += inputTags[i].name + "=" + encodeURIComponent(inputTags[i].value) + "&";
            	}	
            }		
            
            if (inputTags[i].type == "checkbox")
            {
               if (inputTags[i].checked)
               {
                  getstr += inputTags[i].name + "=" + encodeURIComponent(inputTags[i].value) + "&";
               }
            }
            
            if (inputTags[i].type == "radio")
            {
               if (inputTags[i].checked) 
               {
                  getstr += inputTags[i].name + "=" + encodeURIComponent(inputTags[i].value) + "&";
               }
            }
	    	}  
	      
	      var i = 0;
	       
	      selectTags = obj.getElementsByTagName("select");
	      for (i=0; i< selectTags.length; i++) 
	      {
	      	selectToRunThrough = selectTags[i];
	      	
	      	var z = 0;
	      	for (z=0; z<selectToRunThrough.options.length; z++)
	      	{
						  if (selectToRunThrough.options[z].selected == true)
						  {
						     getstr += selectToRunThrough.name + "=" + encodeURIComponent(selectToRunThrough.options[z].value) + "&";
						  }
					 }
	      }
	      
	      var i = 0;
	       
	      textAreaTags = obj.getElementsByTagName("textarea");
	      for (i=0; i< textAreaTags.length; i++) 
	      {
	      	selectToRunThrough = textAreaTags[i];
	      	getstr += selectToRunThrough.name + "=" + encodeURIComponent(selectToRunThrough.value) + "&";
	      }	
	    }
      return getstr;
   }




function ajaxPlaceContentInSelect(stringUrl,contentSelectID,displayOff)
{
	var http = ajaxRequestObject();
	var returnElements;
	var stringText;
	var nothing = true;
	
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
		}
		
		if(http.readyState == 4 && http.status == 200)
		{
			document.getElementById(""+contentSelectID).options.length = "";
			stringText = http.responseText;
			
			if(stringText.length > 0)
			{
				returnElements = stringText.split(">");
        
        for(var i=0; i< returnElements.length -1; i++)
        {
        	valueLabelPair = returnElements[i].split("<")
   				document.getElementById(""+contentSelectID).options[i] = new Option(decodeURIComponent(valueLabelPair[1]), valueLabelPair[0]);
        	nothing = false;
        }
        
        if(displayOff)
        {
        	if(nothing == true)
        	{
        		document.getElementById(""+contentSelectID).style.display = "none";
        	}
        	else
        	{
        		document.getElementById(""+contentSelectID).style.display = "inline";
					}
				}
					
			}
			else
			{
				if(displayOff)
        {
					document.getElementById(""+contentSelectID).style.display = "none";
				}
			}		
		}
	}
	http.open('get',stringUrl,true);
	http.send(null);
	return true;
}

function ajaxExecuteAutoComplete(stringUrl,autoCompleteText,autoCompleteList,autoCompleteSelect,autoCompleteHiddenValue)
{
	var http = ajaxRequestObject();
	var returnElements;
	var stringText;
	
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
		}
		
		if(http.readyState == 4 && http.status == 200)
		{
			document.getElementById(""+autoCompleteSelect).options.length = "";
			stringText = http.responseText;
			
			if(stringText.length > 0)
			{
				returnElements = stringText.split(">");
        
        for(var i=0; i< returnElements.length -1; i++)
        {
        	valueLabelPair = returnElements[i].split("<")
   				document.getElementById(""+autoCompleteSelect).options[i] = new Option(decodeURIComponent(valueLabelPair[1]), valueLabelPair[0]);
   		 	}
        
        document.getElementById(""+autoCompleteList).style.visibility = "visible";
			}
			else
			{
				document.getElementById(""+autoCompleteList).style.visibility = "hidden";
			}	
		}
	}
	http.open('get',stringUrl,true);
	http.send(null);
	return true;
}

function ajaxAutoCompleteMouseClick(autoCompleteText,autoCompleteList,autoCompleteSelect,autoCompleteHiddenValue)
{
	var keyValue;
	var valValue;
	
	selectedAutoComplete = document.getElementById(""+autoCompleteSelect);
	while (selectedAutoComplete.selectedIndex != -1) 
	{
		/// de value attribut uitlezen en de optie naam zelf //
		keyValue = selectedAutoComplete.options[selectedAutoComplete.selectedIndex].value;
		valValue = selectedAutoComplete.options[selectedAutoComplete.selectedIndex].innerHTML;
		selectedAutoComplete.remove(selectedAutoComplete.selectedIndex);
	}
	
	valValue = releaseEscapedAmp(valValue);
	/// het textveld vullen met de geslecteerde waarde/
	document.getElementById(""+autoCompleteText).value = valValue;	
	
	// Als er een hiddenfield bestaat voor de key value van de geselecteerde optie
	// deze doorgeven aan de hidden field.
	if(document.getElementById(""+autoCompleteHiddenValue))
	{
		document.getElementById(""+autoCompleteHiddenValue).value = keyValue;
	}
	
	document.getElementById(""+autoCompleteList).style.visibility = "hidden";
	
	return true;
}

function ajaxAutoCompleteOnUnFocus(autoCompleteList)
{
	document.getElementById(""+autoCompleteList).style.visibility = "hidden";
	return true;
}	

function ajaxSubmitDataToUrl(stringUrl,errorMessageDiv)
{
	var http = ajaxRequestObject();
	var returnElements;
	var stringText;
	
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			ajaxHTTPStatus = http.status;
			ajaxResponseText = http.responseText;
		}
		
		if(http.readyState == 4 && http.status == 200)
		{
			stringText = http.responseText;
			
			if(stringText.length > 0)
			{
				document.getElementById(""+errorMessageDiv).innerHTML = stringText;
				return false;
			}
			else
			{
				document.getElementById(""+errorMessageDiv).innerHTML = "";
				return true;
			}		
		}
	}
	http.open('get',stringUrl,true);
	http.send(null);
}


function ajaxInnerXHTML(contentDivID,xhtmlString)
{
	placeHolder = document.getElementById(""+contentDivID);
	ajaxCleanInnerXHTML(contentDivID);
	
	/// Internet explorer heeft geen DOMparser, allerlei andere browsers wel ///
	
	if(typeof DOMParser == "undefined")
	{
		/// Als het windowsobject aanwezig is wordt deze gebruikt om een string te
		/// parsen voor een optionbox.
		
		if(placeHolder.tagName.toLowerCase() == 'select')
		{
			/// controleren of de ActiveXobject aanwezig is ///
			
			if (window.ActiveXObject)
	  	{
		  	var doc=new ActiveXObject("Microsoft.XMLDOM");
		 	 	doc.async="false";
		  	
		  	/// De xml moet een root element hebben om te gebruiken in de parser ///
		  	
		  	doc.loadXML('<div xmlns="http://www.w3.org/1999/xhtml">' + xhtmlString + '<\/div>');
		  	var root = doc.documentElement;	
				
				/// doorlopen van de childs en het plaatsen van de option ///
				
				for (var i=0; i < root.childNodes.length; ++i)
				{
					optionText = root.childNodes[i].childNodes[0].nodeValue;
					optionValue = root.childNodes[i].getAttribute("value");
					placeHolder.options[i] = new Option(optionText,optionValue);
					
					if(root.childNodes[i].getAttribute("selected"))
					{
						placeHolder.options[i].selected = true;
					}
				}
				doc = null;		
			}
		}	
		else
		{
			//// inprincipe is innerHTML niet w3c complaint, maar wel supper handig voor IE ////
			placeHolder.innerHTML = "";
			placeHolder.innerHTML = xhtmlString;
		}
	}
	else
	{
		/// DOMparser wordt herkent door Opera, Safari, Netscape en Firefox en voldoet
		/// aan de specificaties van het W3C
		var parser = new DOMParser();
		
		/// Parsen van het de xhtmlString met een div wrapper als root ///
		
		var doc = parser.parseFromString('<div xmlns="http://www.w3.org/1999/xhtml">' + xhtmlString + '<\/div>', 'application/xhtml+xml');
		
		/// doorlopen van de het root element, en alle childs eruit halen.
		var root = doc.documentElement;
		for (var i=0; i < root.childNodes.length; ++i)
		{
			//// plaatsen van de childs 
			placeHolder.appendChild(document.importNode(root.childNodes[i], true));
		}
	}
}	

function ajaxCleanInnerXHTML(contentDivID)
{
	placeHolder = document.getElementById(""+contentDivID);
	while(placeHolder.hasChildNodes())
	{
			placeHolder.removeChild(placeHolder.firstChild);
	}
}	

function trim(value)
{
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  return value;
}

function releaseEscapedAmp(nameOfGame)
{
	nameOfGame = nameOfGame.replace("&lt;","<");
	nameOfGame = nameOfGame.replace("&gt;",">");
	nameOfGame = nameOfGame.replace("&amp;","&");
		
	return nameOfGame;
}

function getFileExtension(filename)
{
	var dot = filename.lastIndexOf("."); 
	
 	if( dot == -1 )
 	{
 		return false; 
 	}
 	else
 	{
 		return filename.substr(dot,filename.length);
 	}
}
/*
Set het autocomplete off when ajax is used 
*/
function ajaxAutoCompleteOff()
{
	if (document.getElementsByTagName)
	{
		var inputArray = document.getElementsByTagName("input");
		
		for (i=0; inputArray[i]; i++) 
		{
				inputArray[i].setAttribute("autocomplete","off");
		}
	}
}



