
var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects="";
var rootdomain="http://"+window.location.hostname;
var currentLocation;
var ajax_history; var ajax_history_frame;
var page_loading_url = '';
var ajax_history_frame_url = '/server-js/ajaxloading.htt';
var isIE=0;
    
/* 
enable history feature
embed into main htt
<div id="ajax_history" style="display:none;visibility:hidden;"></div>
<iframe style="border: 0px; width: 0px; height: 0px; position: absolute; bottom: 0px; right: 0px; visibility: hidden; display: none;" name="ajax_history_frame" id="ajax_history_frame" src="/server-js/ajaxloading.html?"></iframe>
onload=historyInitialize(url,container);
*/    
    
function historyInitialize(url,containerid) {
	ajax_history = document.getElementById('ajax_history');
	ajax_history_frame = document.getElementById('ajax_history_frame');	


	if(ajax_history!=null){
		isInternetExplorer();
		currentLocation = new Date().getTime();
		window.location.hash = currentLocation;
		historyStore(url,containerid);
		var locationHandler = function() {
			checkLocation();
	      };
		setInterval(locationHandler, 100);
	}
}

function isInternetExplorer() {
      var userAgent = navigator.userAgent.toLowerCase();
      if (document.all && userAgent.indexOf('msie')!=-1) {
         isIE = 1;
	 return true;
      }
      else {
      	 isIE = 0;
         return false;
      }
   }

function getIFrameHash() {
      // get the new location
      
      
      var historyFrame = document.getElementById("ajax_history_frame");
      var doc = historyFrame.contentWindow.document;
      var hash = new String(doc.location.search);

      if (hash.length == 1 && hash.charAt(0) == "?")
         hash = "";
      else if (hash.length >= 2 && hash.charAt(0) == "?")
         hash = hash.substring(6); 
    
    
      return hash;
}


function checkLocation(){
      // get hash location
     var hash = getCurrentLocation();
	if(isIE){
		var ihash = getIFrameHash();
		if(ihash){hash = ihash;}
	
	}
       // see if there has been a change
      if (hash == currentLocation)
         return;
// forward	 
// alert(hash);
	if (currentLocation < hash){
	var container = document.getElementById('Container'+hash).innerHTML;
	var url = document.getElementById('URL'+hash).innerHTML;	
	var content = document.getElementById('Content'+hash).innerHTML;	
//	var url = document.getElementById(hash+'-url').innerHTML;
//	alert(currentLocation + ' ' + hash + ' ' + container + '   ' + url );
//	ajaxpage(url,container,1)
	 	document.getElementById(container).innerHTML=content;
		currentLocation = hash;

	}else{
// back
	//alert('back');



	var container = document.getElementById('Container'+hash).innerHTML;
	var url = document.getElementById('URL'+hash).innerHTML;	
	var content = document.getElementById('Content'+hash).innerHTML;	
//	var url = document.getElementById(hash+'-url').innerHTML;
//	alert(currentLocation + ' ' + hash + ' ' + container + '   ' + url );
//	ajaxpage(url,container,1)
	
	 	document.getElementById(container).innerHTML=content;
		currentLocation = hash;

	
	}
	//evaljs(container);
	
	if(isIE){
		if(ajax_history_frame==null){ return; }
		document.getElementById("ajax_history_frame").src=ajax_history_frame_url+'?hash='+hash+'#'+hash;
		window.location.hash = hash;
	}
}

function getCurrentLocation() {
      var currentLocation = removeHash(window.location.hash);
      return currentLocation;
}


function removeHash(hashValue) {
      if (hashValue == null || hashValue == undefined)
         return null;
      else if (hashValue == "")
         return "";
      else if (hashValue.length == 1 && hashValue.charAt(0) == "#")
         return "";
      else if (hashValue.length > 1 && hashValue.charAt(0) == "#")
         return hashValue.substring(1);
      else
         return hashValue;     
}

     
/*
Active History vs. Passive / Traditional History

GET = result not reget
POST = result not repost, 304 redirects missed

*/
function historyStore(url,containerid){
	if(ajax_history==null){ return; }


	var hash = new Date().getTime();

	var nContainer = document.createElement('div');
	nContainer.id='Container'+hash;
	nContainer.style.display = 'none';
	nContainer.innerHTML = containerid;
	ajax_history.appendChild(nContainer);

	var nurl = document.createElement('div');
	nurl.id='URL'+hash;
	nurl.style.display = 'none';	
	nurl.innerHTML = url;
	ajax_history.appendChild(nurl);


	var nContent = document.createElement('div');
	nContent.id='Content'+hash;
	nContent.style.display = 'none';	
	nContent.innerHTML = document.getElementById(containerid).innerHTML;
	ajax_history.appendChild(nContent);
//	alert(nContent.innerHTML);
//	alert(document.getElementById('URL'+hash).innerHTML);

	if(isIE){
		
		if(ajax_history_frame==null){ return; }
		document.getElementById("ajax_history_frame").src=ajax_history_frame_url+'?hash='+hash+'#'+hash;
	}
	
	
	window.location.hash = hash;
//	setTimeout('document.getElementById("ajax_history_frame").contentWindow.document.body.innerHTML="'+url+'"',100);	

}

eval_container_contents = {}

function eval_all(containerid,eval_type){
	var to_eval = document.getElementById(containerid+'_' +eval_type); // || document.getElementById(containerid);
	
	if(to_eval){
		
		
		var innerCode = to_eval.innerText;
		if(innerCode==null){
			innerCode = to_eval.innerHTML;
		}
		
		if(innerCode.match(/^\s*<pre>/i)){
			innerCode = to_eval.firstChild.innerHTML;
		}
		
		if(innerCode){
			innerCode = innerCode.replace(/&lt;/g,'<');
			innerCode = innerCode.replace(/&gt;/g,'>');
			innerCode = innerCode.replace(/&quot;/g,'"');
			eval(innerCode);
		}
	}else if(document.getElementById(containerid)){
		if(!eval_container_contents[containerid] || document.getElementById(containerid).innerHTML != eval_container_contents[containerid][eval_type]){
			setTimeout('eval_all("'+containerid+'","'+eval_type+'")',250);
			if (!eval_container_contents[containerid]){ eval_container_contents[containerid] = {}; }
			eval_container_contents[containerid][eval_type] = document.getElementById(containerid).innerHTML;

		}
		
		
	}
	
	
}



function loadpage(page_request, url, containerid,storehistory){
	
	 
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		document.getElementById(containerid).innerHTML=page_request.responseText;
		if(document.getElementById('ajaxpage_loading')){
			document.getElementById('ajaxpage_loading').style.display='none';
		}
		
		if(!storehistory){
			historyStore(url,containerid);
		}	
		
		// change to unified single function (as will be used in thandlereval to load thandler json)
		eval_all(containerid,'jseval');
		eval_all(containerid,'iditableeval');
		eval_all('global','jseval');
		//eval_all(containerid,'thandlereval');
		//evaljs(containerid);
		//evaliditable(containerid);
	
//		alert(page_request.getResponseHeader('Location'));
//		alert(page_request.getAllResponseHeaders());
		
	}
	

}	

function ajaxpage(url, containerid,storehistory){
	// needed because js (ie, iditable) turns %26 => &amp; 
	// which can't be "re-translated" to function as a url
	url = url.replace(/&amp;/g,'&');  
	
	var page_request = false;	
	if(document.getElementById('ajaxpage_loading')){
		document.getElementById('ajaxpage_loading').style.display='block';
	}
	

	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	}	
	else if (window.ActiveXObject){ // if IE
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
		try{
		page_request = new ActiveXObject("Microsoft.XMLHTTP")
		}
		catch (e){}
		}
	}
	else
		return false
	
	
	
	page_request.onreadystatechange=function(){
		loadpage(page_request, url, containerid,storehistory);
	
	}
//	page_loading(url, containerid);

	
	if (bustcachevar) //if bust caching of external page
	var bustcacheparameter=(url.indexOf("?")!=-1)? "&cache="+new Date().getTime() : "?cache="+new Date().getTime()
	
	
	
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)




	
	//alert(containerid);
	


}
var activeNavigationElements;
function activeNavigation(navName,navID,navClassOn,navClassOff){

	if(navName){
		var navs;
	
//		alert(navName+' '+typeof activeNavigationElements);
		var dom = 1;
		if(activeNavigationElements && typeof activeNavigationElements == 'object'){
			navs = activeNavigationElements[navName];
			dom = 0;			
		}else if(navigator.appVersion.match(/MSIE/)){
			var tag = 'DIV'; // default because no other way to know if navid is empty
			if(navID && document.getElementById(navID)){
				tag = document.getElementById(navID).nodeName;
			}
			navs = getElementsByName_iefix(tag,navName);

		}else{
			navs = document.getElementsByName(navName);
		}


	
		for(var i in navs){
		
			if(dom){
				navs[i].className=navClassOff;
			}else{
				if(navs[i] && document.getElementById(navs[i])){
					document.getElementById(navs[i]).className=navClassOff;
				}
			}
		}
	}
	if(navID && document.getElementById(navID)){
		document.getElementById(navID).className=navClassOn;
	}
}


function delayajaxpage(url,containerid,pausefor,storehistory){
	alert('ERROR: Deprecated'); 
	setTimeout("ajaxpage('" + url + "','" + containerid + "'," + storehistory + ")",pausefor);
}


function loadobjs(){
	if (!document.getElementById)
		return
	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
		if (file.indexOf(".js")!=-1){ //If object is a js file
			fileref=document.createElement('script')
			fileref.setAttribute("type","text/javascript");
			fileref.setAttribute("src", file);
		}
		else if (file.indexOf(".css")!=-1){ //If object is a css file
			fileref=document.createElement("link")
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", file);
		}
		}
		if (fileref!=""){
		document.getElementsByTagName("head").item(0).appendChild(fileref)
		loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}



function callInProgress(xmlhttp) {
	switch ( xmlhttp.readyState ) {
		case 1: case 2: case 3:
		return true;
		break;

		// Case 4 and 0
		default:
		return false;
		break;
	}
} 

function createXMLHttpRequest() {
	var ua;
	if(window.XMLHttpRequest) {
		try {
			ua = new XMLHttpRequest();
		} catch(e) {
			ua = false;
		}
	} else if(window.ActiveXObject) {
		var tryPossibleVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp"];
		for(i=0;i<tryPossibleVersions.length;i++){
			try{
				ua = new ActiveXObject(tryPossibleVersions[i]);
				break;
			}catch(xmlHttpRequestObjectError){
			// Ignore Exception
			}
		}

	}

	return ua;
}

function page_loading(url,containerid){
	var page_load = createXMLHttpRequest();
	page_load.onreadystatechange = function(){loadpage(page_load, url, containerid);}
	page_load.open('GET', page_loading_url, true);
	page_load.send(null);
	return;
}

function ajaxform(frm, file,containerid) {

	if(document.getElementById('ajaxpage_loading')){
		document.getElementById('ajaxpage_loading').style.display='block';
	}
	var req = createXMLHttpRequest();

	var rnd982g = Math.random();
	var str = getForm(frm);


	if(str) {
		var url = file;
		req.onreadystatechange = function(){ loadpage(req,url,containerid); }

		var extradata;
		if(file.match(/\?/)){
			extradata = file.substr(file.indexOf('?')+1,file.length);
		}
		extradata = extradata + '&' + str + '&rnd982g='+rnd982g;
		url = url.substr(0,url.length);
		//	 document.getElementById('error').innerHTML=url+'?'+extradata;
		req.open('POST',url,true);
		req.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", str.length);
		req.setRequestHeader("Connection", "close");
		req.send(extradata);

		//	 req.send(null);
	}



	return false;
}



function getForm(fobj) {
	var str = "";
	var ft = "";
	var fv = "";
	var fn = "";
	var els = "";


	for(var i = 0;i < fobj.elements.length;i++) {
		els = fobj.elements[i];
		ft = els.title;
		fv = els.value;
		fn = els.name;

		switch(els.type) {
			case "text":
			case "hidden":
			case "password":
			case "textarea":
			// is it a required field?

			// was encodeURI
			str += fn + "=" + escape(fv) + "&";
			break; 

			case "checkbox":
			case "radio":
			if(els.checked) str += fn + "=" + escape(fv) + "&";
			break;	

			case "select-one":

			for (var cnt = 0; cnt < els.options.length; cnt++){
				if (els.options[ cnt ].selected){
					str += fn + "=" + els.options[ cnt ].value + "&";
				}
			}
			break;
			case "select-multiple":

			for (var cnt = 0; cnt < els.options.length; cnt++){
				//alert(els.options[ cnt ].value + ' - ' + els.options[ cnt ].selected);
				if (els.options[ cnt ].selected){
				str += fn + "=" + els.options[ cnt ].value + "&";

			}

		}
		break;

		} // switch
	} // for

	str = str.substr(0,(str.length - 1));
	return str;
}


function getElementsByName_iefix(tag, name, parent) {

     var elem;
  
     if (parent && document.getElementById(parent)){
	     elem = document.getElementById(parent).getElementsByTagName(tag);
	    
     }else{
	     elem = document.getElementsByTagName(tag);
     }
   
     var arr = new Array();
     for(i = 0; i < elem.length; i++) {
	  att = elem[i].getAttribute("name");
	
	  if(att == name) {
		  
	       arr[arr.length] = elem[i];
	  }
     }
     return arr;
}

var js_included;
function js_include(script_filename) {

	if(!js_included[script_filename]){
		var html_doc = document.getElementsByTagName('head').item(0);
		var js = document.createElement('script');
		js.setAttribute('language', 'javascript');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', script_filename);
		html_doc.appendChild(js);
		js_included[script_filename] = 1;
		return false;
	}
}

var ajaxanchor = {
 /*
  fixAllLinks: function() {
    // Get a list of all links in the page
    var allLinks = document.getElementsByTagName('a');
    // Walk through the list
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) && 
          ( (lnk.pathname == location.pathname) ||
	    ('/'+lnk.pathname == location.pathname) ) && 
          (lnk.search == location.search)) {
        // If the link is internal to the page (begins in #)
        // then attach the go function as an onclick
        // event handler
        ajaxanchor.addEvent(lnk,'click',ajaxanchor.go);
      }
    }
  },
*/
  go: function(anchor) {
    // This is an event handler; get the clicked on element,
    // in a cross-browser fashion
 /*
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;

    // Make sure that the target is an element, not a text node
    // within an element
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }
  
    // Paranoia; check this is an A tag
    if (target.nodeName.toLowerCase() != 'a') return;
 */ 
    // Find the <a name> tag corresponding to this href
    // First strip off the hash (first character)
//    anchor = target.hash.substr(1);
//	anchor = document.getElementById('anchor').value;
    // Now loop all A tags until we find one with that name
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }
    if (!destinationLink) destinationLink = document.getElementById(anchor);

    // If we didn't find a destination, give up and let the browser do
    // its thing
    if (!destinationLink) return true;
  
    // Find the destination's position
    var destx = destinationLink.offsetLeft; 
    var desty = destinationLink.offsetTop - ( destinationLink.style.pixelHeight ?  destinationLink.style.pixelHeight : destinationLink.offsetHeight);
    var thisNode = destinationLink;
    while (thisNode.offsetParent && 
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }
  
    // Stop any current scrolling
    clearInterval(ajaxanchor.INTERVAL);
  
    cypos = ajaxanchor.getCurrentYPos();
  
    ss_stepsize = parseInt((desty-cypos)/ajaxanchor.STEPS);
    ajaxanchor.INTERVAL =
setInterval('ajaxanchor.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
  /*
    // And stop the actual click happening
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
    */
  },

  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ajaxanchor.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ajaxanchor.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(ajaxanchor.INTERVAL);
      // and jump to the link directly so the URL's right
      //location.hash = anchor;
    }
  },

  getCurrentYPos: function() {
    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;
  }
/*
  addEvent: function(elm, evType, fn, useCapture) {
    // addEvent and removeEvent
    // cross-browser event handling for IE5+,  NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  } 
 */
}

ajaxanchor.STEPS = 25;

