// Copyright (c) 2007 Ric Hardacre 
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.

var ajax_release_version = "1.0.0";
var ajax_release_date    = "2007-03-15";

//request a string from the given URL
function ajax_RequestString( fCallback , sURL , sPost , userObject )
{
	return ajax_CreateRequest( fCallback , sURL , sPost , userObject , ajax_requestType_string , false )
}

//constants
var ajax_requestType_null = 0;
var ajax_requestType_string = 1;

var ajax_statusCode_null = 0;
var ajax_statusCode_ok = 200;
var ajax_statusCode_error = 500;
var ajax_statusCode_user = 600;
//you can also send your own status codes provided they are > 599 and < 1000

var ajax_enabled = ( window.XMLHttpRequest || window.ActiveXObject )

//delocalize newlines
function ajax_newlines( s )
{
    return s.replace(/\r\n|\r/g,"\n")
}

// spawns and returns a requestObject
function ajax_CreateRequest( fCallback , sURL , sPost , userObject , requestType , bSkipHeader )
{
    if( !fCallback || !ajax_enabled )
        return null;
       
    var hRO = new ajax_requestObject( fCallback , sURL , sPost , userObject , requestType , bSkipHeader )
    
    if( !hRO.m_HttpRequest )
        hRO = null;
        
    return hRO;
} 

// AJAX request object

// fCallback	= handle to callback function
// sURL			= url to make request to
// sPost		= POST form data to send (leave as "" for GET request)
// userObject   = user var - passed to callback
// requestType	= request type enum
// bSkipHeader	= (reserved)
function ajax_requestObject( fCallback , sURL , sPost , userObject , requestType , bSkipHeader )
{
	var me              = this;
	this.m_fCallback    = fCallback;
	this.m_sURL         = sURL;
	this.m_sPost        = sPost;
	this.m_requestType	= requestType;
	this.m_userObject   = userObject;
	this.m_bSkipHeader	= bSkipHeader;
	this.retry = function(){ ajax_retry( me ); };

	//spawn and attatch the request
	this.m_HttpRequest	= ajax_spawnRequest( me );
}	

// create a native httpRequest object from the paramrs in a requestObject and return
// hRO		= handle to request object
function ajax_spawnRequest( hRO )
{
	var l_HttpRequest = null;
	
	if( window.XMLHttpRequest )	//FF,NS,OP,IE7
	{
		l_HttpRequest = new XMLHttpRequest();
	}
	else
	if( window.ActiveXObject )	//IE5/6
	{
		l_HttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
	}

	if( l_HttpRequest )
	{
		if( hRO.m_sPost != "" )
		{
			l_HttpRequest.open( 'POST', hRO.m_sURL , true );
			l_HttpRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			l_HttpRequest.onreadystatechange = function(){ ajax_stateChange( hRO ); };
			l_HttpRequest.send( hRO.m_sPost );	
		}
		else
		{
			l_HttpRequest.open( 'GET', hRO.m_sURL , true );
			l_HttpRequest.onreadystatechange = function(){ ajax_stateChange( hRO ); };
			l_HttpRequest.send( null );	
		}
	}
	
	return l_HttpRequest;
}

// .retry() - resends a request
// hRO		= request object
function ajax_retry( hRO )
{
	//dont usurp a request in action
	if( hRO.m_HttpRequest && hRO.m_HttpRequest.readyState != 4 )
		return;
		
	hRO.m_HttpRequest = ajax_spawnRequest( hRO );
}

// ..onreadystatechange()
// hRO		= request object
function ajax_stateChange( hRO )
{
    //got a response?
	if( hRO && hRO.m_HttpRequest && hRO.m_HttpRequest.readyState == 4 )
	{
		var s = hRO.m_HttpRequest.responseText;
		var f = hRO.m_fCallback;
		
		//if the http status is 200 then we have a response!
		var statusCode = ajax_statusCode_error;
		if( hRO.m_HttpRequest.status == "200" )
		{
		    statusCode = parseInt( s.substr(0,3) );
		    
		    //bound to know codes but allow user to pass through 600 etc.
		    if( statusCode != ajax_statusCode_ok && statusCode != ajax_statusCode_error && statusCode < ajax_statusCode_user )
		        statusCode = ajax_statusCode_error;
		}
		
		// user recieves a null object if the status = 500
		// but they can still manually get to the http request response text if they need to
		var obj = null;
		if( statusCode == ajax_statusCode_ok || statusCode >= ajax_statusCode_user )
		{
			if( hRO.m_requestType == ajax_requestType_string )
				obj = s.substring(4)
		}
		
        //invoke user callback
		f( obj , statusCode , hRO );
	}
}

function notificationWindow(htmlcontent,delaytime)
{
	var notifywindow=document.getElementById("notifywindow");
	var mainbox=document.getElementById("mainbox");
	var passthrough="";
	var classname="notifywindow";
	if (typeof arguments[3] != 'undefined' && arguments[3] != '') { classname = arguments[3]; }
	if (typeof arguments[2] != 'undefined' && arguments[2] != '') { passthrough = arguments[2]; }
	if (!notifywindow) {
		notifywindow=document.createElement("div");
		notifywindow.id="notifywindow";
		notifywindow.className=classname;
		notifywindow.style.top =(getViewportScrollY()+91)+"px";
		setOpacity(mainbox,30);
		//notifywindow.appendChild(document.createTextNode(htmlcontent));
		notifywindow.innerHTML=htmlcontent;
		document.body.appendChild(notifywindow);
		if (delaytime>0) { setTimeout("killNotificationWindow('"+passthrough+"')",delaytime) }
	}
	return false;
}
function killNotificationWindow(passthrough)
{
	var notifywindow=document.getElementById("notifywindow");
	var mainbox=document.getElementById("mainbox");
	setOpacity(mainbox,100);
	if (!notifywindow) {return false;}
	document.body.removeChild(notifywindow);
	if (typeof arguments[0] != 'undefined' && arguments[0] != '') { 
		killNotificationWindow.func=eval("function(){"+arguments[0]+"}");
		killNotificationWindow.func();
	}

return false;
}

/* function setOpacity(objname,fadeamount)
{
	var fadetype='none';
	
	if(typeof objname.style.opacity != 'undefined') { fadetype = 'w3c'; }
	else if(typeof objname.style.MozOpacity != 'undefined') { fadetype = 'moz'; }
	else if(typeof objname.style.KhtmlOpacity != 'undefined') { fadetype = 'khtml'; }
	else if(typeof objname.filters == 'object') { fadetype = (objname.filters.length > 0 && typeof objname.filters.alpha == 'object' && typeof objname.filters.alpha.opacity == 'number') ? 'ie' : 'none'; }
	else { fadetype = 'none'; }
	
	switch(fadetype)
	{
		case 'ie' :
			objname.filters.alpha.opacity = fadeamount;
			break;
		case 'khtml' :
			objname.style.KhtmlOpacity = fadeamount;
			break;
		case 'moz' : 
			objname.style.MozOpacity = (fadeamount == 1 ? 0.9999999 : fadeamount);
			break;
		default : 
			objname.style.opacity = (fadeamount == 1 ? 0.9999999 : fadeamount);
	}
} */

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win
//  obj.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=" + opacity + ");";
  // Safari<1.2, Konqueror
//  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
 // obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}
// screen out older IE versions
function aaScreenIE() {
   if (navigator.appName == 'Microsoft Internet Explorer') {
     msie=navigator.appVersion.split("MSIE")
     version=parseFloat(msie[1]);
     if (version >= 6) return false;
   } else {
        return false;
   }
   return true;
}

// get stylesheet style
function aaGetStyle(obj, styleName) {
   if (obj.currentStyle) 
      return obj.currentStyle[styleName];
   else if (document.defaultView && document.defaultView.getComputedStyle) 
      return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
   return undefined;
}  

// add event listening
function aaManageEvent(eventObj, event, eventHandler) {
   if (eventObj.addEventListener) {
      eventObj.addEventListener(event, eventHandler,false);
   } else if (eventObj.attachEvent) {
      event = "on" + event;
      eventObj.attachEvent(event, eventHandler);
   }
}

// cancel event
function aaCancelEvent(event) {
   if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
   } else {
      event.returnValue = false;
      event.cancelBubble = true;
   }
}

// stop event listening
function aaStopEvent(eventObj,event,eventHandler) {
   if (eventObj.removeEventListener) {
      eventObj.removeEventListener(event,eventHandler,false);
   } else if (eventObj.detachEvent) {
      event = "on" + event;
      eventObj.detachEvent(event,getKey);
   }
}

// return element
function aaElem(identifier) { return document.getElementById(identifier); }

function getViewportScrollY() {
  var scrollY = 0;
  if( document.documentElement && document.documentElement.scrollTop ) { scrollY = document.documentElement.scrollTop; }
  else if( document.body && document.body.scrollTop ) { scrollY = document.body.scrollTop; }
  else if( window.pageYOffset ) { scrollY = window.pageYOffset; }
  else if( window.scrollY ) { scrollY = window.scrollY; }
  return scrollY;
};

// add script
function aaAddScript(url) {
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;
   document.getElementsByTagName('head')[0].appendChild(script);
 }

function aaBindEventListener(obj, method) { return function(event) { method.call(obj, event || window.event)}; }

function aaBindObjMethod(obj, method) { return function() { method.apply(obj, arguments); } }

function externalLinks() {
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}

aaManageEvent(window,'load',externalLinks);

