/*
	This method sets the hidden fileds for the contact dealer aplication call for the selected dealer
*/
function contactDealer(dId,aState,aName,aZip,aCity,aDState,aStreet,aPhone,aEmail,aDistance,aUrl,next) {
		if(debugMode){
			alert("Entered function contactDealer()");
		}
		document.contactDealer.next.value=next;
		document.contactDealer.hdnActionState.value=aState;
		document.contactDealer.hdnDealerId.value=dId;
		document.contactDealer.hdnDealerName.value=aName;
		document.contactDealer.hdnDealerZip.value=aZip;
		document.contactDealer.hdnDealerCity.value=aCity;
		document.contactDealer.hdnDealerState.value=aDState;
		document.contactDealer.hdnDealerStreet.value=aStreet;
		document.contactDealer.hdnDealerPhone.value=aPhone;
		document.contactDealer.hdnDealerEmail.value=aEmail;
		document.contactDealer.hdnDealerDistance.value=aDistance;
		document.contactDealer.hdnDealerUrl.value=aUrl;
		document.contactDealer.sourcePage.value = "TXN:DLR::DealerResults::TXNDLRDealerResults";
		document.contactDealer.submit();

		if(debugMode){
			alert("Leaving function contactDealer()");
		}
}

/*
	The following method call restricts the number of characters in the given textarea/text box to the given maximum limit.
*/
function textCounter(source,maxlimit) {
	if(debugMode){
		alert("Entered function textCounter()");
	}

	if (document.getElementById(source).value.length > maxlimit){
		// if too long...trim it!
		document.getElementById(source).value = document.getElementById(source).value.substring(0, maxlimit);
	}

	if(debugMode){
		alert("Leaving function textCounter()");
	}
}

/**
 * Function to validate the email address
 */
function checkEmail(emailStr) {
   if(debugMode){
		alert("Entered function checkEmail()");
   }

   if (emailStr.length == 0) {
	   return true;
   }
   /* SR 11693 */
   /* Modified for SR 18241 */
   var emailPat=/^[a-zA-Z](.+)@(.+)?(.+)$/;
   //var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
   //var validChars="\[^\\s" + specialChars + "\]";
   //Removed the hyphen from validChars variable to allow hyphen in emails as per SR 19530 by Dilip Raghupatruni
      var specialChars="\\(\\)<>@,;:/|'`!#%^\{\}\+\*\?\$\&\~\\\\\\\"\\.\\[\\]";
      var validChars="\[^\\s" + specialChars + "\]";
   var quotedUser="(\"[^\"]*\")";
   var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
   var atom=validChars + '+';
   var word="(" + atom + "|" + quotedUser + ")";
   var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
   var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
   var matchArray=emailStr.match(emailPat);
   if (matchArray == null) {
	   return false;
   }
   var user=matchArray[1];
   var domain=matchArray[2];
   if (user.match(userPat) == null) {
	   return false;
   }
   var IPArray = domain.match(ipDomainPat);
   if (IPArray != null) {
	   for (var i = 1; i <= 4; i++) {
		  if (IPArray[i] > 255) {
			 return false;
		  }
	   }
	   return true;
   }
   var domainArray=domain.match(domainPat);
   if (domainArray == null) {
	   return false;
   }
   var atomPat=new RegExp(atom,"g");
   var domArr=domain.match(atomPat);
   var len=domArr.length;
   if ((domArr[domArr.length-1].length < 2) ||
	   (domArr[domArr.length-1].length > 3)) {
	   return false;
   }
   if (len < 2) {
	   return false;
   }

   if(debugMode){
		alert("Leaving function checkEmail()");
   }

   return true;
}

/*
	The following function formats a string.
	If the string contains "'" then it will add "\" before it.
	Ex: If the string is "Nissan's Vehicle" then it will change it to "Nissan\'s Vehicle"
	This formatting is needed to tackle some java script errors when dynamically passing the parameters to the method call.
*/
function formatStringForQuote(inputText){
	/* if(debugMode){
		alert("Entered function formatStringForQuote()");
    } */

	var words=inputText.split(" ")
	var outputText = "";
	for(i=0;i<words.length;i++)
	{
		outputText += words[i].replace('\'',"\\'") + ' ';
	}

	/* if(debugMode){
		alert("Leaving function formatStringForQuote()");
	} */

	return outputText;
}

/*
 *	The following function is used to create a drop down box containing states.
 *	This function at present used to create "state" drop down box which is used in "driving Directions" input form
 *	We can generalize the function to create any drop down box with the information that is being passed in the method call.
*/
function addStateOption(optionData,selected) {
	if(debugMode){
		alert("Entered function addOption()");
    }

	var myArrayTokens = stateCodes.split(',');
	var myOpt = document.createElement("option");

	document.getElementById(optionData).options.add(myOpt);
	myOpt.text = "";
	myOpt.value = "";

	for(var index=0; index < myArrayTokens.length; index++){
		 myOpt = document.createElement("option");
		 document.getElementById(optionData).options.add(myOpt);
		 myOpt.text = myArrayTokens[index];
		 myOpt.value = myArrayTokens[index];
		 if (myOpt.value == selected) myOpt.selected=true;
	}

	if(debugMode){
		alert("Leaving function addOption()");
	}
}

function setupPanTail(map) {
	map.AttachEvent("onstartpan",function() {
		map.AttachEvent("onmousemove",panTail);
	});
	map.AttachEvent("onendpan",function() {
		map.DetachEvent("onmousemove",panTail);
	});
	map.AttachEvent("onstartzoom",function () { document.getElementById("panTail").style.display="none"; });
}

function zoomHandler(e) {
	if (document.getElementById("dealerPanel")) {
		if (document.getElementById("dealerPanel").style.display != "none") {
			panTail();
		}
	}
	if (e.zoomLevel >= 18 && map.IsBirdseyeAvailable()) {
		document.getElementById("MSVE_navAction_AerialMapStyle").style.display="block";
	} else {
		document.getElementById("MSVE_navAction_AerialMapStyle").style.display="none";		
	}
}

function panTail(me) {
	// console.log(me.mapX + ":" + me.mapY);
	if (document.getElementById("panTail") && positionedDealer && document.getElementById("dealerPanel") && document.getElementById("dealerPanel").style.display != "none") {
		var pt = document.getElementById("panTail");
		var px = map.LatLongToPixel(new VELatLong(positionedDealer.latitude,positionedDealer.longitude));
		var w = px.x - 368;
		var t = px.y - 30;
		if (w > 0 && t > -30 && t < 364 && w < 260) {
			pt.style.width=w+"px";
			pt.style.top=t+"px";
			pt.style.display="block";
		} else {
			pt.style.display="none";
		}
		return false;
	}
}

function rePanTail(e) {
	panTail();
	map.DetachEvent(e.eventName,rePanTail);
}

function imgSwitch() {
	var position=this.style.position;
	jQuery(this).iunfixpng();
	this.src=(/_on/ig).test(this.src)?this.src.replace("_on","_off"):this.src.replace("_off","_on");
	jQuery(this).ifixpng().css("position",position);
}

function previewPopup(el,img) {
	if (document.getElementById("previewPop")) jQuery("#previewPop").remove();
	var e = jQuery(el);
	var eo = e.offset();
	var p = jQuery(document.body);
	var a = document.createElement("div");
	a.id="previewPop";
	var tail = document.createElement("img");
	tail.src="/img/dealer_locator/arrowleft.gif";
	jQuery(tail).css({
		position: "absolute",
		top: "5px",
		left: "-22px"
	})
	a.appendChild(tail);
	var i=document.createElement("img");
	i.src=img;
	a.appendChild(i);
	jQuery(a).css({"left":(eo.left+e.width()+45)+"px","top":(eo.top-5)+"px"}).mouseout(function() { jQuery(this).remove(); });
	p.append(a);
}

function awardPopup(el,name) {
	if (document.getElementById("#awardPop")) jQuery("#awardPop").remove();
	var e = jQuery(el);
	eo = e.offset();
	var a = document.createElement("div");
	a.id="awardPop";
	document.getElementById("cdpageContent").appendChild(a);
	eop = jQuery("#cdpageContent").offset();
	var tail = document.createElement("img");
	tail.src="/img/dealer_locator/arrowleft.gif";
	var c = document.createElement("img");
	c.src="/img/dealer_locator/close.jpg";
	jQuery(c).css({
		position: "absolute",
		top: "3px", left: "235px",
		cursor: "pointer"
	});
	jQuery(tail).css({
		position: "absolute",
		top: (eo.top-eop.top)+((e.height()-22)/2)+"px",
		left: "-22px"
	});
	a.appendChild(tail);
	a.appendChild(c);
	a.innerHTML += document.getElementById(name).innerHTML;
	jQuery("#awardPop img:odd").click(function () { jQuery(this.parentNode).remove() });
}

function DLStateManager() {
	this.state=0;
	this.visibles = new Array();
	this.lastMap = {style:null,center:null,zoom:null};
	this.lastBirdseye = null;
	this.formfieldvalues = {};
	this.states = {
		START: 0,
		SEARCHINPROGRESS: 1,
		SEARCHRESULTS: 2,
		DEALERDETAILS: 3,
		NEWPAGE: 4,
		DRIVINGDIRECTIONS: 5,
		NORESULTS: 6
	};
	this.restoreState = function () {
		if (this.lastMap.style != null) {
			if ((this.lastMap.style=="o"&&map.GetMapStyle()!="o")) obliqueView();
			map.SetCenterAndZoom(this.lastMap.center,this.lastMap.zoom);
			this.lastMap={style:null,center:null,zoom:null};
		}
		for (var i = 0, l = this.visibles.length; i < l; i++) {
			document.getElementById(this.visibles[i]).style.display="block";
		}
	}
	
	this.changeState = function (newstate) {
		this.visibles = new Array();
		switch (newstate) {
			case this.states.NORESULTS:
				if (document.getElementById("searchResults")) {this.visibles.push("searchResults"); jQuery("#searchResults").css("display","block"); }
			case this.states.SEARCHRESULTS:
				if (document.getElementById("drivingDirectionsResults")) { this.visibles.push("drivingDirectionsResults");jQuery("#drivingDirectionsResults").css("display","none"); }
				if (document.getElementById("searchResults")) { this.visibles.push("searchResults"); jQuery("#searchResults").css("display","block"); }
			case this.states.SEARCHINPROGRESS:
			case this.states.DRIVINGDIRECTIONS:
				if (newstate==this.states.DRIVINGDIRECTIONS) {
					this.lastMap = {style: map.GetMapStyle(), center: map.GetCenter(), zoom: map.GetZoomLevel()};
				}
			case this.states.NEWPAGE:
				if (document.getElementById("panTail") && document.getElementById("panTail").style.display=="block") { this.visibles.push("panTail"); }
				if (document.getElementById("dealerPanel")) { this.visibles.push("dealerPanel"); hidePanel(); }
				if (document.getElementById("inputBox").style.display != "none") { this.visibles.push("inputBox"); jQuery("#inputBox").css("display","none"); }
			case this.states.DEALERDETAILS:
				if (document.getElementById("awardPop")) { this.visibles.push("awardPop"); jQuery("#awardPop").css("display","none"); }
				break;
		}
		this.state = newstate;
	};
}

// Function to trim a given string
function trimDE(s)
{
	if (typeof(s)=="string"){
		return rtrim(ltrim(s));
	}else{
		return s;
	}
}

// Function to trim the left side of a string
function ltrim(s)
{
	var l=0;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	return s.substring(l, s.length);
}

// Function to trim the right side of the string
function rtrim(s)
{
	var r=s.length -1;
	while(r > 0 && s[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

function isNullOrEmpty(input){
	if(input == null || input ==""){
		return true;
	}else{
		return false;
	}
}