// some general, shared functions

function reloadDiv(div, url, sync, parms, evScript, moreOptions, method) {
	var async = !sync;
	if (!parms) {
		parms = '';
	}
	if (!evScript) evScript = false;
	if (method === undefined) method = 'post';
	
	var options = {asynchronous:async, evalScripts:evScript, parameters: parms, method:method};
	
	if (typeof moreOptions === 'object') {
		for (key in moreOptions) {
			options[key] = moreOptions[key];
		}
	}
	
	new Ajax.Updater(div, url, options);
}

function logoutConfirm( ) {
	if (confirm('Are you sure you want to log out?')) {
		document.location='/?logout=Y';
	}
}

function openCenteredWindow(theURL,winName,width,height,scrollbars,resizable) { //de
	if (!resizable) resizable = '0';
	if (!scrollbars) scrollbars = '0';
	var win = window.open(theURL,winName,'toolbar=0,scrollbars=' + scrollbars + ',location=0,statusbar=0,menubar=0,resizable=' + resizable + ',width='+width+',height='+height+',left='+((screen.width - width) / 2)+',top='+((screen.height - height) / 2));
	win.focus();
}

function openWindow(theURL,winName,features) { // centering added retroactively
	//de	Retroactive "adapter" START
	wid = hei = false;
	if (features.indexOf("width=")) {
		wid = features.substr(features.indexOf("width="));
		if (wid.indexOf(',')>0) wid = wid.substr(0, wid.indexOf(','));
		wid = wid.substr(wid.indexOf('=')+1);
	}
	if (features.indexOf("height=")) {
		hei = features.substr(features.indexOf("height="));
		if (hei.indexOf(',')>0) hei = hei.substr(0, hei.indexOf(','));
		hei = hei.substr(hei.indexOf('=')+1);
	}
	if (wid && hei) {
		openCenteredWindow(theURL, winName, wid, hei);
		exit;
	}
	//de	Retroactive "adapter" END

	var win = window.open(theURL,winName,features);
	win.focus();
}
	
//rc 07/13/06 Added cookie support (from w3schools.com)
function setCookie( cName, value, expireDays ) {
	if (expireDays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expireDays);
	}
	document.cookie = cName + "=" + escape(value) + ((expireDays === null) ? "" : ";expires=" + exdate);
}
	
//rc 11/21/06 see note below
function isCookie( cName ) {
	return document.cookie.length > 0 && document.cookie.indexOf(cName + "=") != -1;
}
	
//rc 11/21/06 NOTE: This code can incorrectly return values. 'test' can return value for 'sometest'
//		A better method can be to use .split(';') to break apart cookie string & then find full match
//		See http://www.quirksmode.org/js/cookies.html for possible solution
function getCookie( cName )
{
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(cName + "=");
		if (c_start != -1) { 
			c_start = c_start + cName.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			
			//rc W3 does not include the use of replace(). It's required to convert "+" to spaces.
			return unescape(document.cookie.substring(c_start, c_end).replace(/\+/g, ' '));
		} 
	}
	return null;
}
	
function clearCookie( cName ) {
	setCookie(cName, '', null);
}

function showHide( divName ) {
	var div = document.getElementById(divName);
	var divA = document.getElementById(divName + 'a');
	if (div.style.display=='none') {
			div.style.display='block';
		if (document.all)
			divA.innerText = 'Hide';
		else
			divA.textContent = 'Hide';
		}
	else {
		div.style.display='none';
		if (document.all)
			divA.innerText = 'Show';
		else
			divA.textContent = 'Show';
	}
}

function showDiv( divName ) {
	$(divName).style.display = 'block';
}

function hideDiv( divName ) {
	$(divName).style.display = 'none';
}

function showSpan( spanName ) {
	$(spanName).style.display = 'inline';
}

function hideSpan( spanName ) {
	$(spanName).style.display = 'none';
}

function getDiv( divName ) {
	var div = $(divName);
	if (div) {
		if (document.all)
			return div.innerText;
		else
			return div.textContent;
	}
	return '';
}

function fillDiv( divName, text ) {
	var div = $(divName);
	if (div) {
		if (document.all)
			div.innerText = text;
		else
			div.textContent = text;
	}
}

function fillFromJson( json, prefix, showDiv ) {
	if (json.error !== undefined && json.error != '') {
		alert(json.error);
		return false;
	}
	for (key in json) {
		fillDiv(prefix + key, json[key]);
	}
	if (showDiv !== undefined) {
		$(showDiv).show();
	}
	return true;
}

//JAKE 06/07/07 NOTE: This function handles the row highlight in selected table rows based
//on the selection of the checkbox
function rowHighlight(checkbox)
{
	if(null != checkbox)
	{
		if(checkbox.checked)
			checkbox.parentNode.parentNode.style.backgroundColor = "#ffffcc";
		else
			checkbox.parentNode.parentNode.style.backgroundColor = "";
	}
}

//JAKE 06/07/07 NOTE: This function handles check all uncheckall funcationality for the table.
function checkAll(tableId,action){
	//if you user is selection from the header change the text and action
	var headerLink = $("check-link");
	if(null != headerLink)
	{
		if(action == "check")
		{
			headerLink.innerHTML = "Uncheck";
			headerLink.href = href="javascript:checkAll('manage-loads-table','uncheck');"
		}
		else
		{
			headerLink.innerHTML = "Check";
			headerLink.href = href="javascript:checkAll('manage-loads-table','check');"
		}
	}
  var table = $(tableId);
  var inputs = table.getElementsByTagName("input");
  var checkboxes = new Array();
	for(i=0;i<inputs.length;i++)
	{
		if(inputs[i].type == "checkbox")
		{
			if(action == "check")
				inputs[i].checked = true;
			else
				inputs[i].checked = false;
				
			//set row highlight
			rowHighlight(inputs[i])	
			
			//add to checkbox array? 
			//checkboxes[i] = inputs[i];
		}
	} 
  //alert(checkboxes.length);
}

function popoverConfirmation( headerText, messageText, url ) {
	var left;
	var top;
	if (document.documentElement && document.documentElement.scrollTop) { // support Explorer 6+
		left = document.documentElement.scrollLeft;
		top = document.documentElement.scrollTop;
	} else {
		left = document.body.scrollLeft;
		top = document.body.scrollTop;
	}
	left += 200;
	top += 75;
	var oLeft = -left - 10;
	var oTop = -top - 10;
	var width = document.body.offsetWidth;
	var height = document.body.offsetHeight;
	
	var newdiv = document.createElement('div');
	newdiv.id = 'alertBox';
	newdiv.className = 'dp_dialog';
	newdiv.style.left = left + 'px';
	newdiv.style.top = top + 'px';
	
	if (headerText == '') headerText = "What would you like to do?";
	if (messageText == '') messageText = "<span style='font-size: 16pt; font-weight: bold;'>One moment . . .<" + "/span>";
	
	newdiv.innerHTML = "<div class='dp_overlay' style='position: absolute; z-index: -1; left: " + oLeft + "px; top: " + oTop + "px; height: " + height + "px; width: " + width + "px; filter:alpha(opacity=25); opacity: 0.25; -moz-opacity:0.25; background-color: #FFFFFF; padding: 0;'>&nbsp;<" + "/div><div class='dp_dialog_header'><a href='javascript:void(0)' onclick='removeNodeById(\"alertBox\")'>X<" + "/a> &nbsp; " + headerText + "<" + "/div><div class='dp_dialog_contents' id='dp_dialog_contents'>" + messageText + "<" + "/div><" + "/div>";
	
	var oDiv = document.body; //getElementById('dp_page');
	oDiv.insertBefore(newdiv, oDiv.childNodes[0]);
	
	if (navigator.appVersion.indexOf('MSIE 6') > 0 && navigator.userAgent.indexOf('Opera') < 0) {
		new Insertion.After($('dp_dialog_contents'), '<iframe style="border: 2pt solid blue; width:' + width + 'px; height:' + height + 'px; position:absolute; left: ' + oLeft + 'px; top: ' + oTop + 'px; z-index: 10; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="javascript:false;" frameborder="5" scrolling="no"><' + '/iframe>');
	}
	
	if (url != undefined)
		reloadDiv('dp_dialog_contents', url, false, false, true);
}

function removeConfirmation( ) {
	removeNodeById("alertBox");
}

function getElementLeft( elem ) {
	return elem.getPosition().x;
}

function getElementTop( elem ) {
	return elem.getPosition().y;
}	

function overlaps( main, check, confirm ) { // "main" is the element that you want to see if "check" is overlapping
	check = $(check);
	if (confirm === undefined) { confirm = 1; }
	var mainCoor = main.getCoordinates();
	var pLeft = mainCoor.left;
	var pTop = mainCoor.top;
	var pWidth = mainCoor.width;
	var pHeight = mainCoor.height;
	
	var checkCoor = check.getCoordinates();
	var left = checkCoor.left;
	var top = checkCoor.top;
	var wid = checkCoor.width;
	var hei = checkCoor.height;
	
	var widmax = wid + left;
	var heimax = hei + top;
	
	var pWidMax = pWidth + pLeft;
	var pHeiMax = pHeight + pTop;
	
	if (confirm) {
		pTop -= 25;  // appears that getElementLeft/Top don't get exact coordinates
		pLeft -= 25;
	}
	
	if (((left > pLeft && left < pWidMax) || (widmax > pLeft && widmax < pWidMax)) && ((top > pTop && top < pHeiMax) || (heimax > pTop && heimax < pHeiMax)))
		return 1;
	return 0;
}

function showTooltip( check, tooltip, down ) {
	check = $(check);
	tooltip = $(tooltip);
	if (down === undefined) {
		down = 13
	}
	
	var checkPos = check.getPosition();
	
	tooltip.setStyles({visibility: 'visible', 'z-index': 2000, left: checkPos.x + 'px', top: (checkPos.y + down) + 'px'});
	
	if (navigator.appVersion.indexOf('MSIE 6') > 0 && navigator.userAgent.indexOf('Opera') < 0) {
		var els = document.getElementsByTagName('select');
		for (var i = 0; i < els.length; ++i) {
			if (overlaps(tooltip, els[i], 0)) {
				$(els[i]).hide();
				$(els[i]).disable();
			}
		}
	}
}

function hideTooltip( tooltip ) {
	$(tooltip).setStyle('visibility', 'hidden');
	if (navigator.appVersion.indexOf('MSIE 6') > 0 && navigator.userAgent.indexOf('Opera') < 0) {		
		if (!$('alertBox'))
		{
			var els = document.getElementsByTagName('select');
			for (var i = 0; i < els.length; ++i) {
				if (els[i].disabled === true) { // only restore what was disabled (not hidden FatLocation state selector)
					$(els[i]).show();
					$(els[i]).enable();
				}	
			}	
		}
	}
}

function removeNodeById( id, option ) {
	if (navigator.appVersion.indexOf('MSIE 6') > 0 && navigator.userAgent.indexOf('Opera') < 0) {
		var els = document.getElementsByTagName('select');
		for (var i = 0; i < els.length; ++i) {
			$(els[i]).show();
			$(els[i]).enable();
		}
	}
	var e = $(id);
	if (e)
		e.parentNode.removeChild(e);
}

function roundCents( val ) {
	val = Math.round(val * 100);
	var cents = val % 100;
	cents = cents.toString();
	switch (cents.length) {
		case 0:
			cents = '00';
			break;
		case 1:
			cents = '0' + cents;
			break;
	}
	return Math.floor(val / 100) + '.' + cents;
}

function iefixShow( ) {
	if (_iefix) {
		_iefix.style.width = _suggestions.getWidth() + 'px';
		_iefix.style.height = _suggestions.getHeight() + 'px';
		_iefix.show();
	}
}

function wholeNumberOnly( obj, fieldname, emptyIsZero ) {
	obj.value = obj.value.replace(/[,\$ ]/g, '');
	if (obj.value.search(/[^0-9\.]/) > -1) {
		obj.style.backgroundColor = '#FFC0C0';
		alert (fieldname + ' can only be a number.');
		return true;
	} else {
		if (obj.value == '' && emptyIsZero) {
			obj.value = '0';
		}
		obj.style.backgroundColor = '';
	}
	return true;
}

/**
 * Get this document's query string
 * 
 * @param array vars to exclude
 */
function getQueryString( exclude ) {
	var qs = window.location.search.substring(1);
	if (typeof exclude === 'object') {
		for (var i = 0; i < exclude.length; ++i) {
			var re1 = new RegExp('^' + exclude[i] + '=[^&]*&?', 'g');
			var re2 = new RegExp('&' + exclude[i] + '=[^&]*', 'g');
			qs = qs.replace(re1, '').replace(re2, '');
		}
	}
	return qs;
}

/**
 * Switch between area search and city search
 * 
 * @param checkbox ID of selector checkbox
 * @param which prefix of location select group
 * @param cityId optional
 */
function switchSearch( checkbox, which, cityId ) {
	if (!prototypeInstalled) {
		alert('Your browser does not support this function.');
		checkbox.checked = false;
		return;
	}
	
	$(which + '-areasearch').style.display = (checkbox.checked ? 'none' : '');
	$(which + '-citysearch').style.display = (checkbox.checked ? 'block' : 'none');
	if (checkbox.checked) {
		$(cityId ? cityId : which + 'city').focus();
	}
}

//rc #3912 this will stay false for pocket pc and others that do not support Prototype
var prototypeInstalled = false;
if (document.getElementById) {
	prototypeInstalled = true;
}

// force phone format and verify it's a complete number
function fixPhone( field, name ) {
	field.value = field.value.replace(/[^0-9]/g, ''); // remove non-numeric
	field.value = field.value.replace(/^1/, ''); // remove leading "1"
	field.value = field.value.replace( /^([0-9]{1,3})([0-9]{0,3})([0-9]{0,4}).*$/, '($1) $2-$3'); // format it
	if (field.value.search(/\([0-9][0-9][0-9]\) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/) !== 0) {
		return name + ' must be in the format\n     (999) 999-9999.\n';
	}
	
	return '';
}


// ------------------------------------------------------------------------------------

//@ http://jsfromhell.com/string/capitalize [v1.0]
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

// escape a value for url
// http://www.phpbuilder.com/board/showthread.php?t=10318476
function urlencode( str ) {
	return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

/*
CSS Browser Selector v0.3.2
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
/**
	This sets a class on the top HTML element that can be used for conditional CSS.
		.mac.ie5 .myClass { padding-top: 3px; }
		.ie7 .anotherClass { font-size: 105%; }
*/
function css_browser_selector(u) {var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&(/msie\s(\d)/.test(ua)))? ('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)? 'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)? ' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; var c = b.join(' '); h.className += ' '+c; return c;} css_browser_selector(navigator.userAgent);
