function getThisWindow() {
	var wid = getThisWindowId();
	return window.top.$A(window.top.Windows.windows).detect(function (e){ return e.getId() == wid; });
}

function truncElementText(s, container, maxWidth, maxHeight) {
	var t = false;
	while ((container.offsetWidth > maxWidth || container.offsetHeight > maxHeight) && (!isIE || s.offsetWidth > maxWidth || s.offsetHeight > maxHeight) && s.innerHTML.length > 0) {
		s.innerHTML = s.innerHTML.substr(0, s.innerHTML.length-1);
		t = true;
	}
	if (t) s.innerHTML += "...";
}

function calcIncentive(payment, incentive, months) {
	payment = parseFloat(payment);
	incentive = parseFloat(incentive);
	months = parseInt(months);
	if (isNaN(payment) || isNaN(incentive) || isNaN(months))
		throw "error";
	try {
		return payment - (incentive / (months - 1));
	} catch(e) {
		return payment;
	}
}

// disables other checkboxes in the same group
// sample: <input type="checkbox" class="excludeenhance" exclude="enhance" onclick="chkDisableOthers(this)" />
function chkDisableOthers(e) {
	var elems = getElementsByClassName(document, "exclude" + e.getAttribute('exclude'));
	for (var i = 0; i < elems.length; i++)
		if (elems[i] != e)
			elems[i].checked = false;
}

// takes all disabled anchors, and removes href from them
function fixDisabledAnchors() {
	var e = document.getElementsByTagName("a");
	for (var i = 0; i < e.length; i++) {
		if (e[i].disabled) {
			e[i].disabled = false;
			e[i].removeAttribute('href');
		}			
	}
}

// parses querystring
function getQueryString(qs) {
	qs = qs.substring(1); // remove "?"
	var r = {};
	var p = qs.split("&");
	for (var i=0; i < p.length; i++) {
		var kv = p[i].split("=");
		r[kv[0]] = kv[1];
	}
	return r;
}

// Returns true if the exprssions to evaluate match a valid phone number.
function isValidPhone(areaCode,prefix,number,nullable){
	if(nullable && areaCode.length==0 && prefix.length==0 && number.length==0)
		return true;
	else if(areaCode.trim().length<3 || prefix.trim().length<3 || number.trim().length<4)
		return false;
	else if(!isInt(areaCode) || !isInt(prefix) || !isInt(number))
		return false;
	else
		return true;
}

// Returns true if the expression to evaluate is an integer number
function isInt(e){
	e = e.toString().replace(/^0*([^0]+)/, "$1");
	return !isNaN(parseInt(e)) && parseInt(e)==e;
}

// comparar dos options de select, para usar con sort()
function sortOption(a,b) { 
	var la=a.text.toLowerCase(); 
	var lb=b.text.toLowerCase();
	return (la == lb ? 0 : la < lb ? -1 : 1);
}

// gets key code for a keypress event
function getKeyCode(e) {
	return window.event ? window.event.keyCode : e.which ? e.which : e.charCode;
}

// on enter, click button 'e'
function enterPress(evento, e) {
	if (getKeyCode(evento) == 13) {
		document.getElementById(e).click();
		return false;
	}
	return true;
}

// gets element pos, cross-browser
function getXYElem(e) {
	var x = 0, y = 0;
	if (!isNaN(this.x))
		return {x:this.x, y:this.y};
	var p=e;
	while (p && !isNaN(p.offsetLeft) && !isNaN(p.offsetTop)) {
		x += p.offsetLeft;
		y += p.offsetTop;
		p = p.offsetParent;
	}
	return {x:x, y:y};		
}

// returns 0 (false) if key pressed was a digit
// returns 3 if key pressed was not a digit
// returns 2 if ctrl, alt, or meta was pressed
// returns 1 if key pressed was not printable (i.e. backspace)
function keyPressInt(e) {
		if (e.ctrlKey || e.altKey || e.metaKey)
			return 2;
		var kc = getKeyCode(e);
		if (kc > 126 || kc < 32)
			return 1;			
		var key = String.fromCharCode(kc);
		if (!isInt(key))
			return 3;
		return 0;
}

// returns 0 (false) if key pressed was a digit
// returns 3 if key pressed was not a digit
// returns 2 if ctrl, alt, or meta was pressed
// returns 1 if key pressed was not printable (i.e. backspace)
function keyPressFloat(e) {
		if (e.ctrlKey || e.altKey || e.metaKey)
			return 2;
		var kc = getKeyCode(e);
		if (kc > 126 || kc < 32)
			return 1;			
		var key = String.fromCharCode(kc);
		if (!isInt(key) && key != ".")
			return 3;
		return 0;
}

function getElementsByClassName(node, classname)
{
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

// .nextSibling is broken in Gecko
function getNextSibling(startBrother){
	endBrother=startBrother.nextSibling;
	while(endBrother != null && endBrother.nodeType!=1){
		endBrother = endBrother.nextSibling;
	}
	return endBrother;
}

function getThisWindowId() {
	var dd = document.createElement('div');
	dd.setAttribute('style', 'display:none');
	dd.id = 'thisRandom' + Math.random();
	var body = document.getElementsByTagName('body')[0];
	body.appendChild(dd);
	var r;
	for (var i=0; ; i++) {
		var f = window.top.frames[i];
		if (!f)
			break;
		if (f.document.getElementById(dd.id)) {
			r = f.name.replace(/_content$/, "");
			break;
		}				
	}
	body.removeChild(dd);
	return r;
}

function getFrameForWindow(id) {
	for (var i=0; ; i++) {
		var f = window.top.frames[i];
		if (!f)
			return null;
		try {
			if (f.name == id + "_content")
				return f;
		} catch(e) {}
	}
}

function openPleaseWait(titles, width, height) {
	var w = new Window("pleaseWait" + Math.random(), {
		className: "alphacube", 
		minimizable:false, 
		maximizable:false, 
		resizable: false, 
		title: titles!=null?titles:'LeaseTrader.com', 
		//title: 'LeaseTrader.com',
		draggable:false,
		closable: false,
		//showEffect: Element.show, 
		//hideEffect: Element.hide,
		width: width!=null?width:200,
		height: height!=null?height:50
	});
	w.getContent().innerHTML = "<div align='center' class='txt10Blue'>Please wait...<br><div class='space5'></div><img src='/img/ajax-loader.gif'><br></div>";
	w.setDestroyOnClose();
	w.showCenter(true);
	return w;
}

// opens a new static modal prototype window
// requires prototype.js
function openStaticModalWindow(content, title, width, height) {
	var jsClose = 'Windows.close("{id}");return false;';
	var closeAll = window.opera || /Konqueror|Safari|KHTML/.test(navigator.userAgent);
	if (closeAll)
		jsClose = 'Windows.closeAll();return false;'; // opera has a bug with innerHTML (http://www.uberconcept.com/OperaBroken.htm)
	var html =
		"<div class='txt10Red'>{0}</div><br><table width='99%' cellpadding='0' cellspacing='0' border='0'><tr><td align='right'><input type=image class='cursor' id='btnOKPopup' onkeypress='{close}' onclick='{close}' src='/img/btn_ok.gif'><br></td></tr></table>"
		.replace("{0}", content)
		.replace(/\{close\}/g, jsClose);
		
	var w = openWindow({
		modal: true,
		title: title,
		content: html,
		width: width!=null?width:200,
		height: height!=null?height:70
	});
	if (!closeAll)
		w.getContent().innerHTML = w.getContent().innerHTML.replace(/\{id\}/g, w.getId());
	document.getElementById("btnOKPopup").focus();
	return w;
}

function goToAnchor(w, name) {
	var a;
	try {
		a = $A(w.document.getElementsByTagName('a')).find(function(e) {return e.name == name; });
	} catch(e) {}
	if (!a) {
		setTimeout(function() {goToAnchor(w, name)}, 50);
	}	else
		w.scrollTo(0, getXYElem(a).y);
}

/*
params:
- title
- width
- height
- modal
- url
- content
- scrolling
- parentControl: reference to parent control, for help
*/
var arrWin = new Array();
function openWindow(params) {
    
	var ws = WindowUtilities.getWindowScroll();
	ws.width -= 10;
	ws.height -= 35;
	var wParams = {
		className: "alphacube",
		minimizable: false,
		maximizable: false,
		resizable: false,
		closable: (params.closable != null ? params.closable : true),
		draggable: !params.modal,
		width: Math.min(params.width, ws.width),
		height: Math.min(params.height, ws.height),
		title: params.title,
		scrolling: (params.height > ws.height || params.width > ws.width ? true : params.scrolling),
		showEffect: Element.show,
		hideEffect: Element.hide
	};
	if (params.url) {
		var h = params.url.split('#')[0];
		var ha = params.url.split('#')[1];
		if (!ha || /safari|khtml/i.test(navigator.userAgent))
			wParams.url = params.url;
		else {
			params.url = h;
			var w = openWindow(params);
			var f;
			var gogo = function () {
				f = getFrameForWindow(w.getId());
				if (!f)
					setTimeout(gogo,50);
				else
					_(f.document).ready(function() {
						goToAnchor(f, ha);
					});
			};
			gogo();
			return w;
		}
	}
	if(arrWin.length > 0)
	{
	    for(var nIndex = 0; nIndex < arrWin.length; nIndex++)
	    {
	         Windows.close(arrWin[nIndex].getId());
	    }
	}
	var winID = "win" + Math.random();
	var w = new Window(winID, wParams);
	arrWin[arrWin.length] = w;
	if (params.content)
		w.getContent().innerHTML = params.content;
	w.setDestroyOnClose();
	if (!params.parentControl) {
		w.showCenter(params.modal);
	}
	else {
		if (window.currentHelp)
			Windows.close(window.currentHelp);
		var r = getXYElem(params.parentControl);
		var x = r.x + params.parentControl.offsetWidth;
		var y = r.y - ws.top;
		var wi = ws.width - params.width - 20;
		if (x > wi)
			x = wi;
		w.showCenter(params.modal, y, x);
		w.parentControl = params.parentControl;
		Windows.addObserver({onClose: 
			function(event, win) { 
				if (win == w) {
					window.currentHelp = null;
					w.parentControl.onclick = function() {openWindow(params)}; 
				}
			}
		});
		params.parentControl.onclick = function() { window.currentHelp = null; Windows.close(null, w.getId()); };
		window.currentHelp = w.getId();
	}			
	return w;	
}

/*
Author: Robert Hashemian
http://www.hashemian.com/

You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
********************************************************
Usage Sample:

<script language="JavaScript" src="http://www.hashemian.com/js/NumberFormat.js"></script>
<script language="JavaScript">
document.write(FormatNumberBy3("1234512345.12345", ".", ","));
</script>
*/

// function to format a number with separators. returns formatted number.
// num - the number to be formatted
// decpoint - the decimal point character. if skipped, "." is used
// sep - the separator character. if skipped, "," is used
function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}


/*
Tooltip library
Author: Mauricio Scheffer

usage:

	<div class="block2" style="display: none" id='tooltipForImagenCualquiera'>
		SUVs <img src='../img/banner_post.gif'>
	</div>
	<img src="../img/c_suvs.jpg" id="imagen" class="tooltip tooltipForImagenCualquiera otraclase">
	
reserved class names:
- tooltip
- tooltipFor*
*/ 
var ProtoToolTip = {
	tooltips: [],
	inOT: false,
		
	init: function() {
		var tt = getElementsByClassName(document, 'tooltip');
		for (var i=0; i < tt.length; i++) {
			_('#'+tt[i].id).hover(ProtoToolTip.ot, ProtoToolTip.ct);
			tt[i].removeAttribute('alt');
			ProtoToolTip.tooltips.push(tt[i]);
		}
	},
	
	closeAllTooltips: function() {
		for (var i=0; i < ProtoToolTip.tooltips.length; i++)
			try {
				ProtoToolTip.ct(null, ProtoToolTip.tooltips[i].id);
			} catch(e) {
			}
	},

	closeTooltip: function(e) {
		if (window.timerCloseTooltip)
			clearTimeout(window.timerCloseTooltip);
		e.style.display = 'none';
	},
	
	// event handler for mouseover
	ot: function(e) {
		while (ProtoToolTip.inOT) {}
		ProtoToolTip.inOT = true;
		ProtoToolTip.closeAllTooltips();
		var ttID = this.className.match(/tooltipFor[^ ]*/);
		var r = getXYElem(this);
		window.timerOpenTooltip = window.setTimeout(
			"ProtoToolTip.openTooltip('{id}', '{tt}', {x}, {y})"
			.replace("{id}", this.id)
			.replace("{tt}", ttID)
			.replace("{x}", r.x)
			.replace("{y}", r.y-16)
		, 10);
		ProtoToolTip.inOT = false;
	},
	
	// event handler for mouseout
	ct: function(e, id) {
		var elem = this;
		if (id)
			elem = document.getElementById(id);
		if (window.timerOpenTooltip)
			clearTimeout(window.timerOpenTooltip);
		var ttID = elem.className.match(/tooltipFor[^ ]*/);					
		var t = document.getElementById(ttID);
		ProtoToolTip.closeTooltip(t);
	},
		
	// gets cursor pos
	getXY: function(e) {
		var r = {};
		if ( document.captureEvents ) {
			r.x = e.pageX;
			r.y = e.pageY;
		} else if ( window.event.clientX ) {
			r.x = window.event.clientX+document.documentElement.scrollLeft;
			r.y = window.event.clientY+document.documentElement.scrollTop;
		}
		return r;
	},
		
	openTooltip: function(elemID, ttID, x, y) {
		//var e = document.getElementById(elemID);
		var t = document.getElementById(ttID);
		if (t.style.display == 'inline')
			return;
		t.style.left = x;
		t.style.top = y;
		t.style.display = 'inline';		
		t.style.position = 'absolute';
		t.style.zIndex = 99;
		window.timerCloseTooltip = window.setTimeout(
			"ProtoToolTip.ct({}, '{id}')"
			.replace("{id}", elemID)
		,6000);
	}		
};


// requires getElementsByClassName, jqueryu
var rollovers = {};
function rollOver_btnOver() {
	if (!rollovers[this.id]) {
		rollovers[this.id] = {};
		rollovers[this.id].normal = new Image();
		rollovers[this.id].normal.src = this.src;
		rollovers[this.id].over = new Image();
		rollovers[this.id].over.src = this.src.replace(/(\..{3,4})$/, "_over$1");
	}
	//this.src = this.src.replace(/(\..{3,4})$/, "_over$1");
	this.src = rollovers[this.id].over.src;
}
function rollOver_btnNormal() {
	//this.src = this.src.replace(/_over/g, "");
	this.src = rollovers[this.id].normal.src;
}
function rollOver_init() {
	var e = getElementsByClassName(document, "rollover");
	for (var i=0; i < e.length; i++) {
		var img = e[i].getElementsByTagName("img")[0];
		_('#'+img.id).hover(rollOver_btnOver, rollOver_btnNormal);
	}
	_('input.rollover2').hover(rollOver_btnOver, rollOver_btnNormal);
}
