/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_10,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;if( typeof( Proxy ) == 'undefined' )
{
     // -----o Constructor 

    var Proxy ={}; 

     // -----o Static Public Methods 

     Proxy.create = function (o, f) { 
             var a =[]; 
             var l = arguments.length ; 
     
             for(var i = 2 ; i < l ; i++){ a[i - 2] = arguments;} 

             return function() { 
                   var aP = [].concat(arguments, a) ; 
                  f.apply(o,   aP); 
             }; 
     };
      
     // -----o Static Private Methods 
      
     Proxy.argumentsToArray = function (arg) { 
             var a =[] ; 
             var n = arg.length ; 
             for (var i = 2 ; i<n ; i++){ a[i-2] = arg;} 
             return a ; 
     }; 
}

if( typeof( EventDispatcher ) == 'undefined' )
{     
    EventDispatcher = function() {} 
     
     EventDispatcher.prototype.version = "1.0"
              
     // ---- 

     var c = EventDispatcher ; // class 
     var p = EventDispatcher.prototype ; // prototype 

     // ----o Static Methods 

     c.initialize = function (target /*Object*/ ) { 
             if (target == undefined) return null ; 
             var attributes = [ 
                  "addEventListener"   , "dispatchEvent", "eventListenerExists" , 
                  "removeAllEventListeners" , "removeEventListener" , "updateEvent" 
             ] ; 
             var i = new EventDispatcher ; 
             var l = attributes.length ; 
             while(--l > -1) { 
                   var prop = attributes[ l ] ; 
                  target [prop] = i[prop] ; 
             } 
     } 

     c.toString = function() /*String*/ { 
             return "[EventDispatcher]" ; 
     } 

     // -----o Private Properties 

     p._listeners = null ; 
      
     // -----o Private Methods 

     p.addEventListener = function ( eventName /*String*/ , obj /*Object*/, func ) /*Void*/ { 
             if (typeof(eventName) == "string") { 
                   if (this._listeners == null) this._listeners = {} ; 
                   var a = this._listeners[eventName] ; 
                   if (a == undefined) this._listeners[eventName] = a = [] ; 
                   if (EventDispatcher.indexOf( a , obj , func) == -1) { 
                        a.push( { o:obj , f:func } ) ; 
                   } 
             } 
     } 
      
     p.dispatchEvent = function ( ev /*Object*/ ) /*Void*/{
     	try{ 
             if ( typeof (ev.type) == "string") { 
                   if ( ev.type == "ALL") return ; 
                   var a ; 
                   if (ev.target == undefined) ev.target = this ; 
                   var f = this[ev.type + "_handler"] ; 
                   if (f != undefined ) f(ev) ; 
                   if( this._listeners ) a   = this._listeners[ev.type] ; 
                   if (a != undefined ) EventDispatcher.dispatch(ev.target, a, ev) ; 
                   if( this._listeners ) a   = this._listeners["ALL"] ; 
                   if (a != undefined) EventDispatcher.dispatch(ev.target, a, ev) ; 
             }
     	}
     	catch( err )
     	{
     		for( var i in err )
     		{
     			trace( i + ":" +  err[i] );
     		}
     	} 
     } 
      
     p.eventListenerExists = function (eventName/*String*/, obj /*Object*/, func/*Object*/) /*Boolean*/ { 
             var a = _listeners[eventName] ; 
             if (a == undefined) return false ; 
             return (EventDispatcher.indexOf(a, obj, func) > -1) ; 
     } 

     p.removeAllEventListeners = function(eventName/*String*/) /*Void*/ { 
             if (eventName) delete this._listeners[eventName] ; 
             else delete this._listeners ; 
     } 

     p.removeEventListener = function ( eventName /*String*/ , obj /*Object*/ , func /*Object*/ ) /*Void*/ { 
             var a = this._listeners[eventName] ; 
             if (a == undefined) return ; 
             var id = EventDispatcher.indexOf(a, obj, func) ; 
             if (id > -1) a.splice(id, 1) ; 
     } 
      
     p.updateEvent = function ( eventName/*String*/, oInit/*Object*/) /*Void*/ { 
             var ev = {} ; 
             ev.dynamic = true ; 
             ev.type = eventName ; 
             ev.target = this ; 
             if ( oInit != undefined ) for (var each in oInit) ev[each] = oInit[each] ; 
             this.dispatchEvent( ev ) ; 
     } 

     // ----o Static Private Methods 
      
     c.dispatch = function ( target /*Object*/ , a /*Array*/ , ev /*Object*/ ) /*Void*/ { 
             for (var each in a) { 
                   var item = a[each] ; 
                   var o = item.o ; 
                   var f = item.f ; 
                   var tof = typeof(o) ; 
                   if (tof == "object") { 
                        if (f instanceof Function) { 
                             var f = Proxy.create(o, f) ; 
                             if (f != undefined) f(ev) ; 
                        } else if (o["handleEvent"] != undefined && f == undefined) { 
                              o ["handleEvent"](ev) ; 
                        } else { 
                             if (f == undefined) f = ev.type ; 
                             if (typeof(f) == "string" && o[f] != undefined) { 
                                   o [f].apply(o, [ev]) ; 
                             } 
                        } 
                  }   else { // function 
                       if( o ) o.apply(target, [ev]) ; 
                   } 
             }      
      } 
      
     c.indexOf = function ( a /*Array*/ , o /*Object*/ , f /*Object*/ ) /*Number*/ { 
             var l = a.length ; 
             while (--l > -1) { 
                   var item = a[ l ] ; 
                   if (item.o == o && item.f == f) return l ; 
             } 
             return -1; 
     } 
      
     // ----o Encapsulate 

     delete c ; 
     delete p ;      
}       /***********************************************
* Cool DHTML tooltip script- ? Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
*************************************
STEPHEN ROWE - HACKED THIS TO PIECES FOR MY OWN USE - THANKS TO DYNAMICDRIVE.COM FOR THE INITIAL START

**********/

var offsetxpoint=10 //Customize x offset of tooltip
var offsetypoint=0 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var showBox=false;
if (ie||ns6)
{
	var boxObj = document.all ? document.all['boxover'] : (document.getElementById ? document.getElementById('boxover') : '');
}

var timeOutId;

var data = new Array();


function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function addElementBefore(node,tag,id,htm)
  {
    var ne = document.createElement(tag);
    if(id) ne.id = id;
    if(htm) ne.innerHTML = htm;
    node.parentNode.insertBefore(ne,node);
  }

  function addElementAfter(node,tag,id,htm)
  {
    var ne = document.createElement(tag);
    if(id) ne.id = id;
    if(htm) ne.innerHTML = htm;
    node.parentNode.insertBefore(ne,node.nextSibling);
  }


function addElement(parent, elementType, elementId) {
	if(!document.getElementById(elementId))
  	{
  		var pEl = document.getElementById(parent);
  		var nEl = document.createElement(elementType);
  		nEl.setAttribute('id',elementId);
  		pEl.appendChild(nEl);
  	}
}

function addAttribute(element, attrName, attrValue)
{
	 element.setAttribute(attrName, attrValue);
}

function removeElement(parent,elementId) {
	if(document.getElementById(elementId))
  	{
 		var pEl = document.getElementById(parent);
  		var nEl = document.getElementById(elementId);
  		pEl.removeChild(nEl);
  	}
}

function removeAllChildren(parent)
{
	var p = document.getElementById(parent);
	if (p)
	{
		while( p.hasChildNodes() ) { p.removeChild( p.lastChild ); }
	}
}

function encodeHtml(val) {
     encodedHtml = escape(val);
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
     return unescape(encodedHtml);
   } 

function setBox(id,data, obj){
	//find the boxover object and prepare its position	
	boxObj = document.getElementById(id); 

	//set the events
	if(ns6)
		document.captureEvents(Event.MOUSEMOVE);
			
	obj.onmousemove=positionBox;
	
	//don't build the data till time is up
	BOtimeOutId = window.setTimeout(function() { setData(data); }, 700);

}

function init(id,data, obj)
{
	//find the boxover object and prepare its position	
	boxObj = document.getElementById(id); 
	
	//set the events
	if(ns6)
	{
		document.captureEvents(Event.MOUSEMOVE);
	}

	obj.onmousemove = positionBox;
	
	//don't build the data till time is up
	BOtimeOutId = window.setTimeout(function() { draw(data); }, 900);
	
}
function initOperator(id,data, obj)
{
	//find the boxover object and prepare its position	
	boxObj = document.getElementById(id); 
	//set the events
	if(ns6)
		document.captureEvents(Event.MOUSEMOVE);
			
	obj.onmousemove=positionBox;
	
	//don't build the data till time is up
	BOtimeOutId = window.setTimeout(function() { drawOperator(data); }, 900);
	
}

function setData(data)
{


	removeElement('BObodyImage', 'BObodyImage_img' );
	removeElement('BOheadText', 'BOheadText_h1' );	

	
	if (ns6||ie){

		var SPAN_OPEN = " <span class='boxoverTextTitle'>";
		var SPAN_CLOSE = "</span> ";
		var string = '';
		
		for(i=0; i< data.length; i++ ) 
		{
				
			if(data[i][0] == 'BObodyImage')
			{
				addElement(data[i][0], 'img', data[i][0] + '_img' );
				document.getElementById(data[i][0] + '_img').src = data[i][2];
			
			} 
			else if(data[i][0] == 'BOheadText')
			{
			
				addElement(data[i][0], 'h1', data[i][0] + '_h1' );
				document.getElementById(data[i][0] + '_h1').innerHTML = data[i][2];
			
			} 
			else if(data[i][0] == 'status')
			{
				string = string + data[i][2] + "<br />";
			}
			else if( data[i][1] &&  data[i][2].length > 0 && data[i][2] != ' <!-- PLACEHOLDER --> ' )
			{
				
					string = string + SPAN_OPEN + data[i][1] + SPAN_CLOSE + data[i][2] + "<br />";
									
			}
		}

		document.getElementById("BObodyText").innerHTML = string;
		 		
		showBox = true;
		
		boxObj.style.visibility="visible";

	}
}

function positionBox(e){
	
	  	var curX;
	  	var curY;

		//Had to change this as firebug shows a event is not defined 	
	  	curX = (ns6) ? e.pageX : event.clientX+ietruebody().scrollLeft;
	  	curY = (ns6) ? e.pageY : event.clientY+ietruebody().scrollTop;		
			  
       
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
		
		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000		

		if( rightedge < boxObj.offsetWidth)		
			boxObj.style.left = ie? ietruebody().scrollLeft+event.clientX-boxObj.offsetWidth+"px" : window.pageXOffset+e.clientX-boxObj.offsetWidth+"px"
		else if (curX < leftedge)
			boxObj.style.left="5px"
		else
			boxObj.style.left=curX+offsetxpoint+"px"
	
		if ( bottomedge < boxObj.offsetHeight)
			boxObj.style.top=ie? ietruebody().scrollTop+event.clientY-boxObj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-boxObj.offsetHeight-offsetypoint+"px"
		else
			boxObj.style.top=curY+offsetypoint+"px"
			
		
	
}

function hideBox(id){
	window.clearTimeout(BOtimeOutId);
	if (ns6||ie){

		showBox=false;
		boxObj = document.getElementById(id);
		boxObj.style.visibility="hidden"
		boxObj.style.left="-1000px"
		boxObj.style.backgroundColor=''
		boxObj.style.width=''
	}
}
/* SR 23-12-08 - is this needed anymore - please delete if more than a month old and has not been uncommented
function MM_preloadImages(){var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}}
function MM_swapImgRestore(){ var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;}
function MM_findObj(n, d){ var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x;}
function MM_swapImage(){ var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}}
function MM_reloadPage(init){ if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }} else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();}
function MM_openBrWindow(theURL,winName,features){window.open(theURL,winName,features);}
function MM_callJS(jsStr){ return eval(jsStr)}
function MM_validateForm(){ var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);if (val) { nm=val.name; if ((val=val.value)!="") {if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';} else if (test!='R') { num = parseFloat(val);if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1);if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }} if (errors) alert('The following error(s) occurred:\n'+errors);document.MM_returnValue = (errors == '');}
MM_reloadPage(true);
*/
var $ = function( id ){	return document.getElementById( id ); };
var afl = new Object();
afl.document = new Object();

/** draws dots to the end of a string for each second that passes e.g. Calling . - Calling .. - Calling ... */
var dotTimerID;
afl.document.dotTimer = function( pElementId , pMessage , pNumberOfDots ){var secs;var state;var i;var dots = "";var element;element = document.getElementById( pElementId );time = new Date();secs = time.getSeconds();for( i = 0 ; i < ( state = secs % ( pNumberOfDots + 1 ) ) ; i++ )if( state != 0 )dots += ".";	element.innerHTML = pMessage + dots; dotTimerID = setTimeout( "dotTimer('" + pElementId + "' , '" + pMessage + "' , " + pNumberOfDots + " )" , 1000 );}

/**
* method replaces the value of elements of the specified name by the passed value
* @param elementName {String} The name of the elements to replace
* @param value {String} the string to place within those nodes
* @return {Boolean} Returns true if elements where replaced false if there were no elements
* @example afl.document.replaceElementsInPage( "wallet_points_available", "hello" ); // replaces the value of all  wallet_points_available with hello
*/
afl.document.replaceElementsInPage = function replaceElementsInPage( elementName, value ){var myElementsCollection = document.getElementsByTagName( elementName );if( myElementsCollection.length ){for( var i = 0; i < myElementsCollection.length; i++ ){myElementsCollection[ i ].innerHTML = value;}return true;}return false;}
/**
* method searchs through all elements of a certain type and replaces the value of all elements that have a certain attribute
* @param elementName {String} The name of the elements to replace
* @param attributeName {String} The name of the attribute to match against
* @param attributeValue {String} The value of the attribute to match against
* @param value {String} the string to place within those nodes
* @return {Boolean} Returns true if elements where replaced false if there were no elements
* @example afl.document.replaceElementsWithAttributeValue( "div", "class", "test", "hello" ); // replaces <div class="test">fdsdfsd</div> with <div class="test">hello</hello>
*/
afl.document.replaceElementsByAttributeValue = function replaceElementsByAttributeValue( elementName, attributeName, attributeValue, value ){var myElementsCollection = document.getElementsByTagName( elementName );if( myElementsCollection.length ){for( var i = 0; i < myElementsCollection.length; i++ ){if( myElementsCollection[ i ].getAttribute( attributeName ) == attributeValue  ){myElementsCollection[ i ].innerHTML = value;}}return true;}return false;}
afl.document.in_array = function(needle, haystack, strict) {var found = false, key; strict = !!strict; for(key in haystack) {if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {found = true; break;}}return found;}
afl.document.addElementBefore = function(node,tag,id,htm){ var ne = document.createElement(tag); if(id) ne.id = id; if(htm) ne.innerHTML = htm; node.parentNode.insertBefore(ne,node); }
afl.document.addElementAfter = function(node,tag,id,htm){var ne = document.createElement(tag); if(id) ne.id = id;if(htm) ne.innerHTML = htm; node.parentNode.insertBefore(ne,node.nextSibling);}
afl.document.addElement = function(parent, elementType, elementId) {if(!document.getElementById(elementId)){var pEl = document.getElementById(parent);var nEl = document.createElement(elementType);nEl.setAttribute('id',elementId);pEl.appendChild(nEl);}}
afl.document.addAttribute = function(element, attrName, attrValue){ element.setAttribute(attrName, attrValue);}
afl.document.removeElement = function(parent,elementId) {if(document.getElementById(elementId)){var pEl = document.getElementById(parent);var nEl = document.getElementById(elementId);pEl.removeChild(nEl);}}
afl.document.removeAllChildren = function(parent){var p = document.getElementById(parent);if (p){while( p.hasChildNodes() ) { p.removeChild( p.lastChild ); }}}
afl.document.encodeHtml = function(val) {encodedHtml = escape(val); encodedHtml = encodedHtml.replace(/\//g,"%2F"); encodedHtml = encodedHtml.replace(/\?/g,"%3F"); encodedHtml = encodedHtml.replace(/=/g,"%3D"); encodedHtml = encodedHtml.replace(/&/g,"%26"); encodedHtml = encodedHtml.replace(/@/g,"%40"); return unescape(encodedHtml);}
afl.document.ieTrueBody = function(){return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body }
afl.document.argumentsToArray = function (arg){ var a = new Array ; var n = arg.length ;for (var i = 2 ; i<n ; i++) a[i-2] = arg ;return a ;}
afl.document.Delegate = function() {}
afl.document.Delegate.create = function (o, f){	return function() {f.apply(o, arguments); }}// Constants for XmlHttp status

var			REQ_UNINITIALISED = 0;
var			REQ_LOADING = 1;
var			REQ_LOADED = 2;
var			REQ_INTERACTIVE = 3;
var			REQ_COMPLETE = 4;

function AjaxRequest()
{
	
	
	this.mRequest = this.getHttpRequest();
	this.mHandlers = new Array();

	// Need to assign 'this' to a variable so we can put it into the anonymous function
	
	var self = this;
	
	this.mRequest.onreadystatechange = function()
	{
		if(	self.mHandlers[ self.mRequest.readyState ] != undefined )
		{
			for( i = 0 ; i < self.mHandlers[ self.mRequest.readyState ].length ; i++ )
			{
				self.mHandlers[ self.mRequest.readyState ][ i ]( self );				
			}
		}
	}
}

AjaxRequest.prototype.addEventListener = function( pEventType, pFunction )
{
	if(	this.mHandlers[ pEventType ] == undefined )
	{
		this.mHandlers[ pEventType ] = new Array();
	}
	
	this.mHandlers[ pEventType ].push( pFunction );
}

AjaxRequest.prototype.getHttpRequest = function()
{
	// List of Microsoft XMLHTTP versions - newest first

	var MSXML_XMLHTTP_PROGIDS = new Array
	(	'MSXML2.XMLHTTP.6.0',
		'MSXML2.XMLHTTP.5.0',
		'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
	);

	// Do we support the request natively (eg, Mozilla, Opera, Safari, Konqueror)

	if( window.XMLHttpRequest != null )
	{
		return new XMLHttpRequest();
	}
	else
	{
		// Look for a supported IE version

		for( i = 0 ; MSXML_XMLHTTP_PROGIDS.length > i ; i++ )
		{
			try
			{
				return new ActiveXObject( MSXML_XMLHTTP_PROGIDS[ i ] );
			}
			catch( e )
			{
			}
		}
	}
	
	return( null );
}


//added by Stephen Rowe to allow a loading period
/*
load_display is args for the display options
func_name is the forwarding function name
2.. = args
*/
function ajaxLoadingInit( load_display )
{

	ajaxLoadDisplay( load_display );
	
	var methodArgs = ( typeof load_display.method == 'undefined' ) ? null : load_display.method;

	if( methodArgs )
	{
		var func_name = ( typeof methodArgs.func_name == 'undefined' ) ? null : methodArgs.func_name;
		
		if( func_name )
		{		
			var newArgs = [];

		    for(var i in methodArgs )
		    	if( methodArgs[i] != func_name )
		        	newArgs.push(methodArgs[i]);

			if( window[func_name] ) window[func_name].apply( this, newArgs );
		}
	}
	
}

function ajaxLoadDisplay( load_display )
{
		
	var mType = ( typeof load_display.type == 'undefined' ) ? 'image' : load_display.type;
   	
   	var mValue = ( typeof load_display.value == 'undefined' ) ? null : load_display.value;
   	
   	var mElement = ( typeof load_display.element == 'undefined' ) ? null : load_display.element;
   	
   	var mCss = ( typeof load_display.css == 'undefined' ) ? null : load_display.css;

   	var loadResult = null;
   	var loadResultHtml = '';

        if (!mValue)
        {
            mValue = '/assets/images/loading-spiral.gif';
        }

   	if( mType && mValue && mElement )
   	{
	   	if ( mType == 'image')
	   	{
                        loadResultHtml = '<table width="100%" height="100%"><tr>'
                            + '<td style="text-align: center" valign="center"><img class="loading_ani" src="'
                            + mValue + '" /></td></tr></table>';
	   		loadResult = document.createElement('img');
	   		loadResult.src = mValue;		
	   	}
	   	else if( mType == 'text')
	   	{
	   		loadResult = document.createElement('p');
	   		loadResult.innerHTML = mValue ;

		}
	
		if( loadResult && mCss )
	   			loadResult.className = mCss;
	   	
	   		
	   	if( document.getElementById(mElement) )
	   	{
                        if (loadResultHtml)
                        {
	   		    document.getElementById( mElement ).innerHTML = loadResultHtml;
                        }
                        else
                        {
	   		    document.getElementById( mElement ).innerHTML = "";
	   		    document.getElementById( mElement ).appendChild(loadResult);

                        }
	   	}
	   		
   	}
}
/*
 *  AdvancedAJAX 2.0 RC2
 *  (c) 2006 Lukasz Lach
 *  mail: anakin@php5.pl
 *  www:  http://advajax.anakin.us/
 *        http://anakin.us/
 * Licensed under Creative Commons GNU Lesser General Public License
 * http://creativecommons.org/licenses/LGPL/2.1/
 */
function advAJAX() {

    this.url = window.location.href;
    this.method = 'GET';
    this.parameters = new Object();
    this.headers = new Object();
    this.mimeType = null;
    this.username = null;
    this.password = null;

    this.useJSON = false;
    this.useCache = false;

    this.requestDone = false;
    this.requestAborted = false;
    this.requestTimedOut = false;

    this.queryString = '';
    this.responseText = null;
    this.responseXML = null;
    this.responseJSON = null;
    this.status = null;
    this.statusText = null;

    this.timeout = 0;
    this.retryCount = 0;
    this.retryDelay = 1000;
    this.retryNo = 0;

    this.repeat = false;
    this.repeatCount = 0;
    this.repeatNo = 0;
    this.repeatDelay = 1000;

    this.tag = null;
    this.group = null;
    this.form = null;
    this.disableForm = true;

    this.onInitialization = null;
    this.onFinalization = null;
    this.onAbort = null;
    this.onReadyStateChange = null;
    this.onLoading = null;
    this.onLoaded = null;
    this.onInteractive = null;
    this.onComplete = null;
    this.onSuccess = null;
    this.onFatalError = null;
    this.onInternalError = null;
    this.onError = null;
    this.onTimeout = null;
    this.onRetryDelay = null;
    this.onRetry = null;
    this.onRepeat = null;
    this.onRepeatDelay = null;
    this.onGroupEnter = null;
    this.onGroupLeave = null;

    this._xhr = null;
    this._eventHandled = [ false ];

    this._timerTimeout = null;
    this._timerRepeat = null;

    this.init = function() {

        (this._xhr !== null) && this.destroy();
        if ((this._xhr = this._createXHR()) === null)
            return false;
        if (typeof advAJAX._defaultParameters != 'undefined')
            this.handleArguments(advAJAX._defaultParameters);
        if (typeof this._xhr.overrideMimeType == 'function' && this.mimeType !== null)
            this._xhr.overrideMimeType(this.mimeType);
        this._eventHandled = [ this._eventHandled[0], false, false, false, false ];

        var _this = this;
        this._xhr.onreadystatechange = function() {

            if (_this.requestAborted)
                return;
            _this._raise('ReadyStateChange', _this._xhr.readyState);
            (!_this._eventHandled[_this._xhr.readyState]) && _this._handleReadyState(_this._xhr.readyState);
        };
        return true;
    };

    this.destroy = function(abort) {

        abort = abort || false;
        try {
            abort && this._xhr.abort();
            delete this._xhr['onreadystatechange'];
        } catch(e) {
        }
        ;
        this._xhr = null;
    };

    this._createXHR = function() {

        if (typeof XMLHttpRequest != 'undefined')
            return new XMLHttpRequest();
        var xhr = [ 'MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0',
                'MSXML2.XMLHttp', 'Microsoft.XMLHttp' ];
        for (var i = 0; i < xhr.length; i++) {
            try {
                var xhrObj = new ActiveXObject(xhr[i]);
                return xhrObj;
            } catch (e) {
            }
            ;
        }
        this._raise('FatalError');
        return null;
    };

    this._handleReadyState = function(readyState) {

        if (this._eventHandled[readyState])
            return;
        this._eventHandled[readyState] = true;
        switch (readyState) {
            /* loading */
            case 1:
                if (this.retryNo == 0 && this.group !== null) {
                    if (typeof advAJAX._groupData[this.group] == 'undefined') {
                        advAJAX._groupData[this.group] = 0;
                        this._raise('GroupEnter', this.group);
                    }
                    advAJAX._groupData[this.group]++;
                }
                this._raise('Loading', this);
                break;
            /* loaded */
            case 2:
                this._raise('Loaded', this);
                break;
            /* interactive */
            case 3:
                this._raise('Interactive', this);
                break;
            /* complete */
            case 4:
                window.clearTimeout(this._timerTimeout);
                if (this.requestAborted)
                    return;
                this.requestDone = true;
                this.responseText = this._xhr.responseText;
                this.responseXML = this._xhr.responseXML;
                try {
                    this.status = this._xhr.status || null;
                    this.statusText = this._xhr.statusText || null;
                } catch (e) {
                    this.status = null;
                    this.statusText = null;
                }
                this._raise('Complete', this);
                if (this.status == 200) {
                    try {
                        var _contentType = this._xhr.getResponseHeader('Content-type');
                        if (_contentType.match(/^text\/javascript/i))
                            eval(this.responseText); else
                        if (_contentType.match(/^text\/x\-json/i))
                            this.responseJSON = eval('(' + this.responseText + ')');
                    } catch(e) {
                        this._raise('InternalError', advAJAX.ERROR_INVALID_EVAL_STRING);
                    };
                    this._raise('Success', this);  
                } else
                    this._raise('Error', this);
                if (this.repeat) {
                    if (++this.repeatNo != this.repeatCount - 1) {
                        this._raise('RepeatDelay', this);
                        var _this = this;
                        this._timerRepeat = window.setTimeout(function() {
                            _this._raise('Repeat', this);
                            _this.init();
                            _this.run();
                        }, this.repeatDelay);
                        return;
                    }
                }
                this.destroy();
                (this.disableForm) && this._switchForm(true);
                this._handleGroup();
                this._raise('Finalization', this);
        }
    };

    this._handleGroup = function() {

        if (this.group === null) return;
        (--advAJAX._groupData[this.group] == 0) && this._raise('GroupLeave', this);
    }

    this._onTimeout = function() {

        if (this._xhr == null || this._eventHandled[4])
            return;
        this.requestAborted = this.requestTimedOut = true;
        this._xhr.abort();
        this._raise('Timeout');
        if (this.retryNo++ < this.retryCount) {
            this.init();
            this._raise('RetryDelay', this);
            var _this = this;
            this._timerTimeout = window.setTimeout(function() {
                _this._raise('Retry', _this);
                _this.run();
            }, this.retryDelay);
        } else {
            this.destroy();
            (this.disableForm) && this._switchForm(true);
            this._handleGroup();
            this._raise('Finalization', this);
        }
    };

    this.run = function() {

        if (this.init() == false)
            return false;
        this.requestAborted = this.requestTimedOut = false;
        (!this._eventHandled[0]) && (this._raise('Initialization', this)) && (this._eventHandled[0] = true);
        if (this.retryNo == 0 && this.repeatNo == 0) {
            if (this.useJSON) {
                if (typeof [].toJSONString != 'function') {
                    this._raise('InternalError', advAJAX.ERROR_NO_JSON);
                    return;
                }
                for (var p in this.parameters) {
                    var useJson = typeof [].toJSONString == 'function';
                    (this.queryString.length > 0) && (this.queryString += '&');
                    this.queryString += encodeURIComponent(p) + '=' +
                                        encodeURIComponent(this.parameters[p].toJSONString());
                }
            } else {
                for (var p in this.parameters) {
                    (this.queryString.length > 0) && (this.queryString += '&');
                    if (typeof this.parameters[p] != "object")
                        this.queryString += encodeURIComponent(p) + '=' + encodeURIComponent(this.parameters[p]); else {
                        if (!(this.parameters[p] instanceof Array)) continue;
                        for (var i = 0, cnt = this.parameters[p].length; i < cnt; i++)
                            this.queryString += encodeURIComponent(p) + '=' + encodeURIComponent(this.parameters[p][i]) + '&';
                        this.queryString = this.queryString.slice(0, -1);
                    }
                }
            }
            (this.method == 'GET') && (this.queryString.length > 0) && (this.url += (this.url.indexOf('?') != -1 ? '&' : '?') + this.queryString);
        }
        (this.disableForm) && this._switchForm(false);
        try {
            this._xhr.open(this.method, this.url, true, this.username || '', this.password || '');
        } catch(e) {
            this._raise('FatalError', this);
            return false;
        }
        var _this = this;
        (this.timeout > 0) && (this._timerTimeout = window.setTimeout(function() {
            _this._onTimeout();
        }, this.timeout));
        if (typeof this._xhr.setRequestHeader == 'function') {
            if (this.method == 'GET' && !this.useCache)
                this._xhr.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
            for (var p in this.headers)
                this._xhr.setRequestHeader(encodeURIComponent(p), encodeURIComponent(this.headers[p]));
        }
        if (this.method == 'POST') {
            try {
                this._xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            } catch(e) {
            };
            this._xhr.send(this.queryString);
        } else if (this.method == 'GET') {
            this._xhr.send('');
        }
    };

    this.getResponseHeader = function(name) {

        return this._xhr.getResponseHeader(name) || null;
    };

    this.getAllResponseHeaders = function() {

        return this._xhr.getAllResponseHeaders() || null;
    };

    this.abort = function() {

        this.requestAborted = true;
        window.clearTimeout(this._timerTimeout);
        window.clearTimeout(this._timerRepeat);
        this._handleGroup();
        this._raise('Abort', this);
        this.destroy();
        this._raise('Finalization', this);
    },

    this._extendObject = function(target, source) {

        for (var p in source)
            target[p] = source[p];
    };

    this.handleArguments = function(args) {

        (typeof args['form'] == 'string') && (args['form'] = document.getElementById(args['form']));
        for (var p in args) {
            if (typeof this[p] == 'undefined') {
                this.parameters[p] = args[p];
            } else {
                if (p != 'parameters' && p != 'headers') {
                    this[p] = args[p];
                } else
                    this._extendObject(this[p], args[p]);
            }
        }
        this.method = this.method.toUpperCase();
        (typeof this.form == 'object') && (this.form !== null) && this._appendForm();
        (args.repeat) && (this.repeatCount++);
    };

    this._switchForm = function(enable) {

        if (typeof this.form != 'object' || this.form === null)
            return;
        var _f = this.form;
        for (var i = 0; i < _f.elements.length; i++)
            if (!enable) {
                if (_f.elements[i]['disabled'])
                    _f.elements[i]['_disabled'] = true; else
                    _f.elements[i]['disabled'] = 'disabled';
            } else {
                if (typeof _f.elements[i]['_disabled'] == 'undefined' || _f.elements[i]['_disabled'] === null)
                    _f.elements[i]['disabled'] = '';
                try {
                    delete _f.elements[i]['_disabled'];
                } catch(e) {
                    _f.elements[i]['_disabled'] = null;
                };
            }
    };

    this._appendForm = function() {

        var _f = this.form;
        this.method = _f.getAttribute('method').toUpperCase();
        this.url = _f.getAttribute('action');
        for (var i = 0; i < _f.elements.length; i++) {
            var _e = _f.elements[i];
            if (_e.disabled)
                continue;
            switch (_e.type) {
                case 'text':
                case 'password':
                case 'hidden':
                case 'textarea':
                    this._addParameter(_e.name, _e.value);
                    break;
                case 'select-one':
                    if (_e.selectedIndex >= 0)
                        this._addParameter(_e.name, _e.options[_e.selectedIndex].value);
                    break;
                case 'select-multiple':
                    var _r = [];
                    for (var j = 0; j < _e.options.length; j++)
                        if (_e.options[j].selected)
                            _r[_r.length] = _e.options[j].value;
                    (_r.length > 0) && (this._addParameter(_e.name, _r));
                    break;
                case 'checkbox':
                case 'radio':
                    (_e.checked) && (this._addParameter(_e.name, _e.value));
                    break;
            }
        }
    };

    this._addParameter = function(name, value) {

        if (typeof this.parameters[name] == 'undefined') {
            this.parameters[name] = value;
        } else {
            if (typeof this.parameters[name] != 'object')
                this.parameters[name] = [ this.parameters[name], value ]; else
                this.parameters[name][this.parameters[name].length] = value;
        }
    };

    this._delParameter = function(name) {

        delete this.parameters[name];
    };

    this._raise = function(name) {

        for (var i = 1, args = []; i < arguments.length; args[args.length] = arguments[i++]);
        (typeof this['on' + name] == 'function') && (this['on' + name].apply(null, args));
        (name == 'FatalError') && this._raise('Finalization', this);
    }

}

advAJAX._groupData = new Object();
advAJAX._defaultParameters = new Object();

advAJAX.get = function(args) {

    return advAJAX._handleRequest('GET', args);
}
advAJAX.post = function(args) {

    return advAJAX._handleRequest('POST', args);
}
advAJAX.head = function(args) {

    return advAJAX._handleRequest('HEAD', args);
}
advAJAX._handleRequest = function(requestType, args) {

    args = args || { };
    var _a = new advAJAX();
    _a.method = requestType;
    _a.handleArguments(args);
    setTimeout(function() {
        _a.run()
    }, 0);
    return _a;
};
advAJAX.submit = function(form, args) {

    args = args || {};
    if (typeof form == 'undefined' || form === null)
        return false;
    var _a = new advAJAX();
    args['form'] = form;
    _a.handleArguments(args);
    setTimeout(function() {
        _a.run()
    }, 0);
    return _a;
};
advAJAX.assign = function(form, args) {

    args = args || {};
    (typeof form == 'string') && (form = document.getElementById(form));
    if (typeof form == 'undefined' || form === null)
        return false;
    form['_advajax_args'] = args;
    var _onsubmit = function(event) {
        event = event || window.event;
        if (event.preventDefault) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            event.returnValue = false;
            event.cancelBubble = true;
        }
        var _e = event.target || event.srcElement;
        return !advAJAX.submit(_e, _e['_advajax_args']);
    }
    if (form.addEventListener) {
        form.addEventListener('submit', _onsubmit, false);
    } else if (form.attachEvent) {
        form.attachEvent('onsubmit', _onsubmit);
    }
    return true;
};
advAJAX.download = function(target, url) {

    (typeof target == 'string') && (target = document.getElementById(target));
    if (typeof target == 'undefined' || target === null)
        return false;
    advAJAX.get({
        'url': url,
        'onSuccess' : function(o) {
            target.innerHTML = o.responseText;
        }
    });
};
advAJAX.setDefaultParameters = function(args) {

    advAJAX._defaultParameters = new Object();
    for (var a in args)
        advAJAX._defaultParameters[a] = args[a];
};

advAJAX.ERROR_INVALID_EVAL_STRING = -1;
advAJAX.ERROR_NO_JSON = -2;function ToolTip(tt)
{
	this.toolTipElement= tt;
	this.Params = {	'offsetXPoint'	: 10,
					'offsetYPoint'	: 0,
					'showBox'		: false,
					'delayedId'		: null,
					'delayedTime'	: 700,
					'browser' 		: navigator.userAgent.toLowerCase(),
					'isIE'			: (navigator.appName == "Microsoft Internet Explorer"),
					'isNS'			: (navigator.appName == "Netscape")};
	this.Params.isSafari = (this.Params.browser.indexOf("safari") > -1);

};
ToolTip.prototype.onMouseOver = function (obj)
{
	if(this.Params.isNS)
		document.captureEvents(Event.MOUSEMOVE);
	obj.onmousemove=afl.document.Delegate.create(this,this.position);
	obj.onmouseout=afl.document.Delegate.create(this,this.hide);
	this.start();
};
ToolTip.prototype.start = function()
{
	if(this.Params.delayedId == null)
		this.Params.delayedId = window.setTimeout(afl.document.Delegate.create(this, this.draw), this.Params.delayedTime);

	return;
};
ToolTip.prototype.stop = function()
{
	if(this.Params.delayedId != null)
		window.clearTimeout(this.Params.delayedId);
	this.Params.delayedId = null;
	return;
};
ToolTip.prototype.restart = function()
{
	this.stop();
	this.start();
};
ToolTip.prototype.draw = function(){/** This is an abstarct func and should be overidden */}
ToolTip.prototype.position = function(e){

	  	var curX = (this.Params.isNS) ? e.pageX : event.clientX+afl.document.ieTrueBody().scrollLeft;
	  	var curY = (this.Params.isNS) ? e.pageY : event.clientY+afl.document.ieTrueBody().scrollTop;
		var rightedge= (this.Params.isIE&&!window.opera)? afl.document.ieTrueBody().clientWidth-event.clientX-this.Params.offsetXPoint : window.innerWidth-e.clientX-this.Params.offsetXPoint-20
		var bottomedge=(this.Params.isIE&&!window.opera)? afl.document.ieTrueBody().clientHeight-event.clientY-this.Params.offsetYPoint : window.innerHeight-e.clientY-this.Params.offsetYPoint-20

		var leftedge=(this.Params.offsetXPoint<0)? this.Params.offsetXPoint*(-1) : -1000

		if( rightedge < this.toolTipElement.offsetWidth)
			this.toolTipElement.style.left = ((this.Params.isIE)? afl.document.ieTrueBody().scrollLeft+event.clientX-this.toolTipElement.offsetWidth : window.pageXOffset+e.clientX-this.toolTipElement.offsetWidth)+"px";
		else if (curX < leftedge)
			this.toolTipElement.style.left="5px"
		else
			this.toolTipElement.style.left=curX+this.Params.offsetXPoint+"px"

		if ( bottomedge < this.toolTipElement.offsetHeight)
			this.toolTipElement.style.top=((this.Params.isIE)? afl.document.ieTrueBody().scrollTop+event.clientY-this.toolTipElement.offsetHeight-this.Params.offsetYPoint : window.pageYOffset+e.clientY-this.toolTipElement.offsetHeight-this.Params.offsetYPoint)+"px"
		else
			this.toolTipElement.style.top=curY+this.Params.offsetYPoint+"px"
	
};

ToolTip.prototype.hide = function(e){
	this.stop();
	if (this.Params.isIE||this.Params.isNS){
		this.Params.showBox=false;
		this.toolTipElement.style.visibility="hidden"
	}
};var ImageProtection = {};

ImageProtection.message =  "These photos are copyright protected. All rights reserved. Unauthorized use prohibited.";

ImageProtection.rightClickProtect = function(e) {
    if (window.event){
        var el = event.srcElement ? event.srcElement : event.target;
    }
    else{
        var el = e.srcElement ? e.srcElement : e.target;
    }

    var tagName = el.tagName;

    if (tagName == 'IMG'){
        window.alert(ImageProtection.message);
        return false;
    }
    else{
        return true;
    }
}

document.oncontextmenu = ImageProtection.rightClickProtect;
function PopupManager()
{
	this.mPopupsAllowed = 10;
	this.mPopups = new Array( this.mPopupsAllowed );
}

PopupManager.prototype.addPopup = function( pPopup )
{
	for( i = 0 ; i < this.mPopupsAllowed ; i++ )
	{
		if( this.mPopups[ i ] == null )
		{
			this.mPopups[ i ] = pPopup;
			
			return( i );
		}
	}
	
	return( null );
}

PopupManager.prototype.remPopup = function( pPopup )
{
	for( i = 0 ; i < this.mPopupsAllowed ; i++ )
	{
		if( this.mPopups[ i ] === pPopup )
		{
			this.mPopups[ i ] = null;
		}
	}
}

PopupManager.prototype.getPopup = function( pIndex )
{
	return( this.mPopups[ pIndex ] );
}

function posTop() 
	{
		var vertical_positioning = typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;
			vertical_positioning = vertical_positioning/10;
			vertical_positioning =  Math.ceil(vertical_positioning);
			vertical_positioning = vertical_positioning * 10;
		return vertical_positioning;
	}

gPopupManager = new PopupManager();

function PopupMessage( j )
{
	
	this.mMessageId = null;
	this.mHeight = 150;
	this.mWhere = 10;
	this.mTimer = null;
	this.mTimeout = 8000;
	this.mTimeoutHandler = null;
	this.mHasTimedOut = false;
	this.mCompleteHandler = null;
	this.mSpeed = 1;
	this.mSelectedOption = null;
	this.vScroll = posTop();
	this.offset = j;
	
	this.mOptions = new Array();
	
	var PageBody = document.getElementsByTagName( "body" ).item( 0 );
	
	this.mContainer = document.createElement( "div" );

	this.mContainer.className = "pmContainer";
	this.mContainer.style.top = "-" + this.mHeight + "px";

	PageBody.appendChild( this.mContainer );
	
	this.mPopupId = gPopupManager.addPopup( this );
	
	//this.mWhere += ( this.mHeight * this.mPopupId );
	
	totalOffset = ((this.offset) * 90) + this.mWhere;

	this.mWhere =  this.vScroll +  totalOffset;

}

PopupMessage.prototype.fromHtml = function( pHtml )
{
	this.mContainer.innerHTML = pHtml;
	this.startAnimate();

}



PopupMessage.prototype.fromXml = function( pXml )
{
			this.mMessageId = pXml.getElementsByTagName( 'messageid' ).item( 0 ).childNodes.item( 0 ).nodeValue  ;


			PopupTitle = pXml.getElementsByTagName( 'title' ).item( 0 ).childNodes.item( 0 ).nodeValue;


			PopupText  = pXml.getElementsByTagName( 'text' ).item( 0 ).childNodes.item( 0 ).nodeValue;

			PopupOptions = pXml.getElementsByTagName( 'options' ).item( 0 ).getElementsByTagName( 'option' );

			OptionHtml = '';

			if( PopupOptions.length > 0 )
			{
				OptionHtml += "<div>";

				for( i = 0 ; i < PopupOptions.length ; i++ )
				{
					Text = PopupOptions.item( i ).getElementsByTagName( 'text' ).item( 0 ).childNodes.item( 0 ).nodeValue;

					this.mOptions[ i ] = new Object();

					if( PopupOptions.item( i ).getElementsByTagName( 'url' ).item( 0 ) )
					{
						Data = PopupOptions.item( i ).getElementsByTagName( 'url' ).item( 0 ).childNodes.item( 0 ).nodeValue;

						this.mOptions[ i ].url = Data;
					}
					else if( PopupOptions.item( i ).getElementsByTagName( 'call' ).item( 0 ) )
					{
						Data = PopupOptions.item( i ).getElementsByTagName( 'call' ).item( 0 ).childNodes.item( 0 ).nodeValue;

						this.mOptions[ i ].code = Data;
					}
					else if( PopupOptions.item( i ).getElementsByTagName( 'ajax' ).item( 0 ) )
					{
						Data = PopupOptions.item( i ).getElementsByTagName( 'ajax' ).item( 0 ).childNodes.item( 0 ).nodeValue;

						this.mOptions[ i ].ajax = Data;
					}

					OptionHtml += "<div><a href=\"javascript:void(0);\" onClick=\"popupDispatch('" + this.mPopupId + "','" + i + "');return(false);\">" + Text + "</a></div>";
				}

				OptionHtml += "</div>";
			}

			this.fromHtml( "<div><div style=\"font-weight: bold;\">" + PopupTitle + "</div><div>" + PopupText + "</div>" + OptionHtml + "</div> " );


			//<object id=\"MediaPlayer4\" classid=\"CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab# Version=5,1,52,701\" standby=\"Loading Microsoft Windows? Media Player components...\" type=\"application/x-oleobject\" width=\"0\" height=\"0\"><param name=\"fileName\" value=\"/assets/sounds/piggrunt2.wav\" /><param name=\"autoStart\" value=\"start\" /><param name=\"showControls\" value=\"false\" /><embed src=\"/assets/sounds/piggrunt2.wav\" hidden=\"true\" autostart=\"true\"></object>
}

PopupMessage.prototype.fromObject = function( obj )
{
            this.mMessageId = obj.message_id;

            PopupTitle = obj.title;
            PopupText  = obj.text;
            PopupOptions = obj.options;

            OptionHtml = '';

            if( PopupOptions.length > 0 )
            {
                OptionHtml += "<div>";

                for( i = 0 ; i < PopupOptions.length ; i++ )
                {
                    Text = PopupOptions[i].text;
                    this.mOptions[ i ] = new Object();
                    if( PopupOptions[i].url)
                    {
                        this.mOptions[ i ].url = PopupOptions[i].url;
                    }
                    else if( PopupOptions[i].call)
                    {
                        this.mOptions[ i ].code = PopupOptions[i].call;
                    }
                    else if( PopupOptions[i].ajax)
                    {
                        this.mOptions[ i ].ajax = PopupOptions[i].ajax;
                    }

                    OptionHtml += "<div><a href=\"javascript:void(0);\" onClick=\"popupDispatch('" + this.mPopupId + "','" + i + "');return(false);\">" + Text + "</a></div>";
                }

                OptionHtml += "</div>";
            }

            this.fromHtml( "<div><div style=\"font-weight: bold;\">" + PopupTitle + "</div><div>" + PopupText + "</div>" + OptionHtml + "</div> " );


            //<object id=\"MediaPlayer4\" classid=\"CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab# Version=5,1,52,701\" standby=\"Loading Microsoft Windows? Media Player components...\" type=\"application/x-oleobject\" width=\"0\" height=\"0\"><param name=\"fileName\" value=\"/assets/sounds/piggrunt2.wav\" /><param name=\"autoStart\" value=\"start\" /><param name=\"showControls\" value=\"false\" /><embed src=\"/assets/sounds/piggrunt2.wav\" hidden=\"true\" autostart=\"true\"></object>
}

PopupMessage.prototype.startAnimate = function()
{
	var		self = this;

	setTimeout( function() { self.doAnimate( self ) }, this.mSpeed );

}

PopupMessage.prototype.doAnimate = function( pPopup )
{
	var		Position = parseInt( pPopup.mContainer.style.top );

	if( Position != pPopup.mWhere )
	{
		pPopup.mContainer.style.top = Position + ( pPopup.mWhere < Position ? -10 : 10 ) + "px";

		pPopup.startAnimate();
	}
	else if( Position > 0 )
	{

		pPopup.startTimer();
	}
	else if( Position < 0 )
	{
		if( pPopup.mHasTimedOut )
		{
			clearTimeout( pPopup.mTimer );
			
			pPopup.mTimer = null;
			
			if( pPopup.mTimeoutHandler != null )
			{
				pPopup.mTimeoutHandler( pPopup );
			}
		}
	}
}

PopupMessage.prototype.startTimer = function()
{
	var		self = this;

	this.mTimer = setTimeout( function() { self.doTimeout( self ) }, this.mTimeout );
}

PopupMessage.prototype.doTimeout = function( pPopup )
{
	pPopup.mHasTimedOut = true;
	
	pPopup.completeMessage();

	pPopup.closeMessage();
}

PopupMessage.prototype.setTimeoutHandler = function( pFunction )
{
	this.mTimeoutHandler = pFunction;
}

PopupMessage.prototype.setCompleteHandler = function( pFunction )
{
	this.mCompleteHandler = pFunction;
}

PopupMessage.prototype.closeMessage = function()
{
	if( this.mTimer != null )
	{
		clearTimeout( this.mTimer );

		this.mTimer = null;
	}
	
	this.mWhere = 0 - this.mHeight;

	this.startAnimate();

	
}

PopupMessage.prototype.completeMessage = function()
{
	if( this.mCompleteHandler != null )
	{
		this.mCompleteHandler( this );
	}
	
	gPopupManager.remPopup( this );
}

function popupDispatch( pPopupId, pOptionId )
{
	if( ( Popup = gPopupManager.getPopup( pPopupId ) ) != null )
	{
		Popup.mSelectedOption = pOptionId;
		
		Popup.completeMessage();
		
		if( ( PopupOption = Popup.mOptions[ pOptionId ] ) != null )
		{
			if( ( Url = PopupOption.url ) != null )
			{
				window.location = Url;
			}
			else if( ( Code = PopupOption.code ) != null )
			{
				Popup.closeMessage();
				
				eval( Code );
			}
			else if( ( Ajax = PopupOption.ajax ) != null )
			{
				Popup.closeMessage();

				AjaxRequest = new AjaxRequest();
	
				if( AjaxRequest.mRequest )
				{
					AjaxRequest.mRequest.open( "GET", Ajax, true );
					AjaxRequest.mRequest.send( null );
				}
			}
			else
			{
				Popup.closeMessage();
			}
		}
		else
		{
			Popup.closeMessage();
		}
	}
}
function processIM( pAjax )
{

	//Alerts = pAjax.mRequest.responseXML.getElementsByTagName( 'alerts' );
	if( pAjax.mRequest.status == 200 )
	{
		Alert = pAjax.mRequest.responseXML.getElementsByTagName( 'alert' );

		if (Alert.length > 0 )
       	{
	 		var Message_storage ="";
			for( j = 0 ; j < Alert.length ; j++ )
			{
				Message = new PopupMessage(j);
				Message.mUserId = pAjax.mUserId;
				Message.fromXml( Alert.item( j ) );

				Message.setTimeoutHandler( timeoutIM );
				Message.setCompleteHandler( completeIM);
			}


		}
		else if (!usingPushServer)
		{
			var	UserId = pAjax.mUserId;

			setTimeout( function() { checkInstantMessages( UserId ); }, 10000 );

		}
	}
}

function timeoutIM( pPopup )
{
	//alert( "Popup " + pPopup.mPopupId + " timed out" );
}

function completeIM( pPopup )
{
	var		UserId = pPopup.mUserId;

	//alert( "Popup " + pPopup.mPopupId + " complete" );

	var Ajax = new AjaxRequest();

	if( Ajax.mRequest )
	{

		RequestUrl = "/ajax/alerts.php?m_id=" + UserId + "&p_id=" + pPopup.mMessageId;

		if( pPopup.mSelectedOption != null )
		{
			RequestUrl += "&o_id=" + pPopup.mSelectedOption;
		}

		Ajax.mRequest.open( "GET", RequestUrl , false );
		Ajax.mRequest.send( null );
	}

    if (!usingPushServer) {
	    setTimeout( function() { checkInstantMessages( UserId ); }, 10000 );
    }


}

function getQueryMode() { 
	var query = window.location.search.substring(1); 
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) { 
		var pair = vars[i].split("="); 
		if (pair[0] == 'mode') { 
			return pair[1]; 
		}
	}
}

function checkInstantMessages( pUserId, bypassChat )
{
	
	
	if(typeof(bypassChat) == 'undefined') bypassChat = false;
	
	var query_mode = getQueryMode();

	// because in some case we might not have a mode in the querystring, it can generates a  js error
	if(query_mode) 
		if(bypassChat && (getQueryMode().toLowerCase() == 'chat')) return;
	
	
	var Ajax = new AjaxRequest();

	if( Ajax.mRequest )
	{
		Ajax.mUserId = pUserId;

		Ajax.addEventListener( REQ_COMPLETE, processIM );
		Ajax.mRequest.open( "GET", "/ajax/alerts.php?m_id=" + pUserId, true );
		Ajax.mRequest.send( null );
	}

}


function getFlashMovie(movieName)
{
    return (navigator.appName.indexOf("Microsoft") != -1)
        ? window[movieName]
        : document[movieName];
}

function sendFlash(cmd, args)
{
    data = '[{"cmd":"' + cmd + '","args":["' + args.join('","') + '"]}]';
    getFlashMovie('client').sendData(data);
}

var usingPushServer = false;
function onConnect(success)
{
    if (success)
    {
        usingPushServer = true;
        sendFlash('CONNECT', [sid, 'U' + uid]);
        sendFlash('JOIN', [sid, '#users']);
    }
}

function onDisconnect()
{
    if (usingPushServer)
    {
        usingPushServer = false;

    }
}

function onData(data)
{
    eval('var cmd = ' + data);
    switch (cmd.cmd.toUpperCase())
    {
    case 'ALERT':
        //alert('received an alert! data:\n' + data);
        var Message_storage = "";
        Message = new PopupMessage(0);
        Message.mUserId = uid;
        Message.fromObject(cmd.args[0]);
        Message.setTimeoutHandler(timeoutIM);
        Message.setCompleteHandler(completeIM);
        break;
    case 'PING':
        sendFlash('PONG', [sid]);
        break;
    }
}

