
var initLoad = false;
var map, mapx ;
var mapArray = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
var point;
var mapTypeControl = new GMapTypeControl();
var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
var http = createRequestObject();
var trckHttp = createRequestObject();
var progressBar;
var stateCode="";
var INVALIDZIP = "InvalidZip";
var notAvailableInStateCodeMessage = '<bean:message key="agentlocator.al.agentlocator.mercurynotavailable"/>';
var stateArr= {AL:'ALABAMA',AK:'ALASKA',AS:'AMERICAN SAMOA',AZ:'ARIZONA',AR:'ARKANSAS',CA:'CALIFORNIA',CO:'COLORADO',CT:'CONNECTICUT',DE:'DELAWARE',DC:'DISTRICT OF COLUMBIA',FM:'FEDERATED STATES OF MICRONESIA',FL:'FLORIDA',GA:'GEORGIA',GU:'GUAM',HI:'HAWAII',ID:'IDAHO',IL:'ILLINOIS',IN:'INDIANA',IA:'IOWA',KS:'KANSAS',KY:'KENTUCKY',LA:'LOUISIANA',ME:'MAINE',MH:'MARSALL ISLANDS',MD:'MARYLAND',MA:'MASSACHUSETTS',MI:'MICHIGAN',MN:'MINNESOTA',MS:'MISSISSIPPI',MO:'MISSOURI',MT:'MONTANA',NE:'NEBRASKA',NV:'NEVADA',NH:'NEW HAMPSHIRE',NJ:'NEW JERSEY',NM:'NEW MEXICO',NY:'NEW YORK',NC:'NORTH CAROLINA',ND:'NORTH DAKOTA',MP:'NORTHERN MARIANA ISLANDS',OH:'OHIO',OK:'OKLAHOMA',OR:'OREGON',PW:'PALAU',PA:'PENNSYLVANIA',PR:'PUERTO RICO',RI:'RHODE ISLAND',SC:'SOUTH CAROLINA',SD:'SOUTH DAKOTA',TN:'TENNESSEE',TX:'TEXAS',UT:'UTAH',VT:'VERMONT',VI:'VIRGIN ISLANDS',VA:'VIRGINIA',WA:'WASHINGTON',WV:'WEST VIRGINIA',WI:'WISCONSIN',WY:'WYOMING'};
var fiftyStatesArr = {AL:'Alabama',AK:'Alaska',AZ:'Arizona',AR:'Arkansas',CA:'California',CO:'Colorado',CT:'Connecticut',DE:'Delaware',DC:'District of Columbia',FL:'Florida',GA:'Georgia',HI:'Hawaii',ID:'Idaho',IL:'Illinois',IN:'Indiana',IA:'Iowa',KS:'Kansas',KY:'Kentucky',LA:'Louisiana',ME:'Maine',MD:'Maryland',MA:'Massachusetts',MI:'Michigan',MN:'Minnesota',MS:'Mississippi',MO:'Missouri',MT:'Montana',NE:'Nebraska',NV:'Nevada',NH:'New Hampshire',NJ:'New Jersey',NM:'New Mexico',NY:'New York',NC:'North Carolina',ND:'North Dakota',OH:'Ohio',OK:'Oklahoma',OR:'Oregon',PA:'Pennsylvania',RI:'Rhode Island',SC:'South Carolina',SD:'South Dakota',TN:'Tennessee',TX:'Texas',UT:'Utah',VT:'Vermont',VA:'Virginia',WA:'Washington',WV:'West Virginia',WI:'Wisconsin',WY:'Wyoming'};
//onerror=handleErr;
var AQLURL = "";

function checkEnter(e){ 
	$("#errors").hide();	
	if(window.event && window.event.keyCode == 13){
		//progressBar = new Boxy('#progress_bar');
		//progressBar.show();
		clickedOnSubmit();
		//hitServerForTracking(agentDirectoryListingUserSelect+'?Zip='+document.getElementById("zipCodeAgent").value );
		//searchAgents();
	} 
	else if (e && e.which == 13){
		clickedOnSubmit();
		//var test = document.getElementsByName("Products");
		//if( test.length != 0 ){
			//test[0].checked = true;
		//}
		//progressBar = new Boxy('#progress_bar');
		//progressBar.show();
		//hitServerForTracking(agentDirectoryListingUserSelect+'?Zip='+document.getElementById("zipCodeAgent").value );
		//searchAgents();
	}
	else {
		return true;
	}
}
function handleErr(msg,url,l)
{
	var txt = '<bean:message key="agentlocator.al.agentlocator.refresh"/>';
	alert( txt );
	return false;
} 

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

function clickedOnSubmit(){
	var test = document.getElementsByName("Products");
	if( test.length != 0 ){
		test[0].checked = true;
	}
	//alert( agentDirectoryListingUserSelect+'?Zip='+document.getElementById("zipCodeAgent").value );
	hitServerForTracking(agentDirectoryListingUserSelect+'?Zip='+document.getElementById("zipCodeAgent").value );
	searchAgents();	
}

function searchAgents() {
	//show('loadingImg', null, null , null , 300 , 600 );
	showLoadingLayer();
	var time = new Date();
	var zipcode = document.getElementById("zipCodeAgent").value;
	var streetAddress = document.getElementById("streetAddress").value;
	var lpref = document.getElementById("lpref").value;
	var reqLangName = document.getElementById("reqLangId").value;
	var lineOfBusiness = 'Auto';
	var test = document.getElementsByName("Products");
	for( i = 0 ; i < test.length ; i++ ){
		if( test[i].checked ){
			lineOfBusiness = test[i].value;
			break;
		}
	}	
//			hitServerForTracking(agentDirectoryListingUserSelect+'?Zip='+zipcode+'ProductLine='+lineOfBusiness );
	http.open('get', 'results.do?command=searchAgents&zipCode='+zipcode + '&streetAddress='+streetAddress + '&lineOfBusiness='+lineOfBusiness + '&langPref='+lpref +'&lang='+reqLangName  );
    //http.open('get', 'results.do?command=searchAgents&zipCode='+ jQuery.trim(zipcode) + '&streetAddress='+streetAddress + '&lineOfBusiness='+lineOfBusiness + '&languagePreference='+lpref);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function searchCCAgents() {
	//show('loadingImg', null, null , null , 300 , 600 );
	showLoadingLayer();
	var time = new Date();
	var zipcode = document.getElementById("zipCodeAgent").value;
	var streetAddress = document.getElementById("streetAddress").value;
	var lpref = document.getElementById("lpref").value;
	var lineOfBusiness = 'Auto';
	var test = document.getElementsByName("Products");
	for( i = 0 ; i < test.length ; i++ ){
		if( test[i].checked ){
			lineOfBusiness = test[i].value;
			break;
		}
	}	

    //http.open('get', 'results.do?command=searchAgents&zipCode='+zipcode + '&streetAddress='+streetAddress + '&languagePreference='+lpref + '&lineOfBusiness='+lineOfBusiness );
    http.open('get', 'results.do?command=searchAgents&zipCode='+zipcode + '&streetAddress='+streetAddress + '&lineOfBusiness='+lineOfBusiness );
    http.onreadystatechange = handleResponse;
	http.send(null);
}


function gotoALPage( pageNumber ){
	//show('loadingImg', null, null , null , 300 , 600 );
	showLoadingLayer();
	var zipcode = document.getElementById("zipCodeAgent").value;
	var streetAddress = document.getElementById("streetAddress").value;
	var lpref = document.getElementById("lpref").value;
	//streetAddress = encodeInput( streetAddress );
   
    http.open('get', 'results.do?command=gotoPage&pageNumber='+pageNumber+'&zipCode='+zipcode + '&streetAddress='+streetAddress+ '&languagePreference='+lpref ); 	
    http.onreadystatechange = handleResponse;
    http.send(null);
 
    
}

function gotoCALL_CENTER_AGENTSPage( pageNumber ){
	gotoALPage( pageNumber );
}
		
function handleResponse() {
	var divElement = document.getElementById("container");
	if(http.readyState == 4){
	
		//setTimeout( "hide('loadingImg')", 1000 );
		//hide('loadingImg');

		var response = http.responseText;
		document.getElementById("container").innerHTML = response;
		///alert( response );		
		var totalAgents = document.getElementById("totalAgents");
		if( totalAgents != null ){
			loadMap( totalAgents.value );
		}
		progressBar.hide();
		startBoxy();
		//document.title = "Mercury Insurance Agent - Find an Agent Results";	//Defect # 29579 Fix
		var stateCode = document.getElementById("agentState").value;
		var outOfState = $("#outOfState").val();
		//var noSpanishResults = $("#noSpanishId").val();
		//if(noSpanishResults!="null" && noSpanishResults=="true"){
		//	noSpanish1();
		//}
		if (outOfState != "null"){
			if(outOfState == "true"){
				if (stateCode in fiftyStatesArr){
					var stateDesc = fiftyStatesArr[stateCode];
					var zipCodeErrorMessage = notAvailableInStateCodeMessage + " " + jQuery.trim(stateDesc) + ".";
					$("#stateCodeId").html(zipCodeErrorMessage); 
					showZipError(stateCode);		
				} else {
					zipErrorGeneric();
				} 
			} 
		} else if (stateCode == INVALIDZIP){
			zipErrorGeneric();
		}

		
		$("#zipCodeAgent").focus();
		
		clearTimeout(timeOutInitialTimer);
		timeOutInitialTimer = setTimeout(timeOutInitial, timeOutInitialSeconds);
	
		clearTimeout(timeOutShowTimer);
		timeOutShowTimer = setTimeout(timeOutShow, timeOutMilliSeconds);		
		
		// Re-initialize the top menubar
	    $("ul.sf-menu").superfish({
	        delay: 200,
	        autoArrows: false,
	        disableHI: false
	    });			
	}
}
function getQuote( agentCode ){
	hide('agentLocatorTableWrapper'+agentCode);
			//show('loadingImg', null, null , null , 50 , 600 );
	showLoadingLayer();
	http.open('get', 'getQuote.do?command=showQuoteRequestPage&agentCode='+agentCode);
	http.onreadystatechange = handleShowRequestQuote;
	http.send(null);
}

function handleShowRequestQuote() {
 var divElement = document.getElementById("requestQuotePage");
    if(http.readyState == 4){
		//hide('loadingImg');
		progressBar.hide();
        var response = http.responseText;
        document.getElementById("requestQuotePage").innerHTML = response;
		show( 'requestQuotePage', null , null, null, 400, 610 );
    }
}

function submitQuote( agentCode ){
	hide('requestQuotePage');
	//show('loadingImg', null, null , null , 300 , 600 );
	showLoadingLayer();
	var localForm = document.forms["quoteForm"];
	var commentsValue = localForm.comments.value;

	var addr1 = localForm.requestorAddress1.value;
	var addr2 = localForm.requestorAddress2.value;
	addr1 = addr1.replace("#" , "%23" );
	addr2 = addr2.replace("#" , "%23" );
	var postString = 'submitQuote.do?command=submitQuoteRequest'
					+'&requestorFirstName='+localForm.requestorFirstName.value
					+'&requestorLastName='+localForm.requestorLastName.value
					+'&requestorAddress1='+addr1
					+'&requestorAddress2='+addr2
					+'&requestorCity='+localForm.requestorCity.value
					+'&requestorState='+localForm.requestorState.value
					+'&requestorZip='+localForm.requestorZip.value
					+'&requestorPhone1='+localForm.requestorPhone1.value
					+'&requestorPhone2='+localForm.requestorPhone2.value
					+'&requestorPhone3='+localForm.requestorPhone3.value
					+'&requestorPhoneType='+localForm.requestorPhoneType.options[localForm.requestorPhoneType.selectedIndex].value
					+'&requestorSecondaryPhone1='+localForm.requestorSecondaryPhone1.value
					+'&requestorSecondaryPhone2='+localForm.requestorSecondaryPhone2.value
					+'&requestorSecondaryPhone3='+localForm.requestorSecondaryPhone3.value
					+'&requestorSecondaryPhoneType='+localForm.requestorSecondaryPhoneType.options[localForm.requestorSecondaryPhoneType.selectedIndex].value
					+'&howDidYouHear='+localForm.howDidYouHear.value
					+'&requestorEmailAddress='+localForm.requestorEmailAddress.value
					+'&comments='+localForm.comments.value;
    http.open('post', postString);
    http.onreadystatechange = handleSubmitQuote;
    http.send(null);
}

function handleSubmitQuote() {
 var divElement = document.getElementById("requestQuotePage");
    if(http.readyState == 4){
        var response = http.responseText;
        document.getElementById("requestQuotePage").innerHTML = response;
		setTimeout( "showLoadingLayer()", 1000 );
		//hide('loadingImg');
		progressBar.hide();
		if( document.getElementById("quoteError") != null ){
			var divTag = document.getElementById('transperant');
			divTag.style.display = "block";
			
			if(  document.getElementById('iframetop') != null ){
				divTag = document.getElementById('iframetop');
				divTag.style.display = "block";
			}
			
		}
		show( 'requestQuotePage', null , null, null, 400, 610 );
		
    }
}

function loadMap( length){
	load();
	var agentInfo;
	var agentInfoArray;
	var i = 0;
	var initLatitude ;
	var initLongitude ;
	
	//var initLatitude  = document.getElementById("centerLat" ).value;
	//var initLongitude  = document.getElementById("centerLong" ).value;
	var infoWindowCaption = "";
	//alert( initLatitude + ": " + initLongitude );
	for( i = 0 ; i <  length  ; i++ ){
		agentInfo = document.getElementById("agentInfo"+i ).value;
		agentInfoArray = agentInfo.split("^");
		initLatitude =  agentInfoArray[0] ;
		initLongitude = agentInfoArray[1];
		
		$("#zipCodeAgent").focus();
		
		if( initLatitude != "-1" ){
			setMapCenter( initLatitude , initLongitude );
			break;
		}
	}
	
	for( i = 0 ; i <  length  ; i++ ){
		agentInfo = document.getElementById("agentInfo"+i ).value;
		agentInfoArray = agentInfo.split("^");
		if( agentInfoArray[0] != -1 ){
			addPointToMap( map,  agentInfoArray[0] , agentInfoArray[1] , agentInfoArray[2] ,  agentInfoArray[3] );
			
			show('agentLocatorPopWrapper'+agentInfoArray[4], agentInfoArray[0] ,agentInfoArray[1] , agentInfoArray[2] , 300, 600 , agentInfoArray[3] ); // show moreDetails Map
		}
		
	}

}

function load( divTag ) {
	if (GBrowserIsCompatible()) {
	
		if( document.getElementById("agentLocatorResultsGoogleMap") != null ){
			map = new GMap2(document.getElementById("agentLocatorResultsGoogleMap") , {size:new GSize(350,500)});
			map.addControl(new GSmallMapControl());
		}
		//map.addControl(mapTypeControl);
		
	}
}

function load( ) {
	if (GBrowserIsCompatible()) {
	
		if( document.getElementById("agentLocatorResultsGoogleMap") != null ){
			map = new GMap2(document.getElementById("agentLocatorResultsGoogleMap") , {size:new GSize(350,500)});
			map.addControl(new GSmallMapControl());
			$('#map_container').show();
		}
		//map.addControl(mapTypeControl);
		
	}
}
	    
	    function setMapCenter( latitude, longitude ) {
			var searchRange = document.getElementById( "searchRange" );
			var searchRangeVal;
			var zoomLevel = 13;
			if( searchRange != null ){
 					searchRangeVal = parseInt( searchRange.value) ;
					if( searchRangeVal > 200 ){
	 					zoomLevel = 5;
					}else{
	 					if( searchRangeVal > 80 ){
		 					zoomLevel = 6;
					    }else{
		 					if( searchRangeVal > 40 ){
			 					zoomLevel = 7;
		 					}else{
								if( searchRangeVal > 18 ){
									zoomLevel = 8;
								}else{
									if( searchRangeVal > 15 ) {
										zoomLevel = 9;
									}else{
										if( searchRangeVal > 5 ) {
											zoomLevel = 10;
										}else{
											if( searchRangeVal >= 3 ) {
												zoomLevel = 11;
											}else{
												if( searchRangeVal >= 2 ) {
													zoomLevel = 11;
												}								
											}							
										}
									}
								}
		 					}
						}
					}		
			}
			//alert( zoomLevel );
			//alert(  'searchRange :' + searchRange.value + ' zoomLevel : ' + zoomLevel );
	    	//map.setCenter(new GLatLng( (parseFloat( latitude )  + 0.03 ), longitude ), parseInt( zoomLevel ) );
	    	map.setCenter(new GLatLng( latitude , longitude ), parseInt( zoomLevel ) );
	    }
	    /*
	    function setMapCenterWithCaption( latitude, longitude , caption ) {

			point = new GLatLng(latitude, longitude );
	    	//map.setCenter(new GLatLng(latitude, longitude ),13);
			//map.setCenter(new GLatLng( (parseFloat( latitude )  + 0.09 ), longitude ),13);
			map.setCenter(new GLatLng(  latitude, longitude ),13);
   	        map.openInfoWindowHtml(point,caption);
	    	
	    }*/
	    
	    function setMapCenterWithCaption( elementID ) {
			var agentInfo;
			var agentInfoArray;
			
			agentInfo = document.getElementById( elementID ).value;
			agentInfoArray = agentInfo.split("^");
			//initLatitude =  agentInfoArray[0] ;
			//initLongitude = agentInfoArray[1];
				
			point = new GLatLng(agentInfoArray[0], agentInfoArray[1] );
	    	//map.setCenter(new GLatLng(latitude, longitude ),13);
			//map.setCenter(new GLatLng( (parseFloat( latitude )  + 0.09 ), longitude ),13);
			map.setCenter(new GLatLng(   agentInfoArray[0] ,  agentInfoArray[1]  ),13);
   	        map.openInfoWindowHtml(point,agentInfoArray[3]);
	    	
	    }
	    
function addPointToMap(  currentMap, latitude , longitude, imageSrc , infoWindowCaption ){

	var marker;
  		point = new GLatLng(latitude, longitude );
		if( imageSrc == 'xx' ){
			marker = new GMarker(point , markerOptions );
		        GEvent.addListener(marker,"click", function() {
		          marker.openInfoWindowHtml(infoWindowCaption );
		    });
			currentMap.addOverlay(new GMarker(point));           
		}else{
			blueIcon.image = imageSrc;
      		markerOptions = { icon:blueIcon };
			marker = new GMarker(point , markerOptions );
		        GEvent.addListener(marker,"click", function() {
		          marker.openInfoWindowHtml(infoWindowCaption );
		        });
  			currentMap.addOverlay( marker );     
		}	
}

function showLayer( layerName ) {
	var divTag = document.getElementById(layerName);
	divTag.style.display = "block";
}


function showLoadingLayer() {
	progressBar = new Boxy( '#progress_bar' , {modal: true} );
	progressBar.show();
/*
    divTag = document.getElementById('loadingImg');
	divTag.style.display = "block";
	divTag.style.position='absolute';
	divTag.style.zIndex=2;

	leftPosition = (screen.width) ? (screen.width - 1000)/2 : 0;
	topPosition = document.documentElement.scrollTop + 100;

	divTag.style.left=( leftPosition )+ 'px';
	divTag.style.top=( topPosition ) +'px';
*/
}


function showMoreDetails( layerId , agentCounter ){
	var	agentInfo = document.getElementById( layerId ).value;
	var agentInfoArray = agentInfo.split("^");
	show('agentLocatorPopWrapper'+agentInfoArray[4], agentInfoArray[0] ,agentInfoArray[1] , agentInfoArray[2] , 300, 600 , agentInfoArray[3], agentCounter );
	new Boxy("#"+agentCounter, {modal: true});
}

// new show agent information
function show( layerName , latitude , longitude  , imgSrc , height, width , infoWindowCaption , agentCounter ){

	if( imgSrc != null ){
		loadTempMaps( layerName +'Map' , latitude , longitude , imgSrc , infoWindowCaption , agentCounter );
	}
	//var divTag = document.getElementById('transperant');
	//divTag.style.display = "block";
	//divTag.style.left= '0px';
	//divTag.style.top= '0px';
	if(  document.getElementById('iframetop') != null ){
		divTag = document.getElementById('iframetop');
		divTag.style.display = "block";
	}


    //divTag = document.getElementById(layerName);

	//divTag.className='agentLocatorPopWrapper';
	//divTag.style.display = "block";
	//divTag.style.position='absolute';
	//divTag.style.zIndex=10;

	//leftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	//topPosition = (screen.height) ? (screen.height-height)/2 : 0;
	
	//leftPosition = document.documentElement.scrollLeft;
	//topPosition = document.documentElement.scrollTop+100;

	//alert( topPosition );
	


	//divTag.style.left=( leftPosition )+ 'px';
	//divTag.style.top=( topPosition ) +'px';	
}

function loadTempMaps( divTag  , latitude , longitude , imgSrc , infoWindowCaption , agentCounter ){
	if( latitude == "-1" ){
		return;
	}
/*
    mapx = new GMap2(document.getElementById(divTag) , {size:new GSize(350,287)});
	mapx.addControl(new GSmallMapControl());
	addPointToMap( mapx , latitude , longitude ,  imgSrc , infoWindowCaption );
	mapx.setCenter(new GLatLng(latitude, longitude), 14);
	mapx.panTo(new GLatLng(latitude, longitude));
	*/
	
	mapArray[agentCounter] = new GMap2(document.getElementById(divTag) , {size:new GSize(350,287)});
	mapArray[agentCounter].setCenter(new GLatLng(latitude, longitude), 14);
	mapArray[agentCounter].addControl(new GSmallMapControl());
	mapArray[agentCounter].setZoom(14);
	addPointToMap( mapArray[agentCounter] , latitude , longitude ,  imgSrc , infoWindowCaption );
	mapArray[agentCounter].panTo(new GLatLng(latitude, longitude));
}

/*
function show( layerName , latitude , longitude  , imgSrc , height, width , infoWindowCaption ){

	var divTag = document.getElementById('transperant');
	divTag.style.display = "block";
	divTag.style.left= '0px';
	divTag.style.top= '0px';
	if(  document.getElementById('iframetop') != null ){
		divTag = document.getElementById('iframetop');
		divTag.style.display = "block";
	}


    divTag = document.getElementById(layerName);

	divTag.className='agentLocatorPopWrapper';
	divTag.style.display = "block";
	divTag.style.position='absolute';
	divTag.style.zIndex=10;

	leftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	//topPosition = (screen.height) ? (screen.height-height)/2 : 0;
	
	//leftPosition = document.documentElement.scrollLeft;
	topPosition = document.documentElement.scrollTop+100;

	//alert( topPosition );
	


	//divTag.style.left=( leftPosition )+ 'px';
	divTag.style.top=( topPosition ) +'px';


	if( imgSrc != null ){
		loadTempMaps( layerName +'Map' , latitude , longitude , imgSrc , infoWindowCaption );
	}

}
*/

function hide( layerName ){

	//var divTag = document.getElementById('transperant');
	//divTag.style.display = "none";
	
	if(  document.getElementById('iframetop') != null ){
		divTag = document.getElementById('iframetop');
		divTag.style.display = "none";
	}
	
	
	divTag = document.getElementById(layerName);
	divTag.style.display = "none";
}


function hideLayer( layerName ){
	var divTag = document.getElementById(layerName);
	divTag.style.display = "none";
}




function encodeInput(inputString){
	var encodedInputString=escape(inputString);

	encodedInputString=encodedInputString.replace("+", "%2B");
	encodedInputString=encodedInputString.replace("/", "%2F");

	return encodedInputString;
}


document.onmousemove = mouseMove;
var mousePos;
function mouseMove(ev){
	ev           = ev || window.event;
	mousePos = mouseCoords(ev);
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function imposeMaxLength(Object, MaxLen)
{
	if( Object.value.length > MaxLen ) {
		Object.value = Object.value.substring( 0 , MaxLen );
	}
  	//return (Object.value.length <= MaxLen);
}
function hitTrackerForProductLine( zip , lineOfBusiness ){
	var url = agentDirectoryListingUserSelect+'?Zip='+zip+'&ProductLine='+lineOfBusiness;
	hitGoogleTracker( url );
	hitServerForTracking( url );
	
}

function hitTrackerForAgentDetails( agentCode , lineOfBusiness ){
	var url = agentDetailsRequest+'?AgentCode='+agentCode+'&ProductLine='+lineOfBusiness;
	hitGoogleTracker( url );
	hitServerForTracking( url );
}

function hitServerForTracking( url ){
	trckHttp.open('get', url);
	trckHttp.send(null);
}

function hideErrors() {
	$("#errors").hide();
}

function startBoxy() {
		$(document).ready(function() {
	    	cookieResize('#sizer a', 'small');
	    	
			////$("#zipCodeAgent").focus();
			
	        // Initiate overlays
	        $('.boxy').boxy({modal: true});
	        
	        var randomImages = 4;
  			var rndNum = Math.ceil(Math.random() * randomImages);
  			$("#page_header").css( "background-image", "url(images/page_header_faa_bg0" + rndNum + ".jpg)" );
  			
  			randomImages = 6;
  			rndNum = Math.ceil(Math.random() * randomImages);
  			//$("img#left_image").attr( "src" , "images/promo2_agent0" + rndNum + ".png" );
  			$('#errors').show();
  			
			cookieResize('#sizer a', 'small');
		
	  		var containerZip = $('div.errors');
			// validate the form when it is submitted
				    var validator = $("#faa_finderForm").validate({
				    	submitHandler:function(){
				    		clickedOnSubmit();
						},
				    	onclick: true,
						errorContainer: $("#faa_finderForm .errors"),
						errorLabelContainer:$("ul", "#faa_finderForm .errors"),
				    	wrapper: 'li',  
				    	meta: 'validate'
				   });
				   
				   var zipValidator = $("#faa_refineForm").validate({
						submitHandler:function(){
							clickedOnSubmit();
						},
						invalidHandler: function() {
							hintAgain();
						},
						errorContainer: $("#faa_refineForm .errors"),
						errorLabelContainer:$("ul", "#faa_refineForm .errors"),
						wrapper: 'li',  
						meta: 'validate'
					});	   
	        
    		});
    		
    		$().ready(function(){	
	//Display header information
	if ($("#header-logout").length > 0 && $("#header-login").length > 0) {
		$("#header-logout").hide();
		$("#header-login").hide();
		if (!$.cookie('mercusername')) {
			$("#header-logout").show();		
			if ($("#homepage_login").length > 0) {
				$("#homepage_login").show();
			}
		} else {
			$("#header-login").show();
			$("#header-agent-name").append($.cookie('mercagentname'));
			$("#header-agent-phone").append($.cookie('mercagentphone'));
			$("#header-user-name").append($.cookie('mercusername'));
			if ($("#homepage_login").length > 0) {
				$("#homepage_login").hide();
			}
		}
	}
	
	//Sub Left Menu hilghted
	var bodyId = $("body").attr("id");
	if ($("#pm_"+bodyId).length > 0) {
		$("#pm_"+bodyId).attr("class","current");
	} 
	
	//Display Random Home Page background image and text
	if (document.getElementById("homepage_content") != null) {
		var n = Math.floor(Math.random()*4+1);

		switch(n)
		{
		case 1:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_001.jpg) 0 0 no-repeat");
			$("#homepage_text").append( '<bean:message key="agentlocator.al.agentlocator.peaceofmind1"/>' <br >'<bean:message key="agentlocator.al.agentlocator.peaceofmind2"/>');
		  break;
		case 2:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_007.jpg) 0 0 no-repeat");
			$("#homepage_text").append( '<bean:message key="agentlocator.al.agentlocator.everythingyouneed"/>');
		  break;
		case 3:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_008.jpg) 0 0 no-repeat");
			$("#homepage_text").append( '<bean:message key="agentlocator.al.agentlocator.familyrestesay1"/>' <br >  '<bean:message key="agentlocator.al.agentlocator.familyrestesay2"/>');
		  break;
		case 4:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_011.jpg) 0 0 no-repeat");
			$("#homepage_text").append( '<bean:message key="agentlocator.al.agentlocator.teendriversrate1"/>'<br >'<bean:message key="agentlocator.al.agentlocator.teendriversrate2"/>');
		  break;		
		default:
		  break;
		}	
	}
	//Display testimonials
	if ($("#promo_left").length > 0) {
		//Auto insurance quotes
		if ($("#promo_auto").length > 0) {
			
			$.ajax({
			  url: "quotes-auto.html",
			  cache: false,
			  success: function(html){
				$('#promo_auto').append(html);
				var n = $('div.quote').length;
				var random = Math.floor( Math.random()*n ); 
				$('div.quote').eq(random).css({'display':'block','visibility':'visible'}); 
			  }
			});	
		}
		//Home insurance quotes
		if ($("#promo_home").length > 0) {
			
			$.ajax({
			  url: "quotes-home.html",
			  cache: false,
			  success: function(html){
				$('#promo_home').append(html);
				var n = $('div.quote').length;
				var random = Math.floor( Math.random()*n ); 
				$('div.quote').eq(random).css({'display':'block','visibility':'visible'}); 
			  }
			});

			/*$('#promo_home').load('quotes-home.html',function(){ 
			      var $quotes = $(this).find('div.quote'); 
			      var n = $quotes.length; 
			      var random = Math.floor( Math.random()*n ); 
			      $quotes.hide().eq(random).fadeIn(); 
			}); */
		}
		//Generic quotes
		if ($("#promo_gen").length > 0) {
			
			$.ajax({
			  url: "quotes-gen.html",
			  cache: false,
			  success: function(html){
				$('#promo_gen').append(html);
				var n = $('div.quote').length;
				var random = Math.floor( Math.random()*n ); 
				$('div.quote').eq(random).css({'display':'block','visibility':'visible'}); 
			  }
			});

			/*$('#promo_gen').load('quotes-gen.html',function(){ 
			      var $quotes = $(this).find('div.quote'); 
			      var n = $quotes.length; 
			      var random = Math.floor( Math.random()*n ); 
			      //$quotes.hide().eq(random).show(); 
			});*/
		}		
	}	
	
	//Main Nav Menu Quote and Find Agent forms
	var menuGaq = $("#menu_quoteForm").validate({// Get a Quote menu item
		submitHandler: function(form) {	
			checkZip('',form.zipCode.value,GETAQUOTE,form);	
		},
		invalidHandler: function() {},
		errorContainer: $("#menu_quoteForm .errors"),
		errorLabelContainer: $("div", "#menu_quoteForm .errors"),
		meta: "validate"
	});		 

	var menuFaa = $("#menu_agentForm").validate({//Find and Agent menu item
		submitHandler: function(form) {
			///goToAgentLoc(form.zipCode.value);
			checkZip('',form.zipCode.value,MENUAGENT,form);	
		},
		invalidHandler: function() {
			hintAgain();
		},
		errorContainer: $("#menu_agentForm .errors"),
		errorLabelContainer: $("div", "#menu_agentForm .errors"),
		meta: "validate"
	});
});
    		

}
function makeVeriSignWin(serverName){
	var url = "https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn="+serverName+"&lang=en";
	var winattr = "height=440,width=540,toolbar=0,location=0,status=0,menuBar=0,scrollBars=1,resizable=no'";
	var veriSignwin = window.open (url,"VeriSignPopup",winattr).focus(); 	
}

function getWQAQLAgentURL(url,appName){
if(appName == 'BREA'){
aqlURL = host_web_quote +url;
}
else{
aqlURL = host_okc_web_quote +url;
}
location.href  = aqlURL; 
} 
