var ajaxobject_array=[];
var ajax_endfunction_array=[];
var ajax_timeout_array=[];
var ajax_array_index=0;
var ajax_queue=[];
var ajax_queue_index;
var ajax_current_count=0;
var using_exploder=0;

function GetXmlHttpObject()
{   
    var objXMLHttp=null;
    if (window.XMLHttpRequest)
        {
            objXMLHttp=new XMLHttpRequest();
        }
    else if (window.ActiveXObject)
        {
            objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
            if (objXMLHttp==null)
                objXMLHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
    return objXMLHttp;
}

function lgp_ajax_statechange(index)
{
    if (ajaxobject_array[(0+index)].readyState==4 || ajaxobject_array[(0+index)].readyState=="complete")
        {
	    ajax_current_count--;

	    if (ajaxobject_array[(0+index)].status==200)
		ajax_endfunction_array[(0+index)](ajaxobject_array[(0+index)].responseText);
	    else
		ajax_endfunction_array[(0+index)]("");

	    ajaxobject_array[(0+index)]=null;
	    ajax_endfunction_array[(0+index)]=null;
	    clearTimeout(ajax_timeout_array[(0+index)]);
	    ajax_timeout_array[(0+index)]=null;

	    lgp_ajax_process_queue();
	}
}


function lgp_ajax_timeout(index)
{
    ajaxobject_array[0+index].abort();
    ajax_endfunction_array[(0+index)]("");
    ajaxobject_array[(0+index)]=null;
    ajax_endfunction_array[(0+index)]=null;
    ajax_timeout_array[(0+index)]=null;

    ajax_current_count--;

    lgp_ajax_process_queue();
}

function lgp_ajax_process_queue()
{
    var queuearray;

    if (ajax_queue.length==0)
	return;

    queuearray=ajax_queue.shift();

    lgp_ajax(queuearray[0],queuearray[1],queuearray[2]);
}

function lgp_ajax(ajax_url,end_function,postparams)
{
    var this_handler;
    var queuearray;

    if (ajax_current_count>1)
    {
	//Queue here
	queuearray=[];
	queuearray[0]=ajax_url;
	queuearray[1]=end_function;
	queuearray[2]=postparams;

	ajax_queue.push(queuearray);
	return;
    }

    ajax_current_count++;

    if (ajax_url.indexOf('?')==-1)
	ajax_url+='?';
    else
	ajax_url+='&';
    ajax_url+='lgp_ajax_nc='+utime();

    this_handler=ajax_array_index++;

    ajax_endfunction_array[this_handler]=end_function;
    
    ajaxobject_array[this_handler]=GetXmlHttpObject();
    
    ajaxobject_array[this_handler].onreadystatechange=new Function('lgp_ajax_statechange('+this_handler+')');
    if (postparams)
    {
	ajaxobject_array[this_handler].open("POST",ajax_url,true);

	ajaxobject_array[this_handler].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxobject_array[this_handler].setRequestHeader("Content-length", postparams.length);
	ajaxobject_array[this_handler].setRequestHeader("Connection", "close");

	ajaxobject_array[this_handler].send(postparams);
    }
    else
    {
	ajaxobject_array[this_handler].open("GET",ajax_url,true);
	ajaxobject_array[this_handler].send(null);
    }

    ajax_timeout_array[this_handler]=setTimeout(new Function('lgp_ajax_timeout('+this_handler+')'),180000);
    
    return;
}

/* 
   THIS APPLIES TO URLENCODE AND URLDECODE
 * More info at: http://kevin.vanzonneveld.net/techblog/category/php2js
 * 
 * php.js is copyright 2008 Kevin van Zonneveld.
 * 
 * Portions copyright Ates Goral (http://magnetiq.com), Legaev Andrey,
 * _argos, Jonas Raoni Soares Silva (http://www.jsfromhell.com),
 * Webtoolkit.info (http://www.webtoolkit.info/), Carlos R. L. Rodrigues, Ash
 * Searle (http://hexmen.com/blog/), Tyler Akins (http://rumkin.com), mdsjack
 * (http://www.mdsjack.bo.it), Alexander Ermolaev
 * (http://snippets.dzone.com/user/AlexanderErmolaev), Andrea Giammarchi
 * (http://webreflection.blogspot.com), Bayron Guevara, Cord, David, Karol
 * Kowalski, Leslie Hoare, Lincoln Ramsay, Mick@el, Nick Callen, Peter-Paul
 * Koch (http://www.quirksmode.org/js/beat.html), Philippe Baumann, Steve
 * Clay, booeyOH
 * 
 * Licensed under the MIT (MIT-LICENSE.txt) license.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES 
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
 * OTHER DEALINGS IN THE SOFTWARE.
 */
function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
	    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
	    return "%"+m2.toUpperCase();
	});
    
    return ret;
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
	    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

//document.write('<span id=debug></span>');
function debug(text)
{
    var element;
    element=document.getElementById('debug');
    if (element)
	element.innerHTML=text;
}
function adebug(text)
{
    var element;
    element=document.getElementById('debug');
    if (element)
	element.innerHTML+=text;
}

function setCookie(name,value,expiredays,domain,path)
{
    var expiredate=new Date();
    expiredate.setDate(expiredate.getDate()+expiredays);
    document.cookie=name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+expiredate.toGMTString())+
	"; domain="+domain+"; path="+path+";";
}

function set_opacity(element,opacity)
{
    var opacity_fraction;

    if (opacity > 100)
        {
            opacity_fraction = 1;
            opacity = 100;
        }
    else if (opacity < 1)
        {
            opacity_fraction = 0;
            opacity = 1;
        }
    else
        opacity_fraction = opacity/100;


    element.style.opacity = (opacity_fraction);
    element.style.filter  = 'alpha(opacity=' + opacity + ')';
}

var lgp_fading_objects=[];

function do_fade_any_object(elementname,opacity,post_fn)
{
    var element=document.getElementById(elementname);

    opacity-=10;
    if (opacity < 1)
	opacity=0;
    set_opacity(element,opacity);

    if (opacity > 0)
	setTimeout('do_fade_any_object(\''+elementname+'\','+opacity+',\''+post_fn+'\');',100);
    else 
	{
	    lgp_fading_objects[elementname]=0;
	    if (post_fn)
		eval(post_fn);
	}
}

function fade_any_object(elementname,post_fn)
{
    if (lgp_fading_objects[elementname]==1)
	return;
    lgp_fading_objects[elementname]=1;

    if (post_fn==undefined)
	post_fn='';
    do_fade_any_object(elementname,100,post_fn);
}

function do_expose_any_object(elementname,opacity,post_fn)
{
    var element=document.getElementById(elementname);

    opacity+=10;
    if (opacity > 99)
	opacity=100;
    set_opacity(element,opacity);

    if (opacity < 100)
	setTimeout('do_expose_any_object(\''+elementname+'\','+opacity+',\''+post_fn+'\');',100);
    else 
	{
	    lgp_fading_objects[elementname]=0;
	    if (post_fn)
		eval(post_fn);
	}
}

function expose_any_object(elementname,post_fn)
{
    if (lgp_fading_objects[elementname]==1)
	return;
    lgp_fading_objects[elementname]=1;

    if (post_fn==undefined)
	post_fn='';
    do_expose_any_object(elementname,0,post_fn);
}

var lgp_expanding_objects=[];

function do_shrink_any_object(elementname,post_fn,speed)
{
    var element=document.getElementById(elementname);

    var height=element.offsetHeight;
    height-=speed;

    if (height<1)
	height=1;
    element.style.height=height+'px';

    if (height>1)
	setTimeout('do_shrink_any_object(\''+elementname+'\',\''+post_fn+'\','+speed+');',100);
    else
	{
	    lgp_expanding_objects[elementname]=0;
	    if (post_fn)
		eval(post_fn);
	}
}

function shrink_any_object(elementname,post_fn,speed)
{
    if (lgp_expanding_objects[elementname]==1)
	return;

    lgp_expanding_objects[elementname]=1;

    if (post_fn==undefined)
	post_fn='';
    
    if (speed==undefined)
	speed=5;

    do_shrink_any_object(elementname,post_fn,speed);
}

function do_expand_any_object(elementname,target,post_fn,speed)
{
    var element=document.getElementById(elementname);

    var height=element.offsetHeight;
    height+=speed;

    if (height>target)
	height=target;
    element.style.height=height+'px';

    if (height<target)
	setTimeout('do_expand_any_object(\''+elementname+'\','+target+',\''+post_fn+'\','+speed+');',100);
    else
	{
	    element.style.height='auto';
	    lgp_expanding_objects[elementname]=0;
	    if (post_fn)
		eval(post_fn);
	}
}

function expand_any_object(elementname,post_fn,speed)
{
    if (lgp_expanding_objects[elementname]==1)
	return;

    lgp_expanding_objects[elementname]=1;

    if (post_fn==undefined)
	post_fn='';
    
    if (speed==undefined)
	speed=5;

    var element=document.getElementById(elementname);
    var height=element.offsetHeight;

    element.style.height='auto';

    var target=element.offsetHeight;

    element.style.height=height+'px';

    do_expand_any_object(elementname,target,post_fn,speed);
}


function toggle_expand_any_object(elementname,post_fn,speed)
{
    if (lgp_expanding_objects[elementname]==1)
	return;

    var element=document.getElementById(elementname);
    var height=element.offsetHeight;

    if (post_fn==undefined)
	post_fn='';

    if (speed==undefined)
	speed=5;

    if (height<3)
	expand_any_object(elementname,post_fn,speed);
    else
	shrink_any_object(elementname,post_fn,speed);
 }

function print_r(arr,level) 
{
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') 
	{ //Array/Hashes/Objects 
	    for(var item in arr) 
		{
		    var value = arr[item];
		    
		    if(typeof(value) == 'object')
			{ //If it is an array,
			    dumped_text += level_padding + "'" + item + "' ...\n";
			    dumped_text += print_r(value,level+1);
			} 
		    else 
			{
			    dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} 
    else 
	{ //Stings/Chars/Numbers etc.
	    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
    return dumped_text;
}


var lgp_resize_oldwidth=-1;
var lgp_resize_basesize;
var lgp_resize_passthrough;
var lgp_resize_min=0;
var lgp_resize_max=0;
function lgp_size_screen()
{
    var width;
    var ratio;
    var absratio;

    width=self.innerWidth;
    if (!(width>0))
	width=document.body.clientWidth;
    
    if (width==lgp_resize_oldwidth)
	return;

    if (lgp_resize_oldwidth==-1)
	lgp_resize_oldwidth=lgp_resize_basesize;

    ratio=width/lgp_resize_oldwidth;

    absratio=width/lgp_resize_basesize;

    if (lgp_resize_min>0 && absratio < lgp_resize_min)
	{
	    return;
	}
    else if (lgp_resize_max>0 && absratio > lgp_resize_max)
	{
	    return;
	}

    var stylesheets;
    var loopa;
    var loopb;

    stylesheets = document.styleSheets;

    for (loopa=0; loopa < stylesheets.length; loopa++)
	{
	    var sheet;
	    var rules;

	    sheet = stylesheets.item(loopa);
	    if (sheet.cssRules)
		rules = sheet.cssRules;
	    else
		rules = sheet.rules;

	    for (loopb = 0; loopb<rules.length; loopb++)
		{
		    var rule;
		    var text;

		    rule = rules.item(loopb);
		    if (rule && -1==rule.selectorText.indexOf('fixedsize'))
			{
			    text=rule.style.fontSize;

			    if (text)
				{
				    var val=parseFloat(text);
				    val*=ratio;
				    if (text.indexOf('%',0)>-1)
					rule.style.fontSize=''+val+'%';
				    else if (text.indexOf('pt',0)>-1)
					rule.style.fontSize=''+val+'pt';
				    else if (text.indexOf('in',0)>-1)
					rule.style.fontSize=''+val+'in';
				    else if (text.indexOf('cm',0)>-1)
					rule.style.fontSize=''+val+'cm';
				    else if (text.indexOf('mm',0)>-1)
					rule.style.fontSize=''+val+'mm';
				    else if (text.indexOf('em',0)>-1)
					rule.style.fontSize=''+val+'em';
				    else if (text.indexOf('pc',0)>-1)
					rule.style.fontSize=''+val+'pc';
				    else
					rule.style.fontSize=''+val;
				}
			}
		}
	}


    lgp_resize_oldwidth=width;
    
    if (lgp_resize_passthrough!='')
	{
	    eval(lgp_resize_passthrough+'('+width+');');
	}
}

function lgp_resizable_screen(state,basesize,passthrough,min,max)
{
    if (state==1)
	{
	    if (passthrough==undefined)
		lgp_resize_passthrough='';
	    else
		lgp_resize_passthrough=passthrough;
	    if (min==undefined)
		lgp_resize_min=0;
	    else
		lgp_resize_min=min;
	    if (max==undefined)
		lgp_resize_max=0;
	    else
		lgp_resize_max=max;
	    lgp_resize_basesize=basesize;
	    window.onresize=lgp_size_screen;
	    //Run once to size

	    lgp_size_screen();
	}
    else
	window.onresize=null;;
	
}

if (!document.getElementsByClassName)
{
    document.getElementsByClassName = function(class_name) 
	{
	    var docList = this.all || this.getElementsByTagName('*');
	    var matchArray = new Array();
	
	    /*Create a regular expression object for class*/
	    var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
	    for (var i = 0; i < docList.length; i++) 
		{
		    if (re.test(docList[i].className) ) 
			{
			    matchArray[matchArray.length] = docList[i];
			}
		}
	    
	    return matchArray;
	}
}

var included_files=[];
function js_include(filename)
{
    var script;

    if (included_files[filename])
	return;

    included_files[filename]=1;

    var body = document.getElementsByTagName('body').item(0);
    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    body.appendChild(script);
}

function htmlencode(input)
{
    var text = document.createTextNode(input);
    var div = document.createElement('div');
    div.appendChild(text);
    return div.innerHTML;
}


function htmldecode(input)
{
    var div = document.createElement('div');
    div.innerHTML = input;
    return div.childNodes[0].nodeValue;
}

var lgp_dialog_parts=[];
if (navigator.appName == 'Microsoft Internet Explorer')
{
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
	using_exploder=1;
}

function lgp_dialog()
{
    var div=document.createElement('div');
    if (using_exploder)
	div.style.position='absolute';
    else
	div.style.position='fixed';
    div.style.top='0px';
    div.style.left='0px';
    div.style.width='100%';
    div.style.height='100%';
    div.style.background='#888888';
    div.style.zIndex='100';
    set_opacity(div,40);
    document.body.appendChild(div);
    lgp_dialog_parts['basediv']=div;

    div=document.createElement('div');
    if (using_exploder)
	div.style.position='absolute';
    else
	div.style.position='fixed';
    div.style.top='0px';
    div.style.left='0px';
    div.style.width='100%';
    div.style.height='100%';
    div.style.zIndex='101';
    document.body.appendChild(div);
    lgp_dialog_parts['containerdiv']=div;
    
    div.innerHTML='<table border=0 width=100% height=100%><tr><td align=middle valign=middle><div id=lgp_dialog_div></div></td></tr></table>';

    return document.getElementById('lgp_dialog_div');
}

function lgp_dialog_close()
{
    if (lgp_dialog_parts['basediv'])
	{
	    if (lgp_dialog_parts['basediv'].removeNode)
		lgp_dialog_parts['basediv'].removeNode(true);
	    else
		lgp_dialog_parts['basediv'].parentNode.removeChild(lgp_dialog_parts['basediv']);
	    lgp_dialog_parts['basediv']=null;
	}
    if (lgp_dialog_parts['containerdiv'])
	{
	    if (lgp_dialog_parts['containerdiv'].removeNode)
		lgp_dialog_parts['containerdiv'].removeNode(true);
	    else
		lgp_dialog_parts['containerdiv'].parentNode.removeChild(lgp_dialog_parts['containerdiv']);

	    lgp_dialog_parts['containerdiv']=null;
	}
}

function time()
{
    var dateobj = new Date();
    now = parseInt(dateobj.getTime()/1000);
    return now;
}

function utime()
{
    var dateobj = new Date();
    now = dateobj.getTime()/1000;
    return now;
}

function number_trailer(num)
{
    switch (num%100)
	{
	case 11:
	case 12:
	case 13:
	    return 'th';
	}
    switch (num%10)
	{
	case 1:
	    return 'st';
	case 2:
	    return 'nd';
	case 3:
	    return 'rd';
	}
    return 'th';
}

function num2hexcol(num) 
{
    if (num >255)
	return 'FF';
    if (num < 16)
	return '0'+parseInt(num,10).toString(16);
    return parseInt(num,10).toString(16);
}

function abspos(name)
{
    var ele;
    var left,top;

    ele=document.getElementById(name);
    
    if (!ele)
	return null;

    left=parseInt(ele.offsetLeft);
    top=parseInt(ele.offsetTop);

    /*
    if (document.all)
	{
	    ele = ele.parentElement;	
	    while (ele.tagName != "BODY")
		{
		    top+=parseInt(ele.offsetTop);
		    left+=parseInt(ele.offsetLeft);
		    ele = ele.parentElement;	
		}
	}
    else
	{
	    ele = ele.parentNode;
	    while (ele.tagName != "HTML")
		{
		    top+=parseInt(ele.offsetTop);
		    left+=parseInt(ele.offsetLeft);
		    ele = ele.parentNode;
		}
	}
    */

    ele = ele.offsetParent;
    while (ele)
	{
	    left += ele.offsetLeft;
	    top += ele.offsetTop;
	    ele = ele.offsetParent;
	}

    var rv=[];
    rv['top']=top;
    rv['left']=left;
    return rv;
}

function lgp_screen_size()
{
    rv=[];

    rv['w']=document.body.clientWidth;

    if (rv['w']>0)
    {
	rv['h']=document.body.clientHeight;
    }
    else
    {
	rv['h']=self.innerHeight;
	rv['w']=self.innerWidth;
    }

    return rv;
}

if (!window.JSON)
{
    try
    {
	js_include('/js/json.js');
    }
    catch (err)
    {
    }
}

