var browser;
var windowIsScrolling = false;
var previousScrollXY;

var ismacie = false;

//--------------------------------------------------------------------------------------------------
//  Functions
//--------------------------------------------------------------------------------------------------

function browserIs() {												// Detect browser.
    var agent	= navigator.userAgent.toLowerCase();
    this.major	= parseInt(navigator.appVersion);
    this.minor	= parseFloat(navigator.appVersion);
    this.ns		= ((agent.indexOf('mozilla') != -1) && ((agent.indexOf('spoofer') == -1) && (agent.indexOf('compatible') == -1)));
	this.ns4	= (!!document.layers);
    this.ns6	= (this.ns && (this.major >= 5));
    this.ie		= (agent.indexOf("msie") != -1);
    this.ie3	= (this.ie && (this.major  < 4));
    this.ie4	= (this.ie && (this.major == 4) && (agent.indexOf("msie 5.0") == -1));
    this.ie5	= (this.ie && (this.major == 4) && (agent.indexOf("msie 5.0") != -1));
    this.ie55	= (this.ie && (this.major == 4) && (agent.indexOf("msie 5.5") != -1));
    this.ie6	= (this.ie && (agent.indexOf("msie 6.0")!=-1) );
	this.ff		= (agent.indexOf("firefox") != -1);
	return this;
}

function getElementHeight(elem) {
	var height;
	if (browser.op5) { 
		height = elem.style.pixelHeight;
	} else {
		height = elem.offsetHeight;
	}
	return height;
}

function getElementWidth(elem) {
	var width;
	if (browser.op5) {
		width = elem.style.pixelWidth;
	} else {
		width = elem.offsetWidth;
	}
	return width;
}

function getElementLeft(elem) {
	if (elem.id=="make-model-selector") {
		document.title = elem.id + " " + elem.offsetLeft + "OL " + elem.clientLeft + "CL";
	}
	var x = 0;
	var tempParent = elem.offsetParent;
	if ((browser.ff == true) ) {
		x = elem.offsetLeft;
	}
	else if ((browser.ie6 == true) ) {
		x = elem.offsetLeft + 12;
	} else {
		var x = elem.offsetLeft;
		while (tempParent != null) {
			x += tempParent.offsetLeft;
			if (elem.id=="make-model-selector") {
				document.title += " | " + tempParent.id + tempParent.offsetLeft + "OL " + tempParent.clientLeft + "CL";
			}
			tempParent = tempParent.offsetParent;
		}
	}
	return x;
}

function getElementTop(elem) {
	var y = elem.offsetTop;
	var tempParent = elem.offsetParent;
	while (tempParent != null) {
		y += tempParent.offsetTop;
		tempParent = tempParent.offsetParent;
	}
	return y;
	
}

function getElementRect(elem) {										// Returns position and size of element
	var rect = new Object();
	rect.top = getElementTop(elem);
	rect.left = getElementLeft(elem);
	rect.width = getElementWidth(elem);
	rect.height = getElementHeight(elem);
	rect.bottom = rect.top + rect.height;
	rect.right = rect.left + rect.width;
	return rect;
}



function getWindowHeight() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}


function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function ensureBottomVisible (elem, scrollSpeed, scrollFactor) {
	windowIsScrolling = true;
	var rect = getElementRect(elem);
	var scrollXY = getScrollXY();
	var windowHeight = getWindowHeight();
	previousScrollXY = scrollXY;
	while (rect.bottom >= windowHeight + scrollXY[1]) {
		scrollXY = getScrollXY();
		scroll(0,scrollXY[1]+scrollSpeed);
		scrollSpeed = scrollSpeed + scrollFactor;
		if (scrollSpeed < 1) {scrollSpeed = 1;}
	}
	windowIsScrolling = false;
}

function restoreScrollPosition () {
	var scrollXY = getScrollXY();
	if (previousScrollXY[1] > scrollXY[1]) {
		while (previousScrollXY[1] > scrollXY[1]) {
			scrollXY = getScrollXY();
			scroll(0,scrollXY[1]+1);
		}
	} else {
		while (previousScrollXY[1] < scrollXY[1]) {
			scrollXY = getScrollXY();
			scroll(0,scrollXY[1]-1);
		}
	}
}

// return object from query string
function getQueryParams(queryString) {
	 var queryObject = new Object();
	queryString = queryString.replace(/^.*\?(.+)$/,'$1');
	while ((pair = queryString.match(/([^=]+)=\'?([^\&\']*)\'?\&?/)) && pair[0].length) {
		queryString = queryString.substring( pair[0].length );
		if (/^\-?\d+$/.test(pair[2])) pair[2] = parseInt(pair[2]);
		queryObject[pair[1]] = pair[2];
	}
	return queryObject;
}

var q = getQueryParams(location.search);


/** XHConn - Simple XMLHTTP Interface - brad@xkr.us - 2005-01-24             **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4) {
        fnDone(xmlhttp); }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}


function dollarize(amount,showCents) {
	amount += '';
	var x = amount.split('.');
	var dollars = x[0];
	var cents = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(dollars)) {
		dollars = dollars.replace(rgx, '$1' + ',' + '$2');
	}
	var dollarized = '$' + dollars;
	if (showCents==true) {
		dollarized += cents;
	}
	return dollarized;
}

//--------------------------------------------------------------------------------------------------
//  Initialize
//--------------------------------------------------------------------------------------------------

var browser = browserIs();

// mdTransit default form validation function
function validateForm(formArg) {
	var firstBlankField = "";
	var blankFieldNames = new Array();
	for (i = 0; i < fields.length; i ++) {
		if ((formArg.elements[fields[i]].value == "") || (formArg.elements[fields[i]].value == "unselected")) {
			blankFieldNames.push(fieldNames[i]);
			if (firstBlankField == "") {
				firstBlankField = fields[i];
			}
		}
	}
	if (blankFieldNames.length) {
		var message = "You did not fill out all the required field(s). You are missing:\n";
		for (i = 0; i < blankFieldNames.length; i ++) {
			message += " - " + blankFieldNames[i] + "\n";
		}
		alert(message);
		formArg.elements[firstBlankField].focus();
	} else {
		formArg.submit();
	}
}



function WM_setCookie (name, value, hours, path, domain, secure) {
  // Don't waste your time if the browser doesn't accept cookies.
    // Set the cookie, adding any parameters that were specified.
    // (Convert hours to milliseconds (*3600000)
    // and then to a GMTString.)
  document.cookie = name + '=' + escape(value) + ((hours)?(';expires=' + ((new Date((new Date()).getTime() + hours*3600000)).toGMTString())):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':'');
}


function WM_readCookie(name) {
    if(document.cookie == '') { // there's no cookie, so go no further
	return false; 
    } else { // there is a cookie
	var firstChar, lastChar;
	var theBigCookie = document.cookie;
	firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
	var NN2Hack = firstChar + name.length;
	if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) { // if you found the cookie
	    firstChar += name.length + 1; // skip 'name' and '='
	    lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
	    if(lastChar == -1) lastChar = theBigCookie.length;
	    return unescape(theBigCookie.substring(firstChar, lastChar));
	} else { // If there was no cookie of that name, return false.
	    return false;
	}
    }	
} // WM_readCookie



