/*****************************************************************************************************
*********	library.js -- javascript functions commonly used site-wide maintained here for consistency
*************************************************************************************************** */
var _g_image_rollover_obj = null;
var $j = {};
if (typeof jQuery === "function") {
	$j = jQuery.noConflict();
}

function RollOver(obj, new_image){
	obj.original_src = obj.src;
	_g_image_rollover_obj = obj;
	obj.src = new_image
}

function RollOut(){
	if(_g_image_rollover_obj != null){
		_g_image_rollover_obj.src = _g_image_rollover_obj.original_src;
	}
}

function limitLength(field, maxChars)
{
	//puropose: disallows entry of text over specified field length
	//dev note: common usage is for textareas (as they do not have maxlength attribute) via onKeyPress event
	
	if(field.value.length >= maxChars)
	{
		field.value = field.value.substr(0,maxChars-1);
	}
}

function getQueryStringValue(strQueryString, name)
{
	//purpose: gets the value of a querystring parameter ( 'index.asp?parameter=value&parameter2=value ) 
	//dev note: common usage of strQueryString is: window.location.href
	
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( strQueryString );
	if( results == null )
		return "";
	else
		return results[1];
}

function toggleDisplay(el)
{
	//purpose: hides or reveals a hidden HTML element (i.e. div layers)
	//dev note: pass in a HTML element (ex. document.getElementById("foo") )
	
	if (el.style.display == "none")
	{
		el.style.display = "";
	}
	else
	{
		el.style.display = "none";
	}
}

function addOverflow(id, limit) {

  var dElement = document.getElementById(id);
  var dElementHeight = dElement.offsetHeight; // actual rendered div height
  if (dElementHeight > limit) {
     dElement.style.height = limit + 'px'; // set div height to height of the limit
     dElement.style.overflowY = 'scroll'; // and make the area overflowable to show the rest
  }

}

function open_win(url, width, height)
{
	// purpose: open a new window with adjustable height and width
	window.open(url, 'bwwindow', 'width=' + width + ',height=' + height + ',menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');
}

function removeElement(parent, div){

	// purpose: remove a child element from a parent
	
	var d1=document.getElementById(parent);
	var d2=document.getElementById(div);
	d1.removeChild(d2);
	
} 

function Left(str, n){

	//purpose: add left vbscript style functionality

	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){

	//purpose: add right vbscript style functionality

    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function add_list_item(ob, value, text){

	// purpose: add an option to a select/dropdown box
	var option = document.createElement("OPTION");
	IE = ((document.all)&&(navigator.appVersion.indexOf("MSIE")!=-1)) ? true : false;

	option.value = value;
	option.text = text;

	if (IE)
		ob.add(option);
	else
		ob.add(option, null);
		
}

function empty_list(ob){

	//purpose: empty all contents of a select box
	while(ob.length){
		ob.remove(0);
	}
	
}
    	
function formatCurrency(strValue){

	//purpose: format a string as currency
	
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	dblValue = Math.floor(dblValue/100).toString();

	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
				   dblValue.substring(dblValue.length-(4*i+3));
		
	return (((blnSign)?'':'-') + '$' + dblValue);
	
}

function viewBrochure(path, vin) {

	// purpose: open custom window sticker product for backwebs
	var link = path + "brochure.asp?vehicle=" + vin;
	window.open (link,"VehicleBrochure","status=1,scrollbars=1,menubar=1,resizable=1,width=850,height=900"); 

}

function previewBrochure(){
	jQuery('#print').val('0');
	jQuery('form.printBrochure').submit();
	
}

function printBrochure(){
	jQuery('#print').val('1');
	jQuery('form.printBrochure').submit();
	
}

function open_unity(URL) {
	window.open(URL, 'UnityMediaWorks', 'height=240,width=320');
}

function printPage(path, vin, manager_label_text, show_manager_name) {
	
	if( typeof(manager_label_text) != "string" )
		manager_label_text = "";
	if( typeof(show_manager_name) != "string" )
		show_manager_name = "true";
	
	// purpose: open custom window sticker product for backwebs
	var link = path + "window_sticker.asp?vehicle=" + vin + "&manager_label_text=" + manager_label_text + "&show_manager_name=" + show_manager_name;
	window.open (link,"WindowSticker","status=1,scrollbars=1,menubar=1,resizable=1,width=850,height=900"); 

}

function go_url(_argument, value){

	// purpose: redirects to same page replacing existing querystring argument with new one specified, keeping all other arguments the same
	
	var current_url = unescape(location.href);
	var q_pos = current_url.indexOf('?');
	var querystring = current_url.substring(q_pos + 1);
	var new_querystring = '';
	var found__argument = false;
	_arguments = querystring.split('&');
	for (i = 0; i < _arguments.length ; i++){
		if (_arguments[i].indexOf(_argument + '=') >= 0){
			_arguments[i] = _argument + '=' + value;
			found__argument = true;
		}
		new_querystring += _arguments[i] + '&';
	}
	//eliminate trailing ampersand
	new_querystring = new_querystring.substring(0, new_querystring.length - 1);
	if (found__argument == false){
		new_querystring = querystring + '&' + _argument + '=' + value;
	}
	
	newLocationString = '?' + new_querystring;
	location.href= newLocationString;
	
}  

function hideActionForm() {

	// purpose: hide the form barebones panel
	
	//Reset form div displays
	document.getElementById('actionForm_loading').style.display = 'none';
	document.getElementById('actionForm_error').style.display = 'none';
	document.getElementById('actionForm_thankyou').style.display = 'none';	
	document.getElementById('actionForm_content').style.display = '';
	
	// Reset nside content so old data doesnt flash before repulling in
	document.getElementById('actionForm_content').innerHTML = '';
	
	//Reset screen and hide main form area
	clearInterval(intervalID);
	jQuery('#formContainer').fadeOut("fast");
    document.getElementById('screen').style.display = 'none';
	
}

function redirect(loc) {
	// purpose: redirect user to new url
	window.location = loc;
}

function SpaceToUscore(str) {
	// purpose: replaces spaces with underscores for formatting of parameters
	str = str.replace(/\s+/g, "_");
	return str;
}

function goToUrl(link) {
	window.open(link);
}

function escapeForSearch(param){
	
	return escape(unescape(param.replace(/%2f/gi,'&#47;'))).replace(/\+/g,"_").replace(/%/g,"%25");
}

function stocksearch(baseUrl){
	var stock = trim(document.getElementById('stock').value);
	var bwCommonUrl = jQuery('#bwCommon').html();
	
	if (stock == "") {
		inlineMsg('stock', '<strong>Error</strong><br />No search terms were entered.', 2);
	} else { 
		var params = 
		{
			bwUrl: jQuery('#bwUrl').html(),
			reseller: jQuery('#bwResellerFolder').html(),
			stock: stock
		};
		
		jQuery.ajax({
			// jsonp allows cross domain ajax requests by loading <script></script> tags.
			dataType: 'jsonp',
			url: bwCommonUrl + 'Common/webservice/stock-number-search.asp',
			data: params,
			success: function(data){
				if ( data.exists ) {
					if ( baseUrl.indexOf("browse") > 0 ) {
						baseUrl = baseUrl.replace(/type_[\d\w,]+\//gi,"type_"+data.type.toLowerCase()+"/");
						baseUrl = baseUrl.replace(/stock_[\d\w,]+\//gi,"");
						baseUrl = baseUrl.concat( "stock_"+stock+"/" );
					} else {
						baseUrl = baseUrl.concat( 'browse/view_detailed/type_' + data.type.toLowerCase() + '/stock_' + stock.toString() + '/' );
					}
					
					redirect(baseUrl);
					
				} else {
					if (typeof(inlineMsg) == "function") {
						inlineMsg('stock', '<strong>Error</strong><br />Stock number does not exist.', 2);
					} else if (typeof(HNSITE.UI.Tooltips) == "object") {
						$j('#stock').attr('title','Stock number does not exist.');
					
						HNSITE.UI.Tooltips.TipOver('#stock');
						setTimeout(function() {
							HNSITE.UI.Tooltips.TipOut('#stock');
						}, 1500);
					}
				}
			},
			error: function() {
				if (typeof(inlineMsg) == "function") {
					inlineMsg('stock', '<strong>Error</strong><br />A server error has ocurred. Try again later.', 2);
				} else if (typeof(HNSITE.UI.Tooltips) == "object") {
					$j('#stock').attr('title','Server error. Please try again.');
				
					HNSITE.UI.Tooltips.TipOver('#stock');
					setTimeout(function() {
						HNSITE.UI.Tooltips.TipOut('#stock');
					}, 1500);
				}
			},
			// IE is having major issues with window.XMLHttpRequest. Forcing to MS XML.
			xhr: function() {
				if ( document.compatMode && document.all ) {
					return new window.ActiveXObject("Microsoft.XMLHTTP");
				} else {
					return new window.XMLHttpRequest();
				}
			}
		});
	}
	
	return false;
}

function keywordsearch(baseUrl,id){
	if( id )
		var keywords = trim(document.getElementById(id).value);
	else
		var keywords = trim(document.getElementById('keyword').value);

	
	//remove excess whitespace but preserve separate words
	keywords = keywords.replace(/([^\w\d\-]\s*)|(\s*[^\w\d\-])/g,",");
	
	if (keywords == "") {
		inlineMsg('keyword', '<strong>Error</strong><br />No search terms were entered.', 2);
	} else { 
	
		if( baseUrl.indexOf("browse") > 0 ){ //browse page - keep search variables
			
			baseUrl = baseUrl.replace(/keywords_[\d\w,]+\//gi,"");
			baseUrl = baseUrl.concat( "keywords_"+keywords+"/" );
			redirect(baseUrl);
			
		} else { //just go to browse with type both
			if( jQuery('#searchVehicleType').length > 0 )
				type = jQuery('#searchVehicleType').val();
			else
				type = "both";
			redirect(baseUrl + 'browse/view_detailed/type_'+ type +'/keywords_' + keywords + '/');
		}
		
	}
	
	return false;
}


function IsNumeric(sText)
{
	// purpose: check if string is numeric
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;


	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
   
}

function toggleAllCheckboxes(referrer,checkboxgroup)
{
	//purpose: handles checking or unchecking all checkboxes of a specified name
	//dev note: referrer is the handling element

	for (i = 0;i < checkboxgroup.length;i++)
	{
		checkboxgroup[i].checked = referrer.checked;
	}
}

function checkAll(field)
{
	//purpose: 'checks' all checkboxes of specified name

	for (i = 0; i < field.length; i++)
	{
		field[i].checked = true;
	}
}
 
function uncheckAll(field)
{
	//purpose: 'unchecks' all checkboxes of specified name
	
	for (i = 0; i < field.length; i++)
	{
		field[i].checked = false ;
	}
}

function clean_xml(x)
{
	//purpose: escapes XML reserved characters
	if (x != "")
	{
		x = x.replace(/&/g,"&amp;");
		x = x.replace(/</g,"&lt;");
		x = x.replace(/>/g,"&gt;");
	}
	return x;
}

function leftPosition(target) {
	
	//purpose: calculate the position of the element in relation to the left of the browser
	
	var left = 0;
	if (target.offsetParent) {
		while (1) {
			left += target.offsetLeft;
			if(!target.offsetParent) {
				break;
			}
			target = target.offsetParent;
		}
	}
	else if (target.x) {
		left += target.x;
	}
	return left;

}

function topPosition(target) {

	//purpose: calculate the position of the element in relation to the top of the browser window
	
	var top = 0;
	if (target.offsetParent) {
		while (1) {
		top += target.offsetTop;
		if (!target.offsetParent) {
			break;
		}
		target = target.offsetParent;
		}
	} 
	else if (target.y) {
		top += target.y;
	}
	return top;
	
}

function timestamp() {
	return Math.round(new Date().getTime());
}

function get_date_time()
{
	var datetime = "";
	var currentTime = new Date();
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	var year = currentTime.getFullYear();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var ampm = "";
	if (minutes < 10) {
		minutes = "0" + minutes;
	}
	if(hours > 11){
		ampm = "PM";
	}
	else{
		ampm = "AM";
	}
	
	datetime = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + ampm;
	
	return datetime;
}

function isEmailValid(email) {

	// purpose: return true if email address is valid
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
	if(reg.test(email) == false)
		return false;
	else
		return true;
		
}

function isCommentValid(comments) {

	// purpose: return true if comments from textarea are legit by checking for html etc
	var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
	
	if(comments.match(messageRegex) == false)
		return true;
	else
		return false;
		
}

function bookmark(url, title){
	
	// purpose: prompt user to bookmark the current page
	
	if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
		window.external.AddFavorite(url,title);
	} else if (navigator.appName == "Netscape") {
		window.sidebar.addPanel(title,url,"");
	} else {
		alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
	}
	
}

function ellipsisTrim(data,length)
{
	//if the data is longer then the length param then trim and add ... to the end
	var trimmed_data = "";
	if (data.length > length)
	{
		trimmed_data = data.substr(0,length) + "...";
	}
	else
	{
	    trimmed_data = data;
	}
		
	return trimmed_data;
}

function trim(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim)
{
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim)
{
	return stringToTrim.replace(/\s+$/,"");
}