/*** version:			v.1.0.0 		***/
/*** last modified date:	2009-09-22    	***/

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

switch(hostname)
{
	case 'ewok11.int.mgc.com':
		host_agent_locator = 'http://brdvagnwas01:9083/agentlocator/';
		host_web_quote = 'http://brdvagnwas01:9082/WebQuote/';	
		host_payments = 'http://brdvagnwas01:9088/payments/';
		host_okc_web_quote = 'http://10.6.18.149:9080/';
		host_static = '/static/';
	  break;
	case 'corpweb-ltqa.mercuryinsurance.com':
		host_agent_locator = 'http://brdvagnwas01:9083/agentlocator/';
		host_web_quote = 'http://brdvagnwas01:9082/WebQuote/';		
		host_payments = 'http://brdvagnwas01:9088/payments/';
		host_okc_web_quote = 'https://dev.quote1.mercuryinsurance.com/';
		host_static = '/static/';
	  break;
	case 'stagewww.mercuryinsurance.com':
		host_agent_locator = 'http://brdvagnwas01:9083/agentlocator/';
		host_web_quote = 'http://brdvagnwas01:9082/WebQuote/';		
		host_payments = 'http://brdvagnwas01:9088/payments/';
		host_okc_web_quote = 'https://dev.quote1.mercuryinsurance.com/';
		host_static = '/static/';
	  break;
	case 'www.mercuryinsurance.com':
		host_agent_locator = 'http://agents.mercuryinsurance.com/agentlocator/';
		host_web_quote = 'https://quote2.mercuryinsurance.com/WebQuote/';
		host_payments = 'https://payment.mercuryinsurance.com/payments/';
		host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
		host_static = '/static/';	
	  break;		
	default:
		host_agent_locator = 'http://agents.mercuryinsurance.com/agentlocator/';
		host_web_quote = 'https://quote2.mercuryinsurance.com/WebQuote/';
		host_payments = 'https://payment.mercuryinsurance.com/payments/';
		host_okc_web_quote = 'https://quote1.mercuryinsurance.com/';
		host_static = '/static/';
	  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_012.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Low rates, local agents and<br />complete peace of mind.');
		  break;
		case 2:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_007.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Mercury provides everything you need in an insurance company.');
		  break;
		case 3:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_013.jpg) 0 0 no-repeat");
			$("#homepage_text").append('See why more than 3,000 drivers <br /> a day choose Mercury.');
		  break;
		case 4:
			$("#homepage_content").attr("style","background: url("+host_static+"images/homepage_lifestyle-bg_011.jpg) 0 0 no-repeat");
			$("#homepage_text").append('Our great rates for teen drivers <br /> will make you smile too!');
		  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,false,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);
		},
		invalidHandler: function() {},
		errorContainer: $("#menu_agentForm .errors"),
		errorLabelContainer: $("div", "#menu_agentForm .errors"),
		meta: "validate"
	});
	
});

//Quote and Find Agent forms

var zipBoxy;
function zipError() {
	$('.boxy').boxy({modal: true});
	//document.getElementById('displayZip').innerHTML="<p>We're sorry, but Mercury Insurance is not currently available in your State. If you meant to enter something else, <a href='#' onclick='closeBoxy();'>please try again</a>.</p><p>Mercury is constantly expanding into other states so we may be available in your area soon. We currently sell insurance in AZ, CA, FL, GA, IL, MI, NJ, NV, NY, OK, PA, TX, VA.</p>";
	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,retrieve,form){
	var zipcode = jQuery.trim(zip);
	var quoteid = jQuery.trim(qid);
		
	randomNum = new  Date().getTime() + Math.random();
	//service_url = host_web_quote+"quickEstimateServices.do?submitName=getStateValidity&rM" + randomNum;
	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>" + 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"){
				zipError();
			}
			else {
				var action;
				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;							
					}
				}
				submitForm(form,action);
			}			
		},
		error: function(xhr, desc, exceptionobj) {		 
			 zipError();
		  return false;
		}	
	  });
	return false;
}

//UTILITIES FUNCTIONS

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);
        });
    });
});