/*
*   Send a AJAX request to server and insert the returned page in HTML container element
*   @param url Url to the request server page
*   @param parameters The parameters that are send as POST with the request
*   @param containerId The container id of the html container element where the answer of the request will be inserted 
*/
var lastUrl = "";
// Scripts that needs to be eval() after request
var scripts = new Array();
	
function getPage(url, parameters,containerId, parseJava) 
{       
	// Update global url for debug
	lastUrl = url;

	// Empty the http_request
	var http_request = false;

	// Mozilla, Safari,...
	if (window.XMLHttpRequest) 
	{ 
	  http_request = new XMLHttpRequest();
	  if (http_request.overrideMimeType) 
	  {
	      // set content type
	      http_request.overrideMimeType('text/html');
	  }
	} 

	// IE  
	else if (window.ActiveXObject) 
	{ 
	  try
	  {
	  	http_request = new ActiveXObject("Msxml2.XMLHTTP");
	  } 
	  catch (e)
	  {
      try
      {
      	http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch (e) 
      {
      }
	  }
	}

	// If the request element couldent be created
	if (!http_request) 
	{
	  alert('Sorry - there was an error. \n Cannot create XMLHTTP instance');
	  return false;
	}

	// Send parameters as POST. false means a syncron request
	http_request.open("POST", url, true);

	// Set to POST header type
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	// When the server has answered - call the setContent function
	http_request.onreadystatechange = function(){ setContent(containerId,http_request,parseJava); };        

	// Send the parameters via POST
	http_request.send(parameters);

	// Fix the firefox bug with sychronos AJAX requests
	try
	{
	  if (http_request.onreadystatechange == null) 
	  {
	      // If firebug wasent enabled
	      setContent(containerId,http_request);
	  }
	}
	catch(e){} 
	return true;
}

/*
*   Insert the content of a http_request object in a  given HTML container element
*   @param containerId The container id of the html div where the return of the request will be inserted 
*   @param http_request The http_request object
*/
function setContent(containerId,http_request,parseJava) 
{
  // If the readyState is "complete"
  if (http_request.readyState == 4) 
  {
    if (http_request.status == 200) 
    {
		  // Remove javascripts from source code
		  if(parseJava==true) result = removeJavaScript(http_request.responseText);
		  else result = http_request.responseText;
		        // Insert html from request
		        document.getElementById(containerId).innerHTML = result;
		  // Parse javascript or not
		  if(parseJava==true) evalScripts(scripts);
    }
    else 
    {
			//BugFix
			if (lastUrl != "loginSystem/brugerScripts/getWordCount.php")
			{
				//alert( "Kunne ikke finde siden: '"+lastUrl+"' . \nError code " + http_request.status);        
			}
		}
  }
}


function setContainerText(containerId,text) 
{
	document.getElementById(containerId).innerHTML =text;            
}
/*
*   Refresh the current page without sending POST requests again, 
*   after a given delay in miliseconds. 
*   @param timeour The delay in miliseconds, before the page is refreshed. 
*/
function updatePage(timeout)
{
	setTimeout("location.href = location.href",timeout);
}

// Remove javascript from AJAX request and put in global script array
function removeJavaScript(source) 
{	
	scripts = new Array();	
	// Find all script tags
	while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) 
	{
		// Find start script pos
		var tagStart = source.indexOf("<script");
		// Find end of script			
		var tagStartEnd = source.indexOf(">", tagStart);
		// Find end pos of script	
		var tagEnd = source.indexOf("</script", tagStart);
		var tagEndEnd = source.indexOf(">", tagEnd);

		// Add script to array
		scripts.push(source.substring(tagStartEnd+1, tagEnd));

		// Remove script from source
		source = source.substring(0, tagStart) + source.substring(tagEndEnd+1);
	}
	// Return clean source
	return source;
}

// Eval script array
function evalScripts(scripts)
{
	// Loop through all collected scripts and eval it
	var numscripts = scripts.length;
	for(var i=0; i<numscripts; i++) 
	{
		try
	 	{
			var lines = scripts[i].split(/\r\n|\r|\n/);
			var numlines = lines.length;
			for(var j=0;j<numlines;j++)
			{
				eval(lines[j]);
			}
		}
		catch(ex) 
		{
			alert("Error in javascript from ajax - " + ex);
		}
	}		
}


function requestObj()
{
	var req = false;
	try{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(err){
			A = false;
		}
	}

	if(!req && typeof(XMLHttpRequest) != 'undefined')
	{
		req = new XMLHttpRequest();
	}	
	return req;
}

/**************************************************************************/
function findAnchor(anchor)
{
 var allLinks = document.getElementsByTagName('a');
 var destinationLink = null;
	 // loop all A tags until we find the wright
 	for (var i=0; i < allLinks.length; i++) 
	{
	  var lnk = allLinks[i];
	  if (lnk.name && (lnk.name == anchor)) 
		{
   		destinationLink = lnk;
   		break;
		}
 	}
	return destinationLink;
}

function scrollToAnchor(anchor) 
{
	var destinationLink = null;
	destinationLink = findAnchor(anchor);
 
 	// If we didn't find a destination,
 	if (!destinationLink) return true;
	location.hash = anchor;
}


function smoothScroll(anchor,wait) 
{
	var destinationLink = null;
	destinationLink = findAnchor(anchor);
 
 	// If we didn't find a destination,
 	if (!destinationLink) return true;
 
 	// Find the destination's position
 	var destx = destinationLink.offsetLeft;  
 	var desty = destinationLink.offsetTop;
 	var thisNode = destinationLink;
 	
	//alert(destx);
	while (thisNode.offsetParent && (thisNode.offsetParent != document.body)) 
	{
	   thisNode = thisNode.offsetParent;
	   destx += thisNode.offsetLeft;
	   desty += thisNode.offsetTop;
 	}
 
	// Stop any current scrolling
	clearInterval(ss_INTERVAL);
	 
	var yPos = getCurrentYPos();
	 
	ss_stepsize = parseInt((desty-yPos)/ss_STEPS);
	ss_INTERVAL = setInterval('scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',wait);
	 
}


function scrollWindow(scramount,dest,anchor) 
{
	wascypos = getCurrentYPos();
 	isAbove = (wascypos < dest);
 	window.scrollTo(0,wascypos + scramount);
 	iscypos = getCurrentYPos();
 	isAboveNow = (iscypos < dest);
 	
	if ((isAbove != isAboveNow) || (wascypos == iscypos))
	{
 		// if we've just scrolled past the destination, or
 		// we haven't moved from the last scroll (i.e., we're at the
 		// bottom of the page) then scroll exactly to the link
 		window.scrollTo(0,dest);
 		// cancel the repeating timer
 		clearInterval(ss_INTERVAL);
 		// and jump to the link directly so the URL's right
 		location.hash = anchor;
 	}
}

function getCurrentYPos() 
{
 if (document.body && document.body.scrollTop)
   return document.body.scrollTop;
 if (document.documentElement && document.documentElement.scrollTop)
   return document.documentElement.scrollTop;
 if (window.pageYOffset)
   return window.pageYOffset;
 return 0;
}

var ss_INTERVAL;
var ss_STEPS = 100;
