
// IMPORTANT!
// While developing this should be false
var LOG_TO_SERVER = false;


var safari = /KHTML/.test(navigator.userAgent);

var nbsp = String.fromCharCode(160);

var currentProgress = null;

// hover popups data
var gHoverPopup = new Object();
gHoverPopup.status = 0; // 0=not in use, 1=open
gHoverPopup.el = null;

// mouse over el
var gMouseOverEl = '';

/***********************************
*     logging
***********************************/

var LOG_CURRENT_LEVEL = 3;
var LOGFATAL = 1;
var LOGERROR = 2;
var LOGWARNING = 3;
var LOGINFO = 4;
var LOGDEBUG = 5;

var LOGFLIGHTS = 1;
var LOGABOUT = 2;
var LOGUSER = 3;

var LOG_INTERVAL = 1000*60*3; // used for warn, info, debug
var LOG_MAXLOGS = 100;
var gLogTimeoutId = null;
var gLogArray = new Array();

function loadIFrame(url,jsprefix)
{
	var ifr = document.createElement("IFRAME");
	ifr.width=1;ifr.height=1;ifr.frameBorder=0;
	
	if(jsprefix)
	{
		document.getElementById('jsiframeholder').appendChild(ifr);
		var doc = ifr.contentDocument?ifr.contentDocument:ifr.contentWindow.document;
		doc.open();
		var st = "script";
		doc.write("<html><head><"+st+" src='"+url+"&prefix="+jsprefix+"'></"+st+"></head></html>");
		doc.close();
	}
	else
	{
		document.getElementById('iframeholder').appendChild(ifr);
		ifr.src = url;
	}

	return ifr;
	
}
function popupWin(w, h, url, title, option) 
{
	if (w > window.screen.availWidth)
		w = window.screen.availWidth - 20;

	if (h > window.screen.availHeight)
		h = window.screen.availHeight - 20;

	if (option == null)
		option = "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1";

	var params = 'width=' + w + ', height=' + h;
	if (option != '')
		params += ',' + option;

	var win = window.open(url, title, params);
	win.focus();
}


/***********************************
*     asserts
***********************************/

function assert(bool, errmsg)
{
	if (bool)
		alert(errmsg);
}

/***********************************/
function mouseOverCtrl(el)
{
	if (el && el.id)
		gMouseOverEl = el.id;
}
function mouseOutCtrl(el)
{
	gMouseOverEl = '';
}
function getMouseOverCtrl(){return gMouseOverEl;}

/***********************************
*     Popup functions
***********************************/
var overPopup = false;
var calendar = new Object();
var locator = new Object();
var progress = new Object();
var gMailto = new Object();
var countryselect = new Object();
gMailto.contents = null; // created on demand
var infopopup = new Object(); 

var ParentControl;
function createCalendar()
{
	//calendar.contents = initCalendar("departDate", "arrivalDate", "en");
	calendar.contents = initCalendar(ParentControl+"txtStartDate", ParentControl+"txtEndDate", "en");
}

function popup(me, c, halign, valign, popFrame, e)
{
	//p=popup, c=calledby
	//halign: null|0-> p.left = c.left , 1-> p.left = c.right, 2->p.right = c.left, 3->p.right =c.right, 4-> p.left = c.middle, 
	//valign: null|0-> p.top = c.top, 1-> p.top = c.bottom, 2-> p.bottom = c.top, 3-> p.bottom = c.bottom, 4-> p.top = c.bottom

	var bla = document.getElementById("dapopup");
	
	//I think not doing this might be causing the mixup
	if(bla.firstChild)
		bla.removeChild(bla.firstChild);

		if(me.tagName=='INPUT')
			me.select();
		bla.appendChild(calendar.contents);
		currentDateField = me;
		displayDates();	
		
	bla.halign = halign?halign:0;
	bla.valign = valign?valign:0;
	bla.fixed = (c=="locator"?true:false);
	bla.popFrame = popFrame;
	bla.calledby = me;	
	if (bla.className.indexOf(c) == -1)
	{
		bla.className = "popup "+c;
	}
	positionpopup(bla, e);
	setPopupCover();
	
}

/*****************************
*  Hover popups
*****************************/

function doHoverPopup()
{
	// !!! remove
	assert( (gHoverPopup.timeout == null), "doHoverPopup err1" );
	assert( (gHoverPopup.status != 0), "doHoverPopup err2" );
	assert( (gHoverPopup.el == null), "doHoverPopup err4" );

	gHoverPopup.timeout = null;
	gHoverPopup.status = 1;

	var el = gHoverPopup.el;
	if(el.attributes['dopopvar'])
		infopopup.contents.innerHTML = eval(el.attributes['dopopvar'].value);
	else if(el.dopopfunc)
		infopopup.contents.innerHTML = el.dopopfunc(el.dopopargs);
	else
		return;
	
	if(el.attributes['dopopwidth'])
		infopopup.contents.style.width = el.attributes['dopopwidth'].value;
	else
		infopopup.contents.style.width = "auto";

	var popFrame = '';
	if (el.attributes['dopopframe'])
		popFrame = el.attributes['dopopframe'].value;

	var hpos = 1;
	if (el.attributes['dopophpos'])
		hpos = el.attributes['dopophpos'].value;

	popup(gHoverPopup.el,"infopopup",hpos,1, popFrame);
}
function cancelHoverPopup()
{
	if (gHoverPopup.status == 1)
	{
		// !!! remove
		assert( (gHoverPopup.el == null), "cancelHoverPopup err2" );

		popdown(true);

		gHoverPopup.status = 0;
		gHoverPopup.type = null;
		gHoverPopup.el = null;
		gHoverPopup.timeout = null;
	}
}
function cancelHoverTimeout()
{
	// cancel any pending timeout
	if (gHoverPopup.timeout)
	{
		window.clearTimeout(gHoverPopup.timeout);
		gHoverPopup.timeout = null;
	}
}
function dopopover(el)
{
	cancelHoverTimeout();
	cancelHoverPopup();
	gHoverPopup.el = el;	
	gHoverPopup.timeout = window.setTimeout(doHoverPopup, 500);
}
function dopopout()
{
	cancelHoverTimeout();
	if (gHoverPopup.status == 1)
		gHoverPopup.timeout = window.setTimeout(cancelHoverPopup, 600);
}
function mouseOverPopupLayer(ev)
{
	if (checkMouseEnter(this, ev) == false)
		return;

	// !!! remove
	assert( (gHoverPopup.status != 1), "mouseOverPopupLayer err1" );
	assert( (gHoverPopup.timeout == null), "mouseOverPopupLayer err2" );

	cancelHoverTimeout();
}
function mouseOutPopupLayer(ev)
{
	if (checkMouseLeave(this, ev) == false)
		return;

	cancelHoverPopup();
}


function popdown(force)
{
	if(force || !overPopup)
	{
		var bla = document.getElementById("dapopup");	
		bla.className = "popup";
		bla.style.height = "";
		if(bla.firstChild)
			bla.removeChild(bla.firstChild);
		bla.calledby = null;
		currentLocator = null;
		currentDateField = null;
		currentProgress = null;

		var cov = document.getElementById("dapopupcover");	
		cov.style.visibility = "hidden";
		cov.style.display = "none";
		
		document.body.style.cursor = "default";
	}
}
function align(t,p,whc,whp)
{
	// see comment in popup()
	if(t)
	{
		if(t == 1)
			return p+whc;
		if(t == 2)
			return p-whp;
		if(t == 3)
			return p+whc-whp;
		if (t == 4)
			return Math.round(p+whc/2);
	}
	return p;
}

function positionpopup(p, e)
{
	var bla = p?p:document.getElementById("dapopup");
	bla.style.visibility = "hidden";
	bla.style.position = "absolute";	
	bla.style.display = "block";
	if(bla.calledby)
	{
		var cx = findPosX(bla.calledby);
		var cy = findPosY(bla.calledby);
        if (bla.calledby.id.indexOf("LocationDateControl") > -1)
        {
            var x = align(bla.halign,cx,bla.calledby.offsetWidth, bla.offsetWidth) - 23;
            var y;
            var posY = 0;

            try
            {
                if (x > 500)
                    x=x-70;
            }
            catch(ex)
            {
            }   
            
            try
            {   
                if (!e) var e = window.event;
                
                if (e.pageY)
	            {
		            posY = e.pageY;
        		    
		            try
		            {
		                if (document.body.scrollTop > 0 && posY > document.body.scrollTop)
		                    posY = posY - document.body.scrollTop;
		            }
		            catch(ex)
		            {
		            }
	            }
	            else if (e.clientY)
		            posY = e.clientY + document.body.scrollTop;
        	    
            }
            catch(ex)
            {
                posY = 0;
            }   

	        if (posY > 470)
	            y = cy - 256;
            else if ((posY - 10) < cy)
	            y = cy - 256;
	        else
                y = cy-122;
        }
        else
        {
            var x = align(bla.halign,cx,bla.calledby.offsetWidth, bla.offsetWidth);
            var y = align(bla.valign,cy,bla.calledby.offsetHeight,bla.offsetHeight);
        }

		if(!bla.fixed)
		{
			if (p.popFrame && p.popFrame != '' && document.getElementById(p.popFrame))
				var r = elementRect(document.getElementById(p.popFrame));
			else
				var r = clientRect();

			var c = contained({'l':x,'t':y,'r':x+bla.offsetWidth,'b':y+bla.offsetHeight},r);
			
			if(c.axis == 'y') //x okay
			{
				//flip or nudge
				if(bla.halign == 0 || bla.halign == 3)//flip up/down
				{			
					//y = align(c.diff>0?1:2,cy,bla.calledby.offsetHeight, bla.offsetHeight);
                    if (bla.calledby.id.indexOf("LocationDateControl") > -1)
                    {
                        y = align(c.diff>0?1:2,cy,bla.calledby.offsetHeight, bla.offsetHeight);
                        
                        var y;
                        var posY = 0;
                
                        try
                        {   
                            if (!e) var e = window.event;
                            
                            if (e.pageY)
	                        {
		                        posY = e.pageY;
                    		    
		                        try
		                        {
		                            if (document.body.scrollTop > 0 && posY > document.body.scrollTop)
		                                posY = posY - document.body.scrollTop;
		                        }
		                        catch(ex)
		                        {
		                        }
	                        }
	                        else if (e.clientY)
		                        posY = e.clientY + document.body.scrollTop;
                    	    
                        }
                        catch(ex)
                        {
                            posY = 0;
                        }   

	                    if (posY > 450)
	                        y = cy - 256;
	                    else
	                        y = cy - 141;

                    }
                    else
                        y = align(c.diff>0?1:2,cy,bla.calledby.offsetHeight, bla.offsetHeight);
				}
				else y += c.diff			
			}
			else if(c.axis == 'x') //y okay
			{
				//flip or nudge
				if(bla.valign == 0 || bla.valign == 3)//flip to side
					x = align(c.diff>0?1:2,cx,bla.calledby.offsetWidth, bla.offsetWidth);
				else x += c.diff;
			}	
		}		
		bla.style.left = x + "px";
		bla.style.top = y + "px";
	}

	bla.style.visibility = "visible";
}
function horzPosPopup()
{
	var bla = document.getElementById("dapopup");
	var cx = findPosX(bla.calledby);
	var x = align(bla.halign,cx,bla.calledby.offsetWidth, bla.offsetWidth);

		if(!bla.fixed)
		{
			var r = clientRect();
			var y = 0;
			var c = contained({'l':x,'t':y,'r':x+bla.offsetWidth,'b':y+bla.offsetHeight},r);
			
			if(c.axis == 'x') 
			{
				//flip or nudge
				if(bla.valign == 0 || bla.valign == 3)//flip to side
					x = align(c.diff>0?1:2,cx,bla.calledby.offsetWidth, bla.offsetWidth);
				else x += c.diff;
			}	
		}		
		bla.style.left = x + "px";
}
function setPopupCover()
{
	if(navigator.appName != "Microsoft Internet Explorer")
		return;

	var bla = document.getElementById("dapopup");
	var cov = document.getElementById("dapopupcover");
	cov.style.display = "block";
	cov.style.left = bla.style.left;
	cov.style.top = bla.style.top;
	cov.style.width = bla.offsetWidth;
	cov.style.height = bla.offsetHeight;
	cov.style.visibility = "visible";
}

function overpopup()
{
	overPopup = true;
}
function leavepopup()
{
	overPopup = false;
}
function clickpopup()
{
	var bla = document.getElementById("dapopup");
}

function changeDisplayStyle(id, display)
{
	var bla = document.getElementById(id);
	if (bla)
	{
		bla.style.display = display;
	}
}

// http://www.quirksmode.org/js/findpos.html.
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function elementRect(el)
{
	var l = findPosX(el);
	var t = findPosY(el);
	
	return {'l':l,'t':t,'r':l+el.offsetWidth,'b':t+el.offsetHeight};
}
function clientRect()
{
	var d = getInnerDimension();

	return {'l':d.l,'t':d.t,'r':d.l+d.w,'b':d.t+d.h};
}
//1: x and y contained, 2,3:x contained, 4,5:y contained, 0:x and y outside
function contained(p,r)
{
	var axis = '';
	var diff = 0;
	if(p.l>=r.l && p.r<=r.r)
	{
		if(p.t<r.t || p.b>r.b)
		{
			axis='y';
			if(p.t<r.t) diff=r.t-p.t;
			else diff=r.b-p.b;			
		}
	}
	else if(p.t>=r.t && p.b<=r.b)
	{
		axis = 'x';
		if(p.l<r.l) diff=r.l-p.l;
		else diff=r.r-p.r;
	}
	return {'axis':axis,'diff':diff};
}

function getInnerDimension()
{
	var d = {'w':0, 'h':0, 'l':0, 't':0};
	if (window.innerWidth)
	{
		d.w = window.innerWidth;
		d.h = window.innerHeight;
		d.l = window.scrollX;
		d.t = window.scrollY;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		d.w = document.documentElement.clientWidth;
		d.h = document.documentElement.clientHeight;
		d.l = document.documentElement.scrollLeft;
		d.t = document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		d.w = document.body.clientWidth;
		d.h = document.body.clientHeight;
		d.l = document.body.scrollLeft;
		d.t = document.body.scrollTop;
	}
	return d;
}

// http://www.quirksmode.org/js/events_order.html
function stopBubble(ev) {
	ev = (ev) ? ev : (window.event) ? event : null;
	if (ev)
	{
		ev.cancelBubble = true;
		if (ev.stopPropagation) ev.stopPropagation();
	}
}
// http://www.quirksmode.org/js/events_properties.html
function getEvTarget(ee)
{
	var targ;
	var e = ee;
	if (!e) e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

// http://www.faqts.com/knowledge_base/view.phtml/aid/1606
function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}
function checkMouseLeave (element, evt) {
	evt = (evt) ? evt : (window.event) ? event : null;
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}
function checkMouseEnter (element, evt) {
	evt = (evt) ? evt : (window.event) ? event : null;
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}



function cleanTable(t, rowsleave)
{	
	while(t != null && t.rows.length > rowsleave) 
	{
		
		t.deleteRow(t.rows.length - 1 - rowsleave);	
	}
}
function leftpadInt(n,len,pad)
{
	if(!pad || pad.length==0)
		pad=String.fromCharCode(160);
	var retval = n.toString();
	while(retval.length < len)
		retval = pad+retval;
	return retval;
}
function formatTimePassed(n, parenthesisWrap)
{
	//difference in minutes
	var t = new Date();
	var r = '';
	if(!n) r+=rm.unchecked;
	else
	{
		var d = ((t - n) / 60000)+t.getTimezoneOffset(); //60*1000	
		if(d > rm.maxageshown) r+=rm.unchecked;
		else if(d < rm.maxagebeforeupdate) r+=rm.current;
		else if(d > 1440) r+=Math.floor(d/1440)+rm.dayAccronym;
		else if(d > 60) r+=+Math.floor(d/60)+rm.hourAccronym;
		else r+=Math.round(d)+rm.minuteAccronym;
	}	
	if (parenthesisWrap)
		return '(' + r + ')';
	else
		return r;
}

function formatTimespan(timespan)
{
	var days = Math.floor(timespan/(60*24));
	timespan -= days * 60*24;
	return (days>0) ?
		days + rm.dayAccronym+" "+Math.floor(timespan / 60) + rm.hourAccronym+" " + ((timespan % 60)<10?'0':'') + Math.round((timespan % 60)) +rm.minuteAccronym
	:
		Math.floor(timespan / 60) + rm.hourAccronym+" " + ((timespan % 60)<10?'0':'') + Math.round((timespan % 60))+rm.minuteAccronym; 
}
function formatTime(t, padhour)
{		
	var hourD = Math.floor(t/60);
	if (padhour && hourD < 10) {
		hourD = '0' + hourD;
	}
	var minD =  Math.round(t - hourD*60);	
	if (minD < 10) {
		minD = '0' + minD;
	}
	return hourD + ':' + minD;
}
function formatCurrencyAmount(num, points)
{
	if(num < 1)
		points = 2;
	return formatNumber(num*global.rates[global.exchangeCode].r,points);
}
function formatCurrency(num, points)
{
// Pretty currency codes, do l8er
//	if (global.rates[global.exchangeCode].p != '' && navigator.userAgent.toLowerCase().indexOf("msie")==-1)
//		return global.rates[global.exchangeCode].p.replace('*',formatNumber(num*global.rates[global.exchangeCode].r,points));
	return  formatCurrencyAmount(num, points)+' '+ global.exchangeCode;
}
function formatNumber(num, points)
{
	var runner = Math.floor(num);
	var formatted = "";
	if (rm.decimalseparator != null && points > 0)
	{		
		formatted = rm.decimalseparator + Math.round((num-runner)*Math.pow(10,points));	
	}
	else
	{
		runner = Math.round(num);
	}

	if(rm.thousandseparator != null)
	{   
		var local;
		while((runner) >= 1000)
		{
			local = Math.round(runner % 1000);
			formatted = rm.thousandseparator + (local < 100?'0':'') + (local < 10?'0':'') + local + formatted;	
			runner /= 1000;			
		}	
		runner %= 1000;
	}
	formatted = Math.floor(runner.toString()) + formatted;
	return formatted;
}

function makeTD(tr, cn, ch)
{
	var d = document.createElement("TD");
	if (tr)
		tr.appendChild(d);
	d.className = cn;
	if(ch)
	{
		if (ch == nbsp)d.appendChild(document.createTextNode(nbsp));
		else d.appendChild(ch);
	}
	return d;
}
function removeElement(el) 
{
	el.parentNode.removeChild(el);
}
function setCookie(k,v,e,d)
{
	document.cookie = k + "=" + escape(v) + "; " +(e?"expires=" + e.toGMTString()+"; ":'') + "path=/;" + (d?" domain="+d+";":"");
}
function getCookie(k)
{
	var aCookie = document.cookie.split(";");
	for (var i=0; i < aCookie.length; i++)
	{
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (k == aCrumb[0].replace(/^\s+/,'').replace(/\s+$/,'')) 
			return unescape(aCrumb[1]);
	}
	// a cookie with the requested name does not exist
	return null;
}
function killCookie(k,d)
{
  document.cookie = k + "=" + escape(null) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT; "+ "path=/;" + (d?" domain="+d+";":"");
}
function FlipCurrency(selected)
{	
	if (selected=='')
	{
		fullCurrencyList();
		return;
	}
	if (global.rates && selected && selected!='')
	{
		global.exchangeCode = selected;
	}		
}
function FlipLanguage(selected)
{
	if (window.location.pathname.toLowerCase().indexOf(selected) != 0)
	{
		setCookie("language", selected);
		window.location.href = "http://"+window.location.host+"/"+selected+ window.location.pathname.replace(/^\/\w\w\//,'/')+window.location.search+window.location.hash;
	}
}

function ImageLoadFailed(ev) {
	this.style.display = "None";
}

function limitText(text, maxlength)
{
	if (text.length <= maxlength)
		return text;
	return text.substr(0, maxlength-3) + "...";
}
function extract(list)
{
	var obj = new Object();
	for(var i = 0; i < list.length;i++)
	{
		elem = list[i].split("=");
		if(elem.length == 2 || elem.length == 3)
			obj[elem[0]] = unescape(elem[1]);		
	}	
	return obj;
}
/***********************************
*     Validation functions
***********************************/

function isValidEmail(addr) {
   return (addr.indexOf(".") > 2) && (addr.indexOf("@") > 0);
}

function stringtodate(s)
{
	var firstslash = s.indexOf("/");
	var lastslash = s.lastIndexOf("/");
	
	return new Date(s.substring(lastslash+1), s.substring(firstslash+1, lastslash)-1, s.substring(0, firstslash));
}

function datetostring(d)
{
	return rm.weekdays[d.getDay()]+' '+d.getDate()+' '+rm.monthshort[d.getMonth()]+' '+d.getFullYear()
}
