/*** version:			v.1.0.1 		***/
/*** last modified date:	2010-06-14  	***/

var host_agent_locator;
var host_web_quote;
var host_my_account;
var host_payments;
var host_okc_web_quote;
var hostname = window.location.hostname;

var host_static = '/static/';
var FINDAGENT = 'Agent';
var MENUAGENT = 'MenuAgent';
var GETAQUOTE = 'GetAQuote';
var RETRIEVEAQUOTE = 'RetrieveAQuote';

var stateCode="";
var notAvailableInStateCodeMessage = "Mercury Insurance is not currently available in";
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'};

switch(hostname)
{
	case 'ewok11.int.mgc.com':
					host_agent_locator = 'http://brdvagnwas01:9083/agentlocator/';
					host_web_quote = 'http://brdvagnwas01:9082/WebQuote/';
					host_consumer_portal = 'http://brdvagnwas01:9086/myaccount/';
					host_payments = 'http://brdvagnwas01:9084/payments/';
					host_okc_web_quote = 'https://dev.quote1.mercuryinsurance.com/';
					break;
	case 'corpweb-ltqa.mercuryinsurance.com':
					host_agent_locator = 'http://brqaagnwas03:9083/agentlocator/';
					host_web_quote = 'http://brqaagnwas03:9082/WebQuote/';
					host_consumer_portal = 'http://brqaagnwas03:9086/myaccount/';
					host_payments = 'http://brqaagnwas03:9084/payments/';
					host_okc_web_quote = 'https://qa.quote1.mercuryinsurance.com/';
					break;
	case 'quotestage.mercuryinsurance.com':
					host_agent_locator = 'http://stageagents.mercuryinsurance.com/agentlocator/';
					host_web_quote = 'https://quotestage.mercuryinsurance.com/WebQuote/';
					host_consumer_portal = 'https://quotestage.mercuryinsurance.com/myaccount/';
					host_payments = 'https://quotestage.mercuryinsurance.com/payments/';
					host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
					break;
	case 'stagewww.mercuryinsurance.com':
					host_agent_locator = 'http://stageagents.mercuryinsurance.com/agentlocator/';
					host_web_quote = 'https://quotestage.mercuryinsurance.com/WebQuote/';
					host_consumer_portal = 'https://quotestage.mercuryinsurance.com/myaccount/';
					host_payments = 'https://quotestage.mercuryinsurance.com/payments/';
					host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
					break;
	case 'www.mercuryinsurance.com':
					host_agent_locator = 'http://agents.mercuryinsurance.com/agentlocator/';
					host_web_quote = 'https://quote2.mercuryinsurance.com/WebQuote/';
					host_consumer_portal = 'http://brdvagnwas01:9086/myaccount/';
					host_payments = 'https://payment.mercuryinsurance.com/payments/';
					host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
					break;
	default:
					host_agent_locator = 'http://agents.mercuryinsurance.com/agentlocator/';
					host_web_quote = 'https://quote2.mercuryinsurance.com/WebQuote/';
					host_consumer_portal = 'http://brdvagnwas01:9086/myaccount/';
					host_payments = 'https://payment.mercuryinsurance.com/payments/';
					host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
					break;
}



$().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_017.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Our low rates and dedicated<br /> agents will make you smile too.');
		  break;
		case 2:			
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_018.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Mercury provides protection<br /> for the things that matter most.');
		  break;
		case 3:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_019.jpg) 0 0 no-repeat");
			$("#homepage_text").append('See why more than 3,000<br /> drivers a day choose Mercury.');
		  break;
		case 4:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_020.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Mercury provides coverage<br /> tailored to fit your needs.');
		  break;		
		default:
		  break;
		}	
	}
	
	//Display Superior Service
	if ($("#promo_left2").length > 0) {
		//Enjoy Superior Service
		if ($("#promo_service").length > 0) {
			
			$.ajax({
			  url: host_static+"html/superior-service.html",
			  cache: false,
			  success: function(html){
				//alert(html);
				$('#promo_service').append(html);
				var n = $('div.content').length;
				var random = Math.floor( Math.random()*n ); 
				$('div.content').eq(random).css({'display':'block','visibility':'visible'}); 
			  }
			});
		}	
	}
	
	//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"
	});
	
});

//Quote and Find Agent forms

var zipBoxy;
function zipErrorGeneric() {
	$('.boxy').boxy({modal: true});  
	
	if ( Boxy.isModalVisible() ) {
		zipBoxy.hide();
	}
		
	var zipBoxyHTML =  '<div id="zip_error_generic" class="hidden_overlay size1">' +
					   '  <div class="title_bar">' +
					   '    <p>ZIP CODE NOT FOUND</p>' +
					   '    <div class="close"></div>' +
					   '  </div>' +
					   '  <div class="text_container">' +
					   '    <p>We&#39;re sorry, but we are unable to locate your zip code. If you meant to enter something else, <a href="#"  onclick="closeBoxy();">please try again</a>.</p>' +
					   '    <p>If you would prefer to speak to an authorized Mercury agent, please call (800) 956-3728.</p>' +
					   '  </div>' +
					   '</div>';	

	zipBoxy = new Boxy(zipBoxyHTML,{modal: true});
}
function zipError(stateCode) {
	$('.boxy').boxy({modal: true});
	
	if ( Boxy.isModalVisible() ) {	
		zipBoxy.hide();
	}
	
	var stateDesc = fiftyStatesArr[stateCode];
	var zipCodeErrorMessage = notAvailableInStateCodeMessage + " " + jQuery.trim(stateDesc) + ".";
	$("#stateCodeId").html(zipCodeErrorMessage);
	zipBoxy = new Boxy('#zip_error',{modal: true});	
}
function closeBoxy(){
	zipBoxy.hide();
}

function goToAgentLoc(zipcode){
	window.location=host_agent_locator+"?zipCode="+jQuery.trim(zipcode);
	return false;
}

function checkZip(qid,zip,retrieveType,form){
	var zipcode = jQuery.trim(zip);
	var quoteid = jQuery.trim(qid);
		
	randomNum = new  Date().getTime() + Math.random();
	service_url = "/WebQuote/quickEstimateServices.do?submitName=getStateValidity&rM" + randomNum;	
	var error_msg = '';
	var xmlBody = "<?xml version='1.0' encoding='UTF-8'?>";
	xmlBody += "<cityState>";
	xmlBody += "<zipcode>" + jQuery.trim(zipcode) + "</zipcode>";
	xmlBody += "<source>WQ</source>";
	xmlBody += "</cityState>";
	
   $.ajax({
		type: "POST",
		url: service_url,
		data: xmlBody,
		contentType: "text/xml",
		dataType: "json",

		success: function(response) {		
			$.each(response.CityState,function(i,item){			   
				data = item.split(":");
			})
			if (data[1] != "VALID"){
				if(data[0] != 'null'){
				
					stateCode = jQuery.trim(data[0]);
					if (stateCode in fiftyStatesArr){
						zipError(stateCode);
					} else {
						zipErrorGeneric();
					}										
					
				} else{
					if (data[0] == 'null'){
						zipErrorGeneric();
					} else {
						showClientValidation();                         	         		
					}
				}
			} else {
				var action;				
				if (retrieveType == GETAQUOTE){
					if (data[0]=='CA') {							
						action = host_web_quote+"?zip="+zipcode+"&state="+data[0];
					} else if (data[0]=='AZ'||data[0]=='NV'||data[0]=='OK'||data[0]=='MI'||data[0]=='NJ'||data[0]=='PA') {							
						action = host_okc_web_quote+"startQuote.jsp?RedSt="+data[0]+"&Zip="+zipcode;
					}else {							
						action = host_web_quote+"startQuote.do?submitName=startQuote&RedSt="+data[0]+"&zip="+zipcode;
					}	
					submitForm(form,action);					
				} 
				if ((retrieveType == MENUAGENT) ||(retrieveType == FINDAGENT)){
					goToAgentLoc(zip);
				}
				/* if (!retrieve) {	
					if (data[0]=='CA') {							
						action = host_web_quote+"?zip="+zipcode+"&state="+data[0];
					} else if (data[0]=='AZ'||data[0]=='NV'||data[0]=='OK'||data[0]=='MI'||data[0]=='NJ'||data[0]=='PA') {							
						action = host_okc_web_quote+"startQuote.jsp?RedSt="+data[0]+"&Zip="+zipcode;
					}else {							
						action = host_web_quote+"startQuote.do?submitName=startQuote&RedSt="+data[0]+"&zip="+zipcode;
					}						
				} else {
					if (data[0]=='AZ'||data[0]=='NV'||data[0]=='OK'||data[0]=='MI'||data[0]=='NJ'||data[0]=='PA') {							
						action =  host_web_quote+"startQuote.do?submitName=findQuote&QuoteID=" + quoteid;
					} else {							
						action =  host_web_quote+"startQuote.do?submitName=findQuote&QuoteID=" + quoteid;							
					}
				}*/
				
			}			
		},
		error: function(xhr, desc, exceptionobj) {		 
			 zipErrorGeneric();
		  return false;
		}	
	  });
	return false;
}


function findQuote(form){
	//var frmfindQuote = document.forms.findQuoteForm;
	var fFormAction = "/WebQuote/startQuote.do";
	form.action = fFormAction + "?submitName=findQuote&QuoteID=" + form.quoteId.value;
	form.submit();
}
//UTILITIES FUNCTIONS
function showClientValidation(){

	var re5digit=/^\d{5}$/
		/**	
	menu_quoteForm
		menuQuoteFormZip
	
	menu_agentForm
		menuAgentZip
	
	gaq_home
		gaqHomeZip
	
	raq_home
		raqHomeZip
	gaq_small
		gaqSmallZip
	raq_small
		raqSmallZip

		*/
	if (re5digit.test(jQuery.trim( $(".menuQuoteFormZip").val() ))){
		//GET A QUOTE - menu_gaq-zip form
		$(".menuQuoteFormZip").val("");
		$("#menu_quoteForm").validate().element( ".menuQuoteFormZip" ); 
		$(".menuQuoteFormZip").focus();
	} else if (re5digit.test(jQuery.trim( $(".menuAgentZip").val() ))){
		//FIND AN AGENT  - menu_agentForm
		$(".menuAgentZip").val("");
		$("#menu_agentForm").validate().element( ".menuAgentZip" ); 
		$(".menuAgentZip").focus();
	} else if (re5digit.test(jQuery.trim( $(".gaqHomeZip").val() ))){
		//Full quote - blue_fq form
		$(".gaqHomeZip").val("");
		$("#gaq_home").validate().element( ".gaqHomeZip" );
		$(".gaqHomeZip").focus(); 
	} else if (re5digit.test(jQuery.trim( $(".raqHomeZip").val() ))){
		//Quick Esitmate - orange_gaq form
		$(".raqHomeZip").val("");
		$("#raq_home").validate().element( ".raqHomeZip" ); 
		$(".raqHomeZip").focus();
	} else if (re5digit.test( jQuery.trim( $(".momentsQuoteFormZip").val() ))){
		//moments - index.html
		$(".momentsQuoteFormZip").val("");
		$("#quoteForm").validate().element( ".momentsQuoteFormZip" ); 
		$(".momentsQuoteFormZip").focus();
	}else if (re5digit.test(jQuery.trim( $(".gaqSmallZip").val() ))){
		//insurance-products -get a quote
		$(".gaqSmallZip").val("");
		$("#gaq_small").validate().element( ".gaqSmallZip" ); 
		$(".gaqSmallZip").focus();
	}else if (re5digit.test( jQuery.trim( $(".raqSmallZip").val() ))){
		//insurance-products - retrieve quote
		$(".raqSmallZip").val("");
		$("#raq_small").validate().element( ".raqSmallZip" ); 
		$(".raqSmallZip").focus();
	} else if (re5digit.test( jQuery.trim($(".homeAgentFormZip").val() ))){
		//find agent - home
		$(".homeAgentFormZip").val("");
		$("#home_agentForm").validate().element(".homeAgentFormZip"); 
		$(".homeAgentFormZip").focus();
	}
}
function hintAgain(){
	$('input[title!=""]').each(function(){
		if ($('#' + this.id).val() == ""){
			$('#' + this.id).val($('#' + this.id).attr('title')).addClass('blur');
		}
	});
}

//Submit form
function submitForm(form,action) {
	
  form.action = action;
  form.submit();
}

// Create a namespace for our utilities
var UTIL = UTIL || {};
UTIL.popup = UTIL.popup || {};

/**
 * Open popup window
 * 
 * Opens a popup window using as little as a URL. An optional params object can 
 * be passed.
 * 
 * @param {Object} href
 * @param {Object} params
 * @return {WindowObjectReference}
 */
UTIL.popup.open = function (href, params)
{
    // Defaults (don't leave it to the browser)
    var defaultParams = {
        "width":       "800",   // Window width
        "height":      "600",   // Window height 
        "top":         "0",     // Y offset (in pixels) from top of screen
        "left":        "0",     // X offset (in pixels) from left side of screen
        "directories": "no",    // Show directories/Links bar?
        "location":    "no",    // Show location/address bar?
        "resizeable":  "yes",   // Make the window resizable?
        "menubar":     "no",    // Show the menu bar?
        "toolbar":     "no",    // Show the tool (Back button etc.) bar?
        "scrollbars":  "yes",   // Show scrollbars?
        "status":      "no"     // Show the status bar?
    };
    
    var windowName = params["windowName"] || "new_window";
    
    var i, useParams = "";
    
    // Override defaults with custom values while we construct the params string
    for (i in defaultParams)
    {
        useParams += (useParams === "") ? "" : ",";
        useParams += i + "=";
        useParams += params[i] || defaultParams[i];
    }
    
    return window.open(href, windowName, useParams);
};



$(function(){ // Run this code when the document's done loading

    // Apply this code to each link with class="popup"
    $("a.popup").each(function (i){
		
		// Add an onClick behavior to this link 
        $(this).click(function(event) {
            
			// Prevent the browser's default onClick handler
            event.preventDefault();
    
            // Grab parameters using jQuery's data() method
            var params = $(this).data("popup") || {};
        
            // Use the target attribute as the window name
            if ($(this).attr("target"))
            {
                params.windowName = $(this).attr("target");
            }
        
            // Pop up the window
            var windowObject = UTIL.popup.open(this.href, params);
			
            // Save the window object for other code to use
            $(this).data("windowObject", windowObject);
        });
    });
});

function toggleStateMenu(){
	$('.column').toggle();
}
