/*****CHANGE LOG*****

10/28/11 -- Changes to form submit to improve tracking
11/28/11 -- Prevent double submits
12/8/11 -- Prostv iframe cursor pre-pop suppressed
12/13/11 -- Send campaign value over to Privacy Policy
1/12/12 -- Focus on the first form field (non-specific)
1/17/12 -- Universal pixel added 
1/24/12 -- Universal pixel removed (put into CMS include)
********************/

landerUtil = {		
	config: {			
		"theme" : ""
		,"postquoteredirect" : false		
		,"postQuoteOffer" : ""
		,"placement" : "leavebehind"						
		,"qwFormLnk" : "/forms/"
		,"quoteType" :""		
		,"offer" : "brokersweb"	
		,"errorDisplay" : "block"
		,"randomnumber" : -1
		,"userFirstName" : ""
		,"userLastName" : ""
		,"userEmail" : ""
		,"userAddress" : ""
		,"userCity" : ""
		,"userState" : ""
		,"userZip" : ""
		,"userPhone" : ""		
		,"leaveBehindTest" : false
		,"leavebehind" : false		
		,"vendor" : ""
		,"campaign" : ""
		,"key" : ""		
		,"wizsid" : ""
		,"offerType" : ""
		,"isLoyalty" : false 
		,"grayboxType" : "none"
		,"splitTest" : -1 
		,"costType" : ""
		,"isIVR" : false
		,"ebureauScore" : -1
		,"autoTransfer" : false
		,"homeTransfer" : false
		,"lifeTransfer" : false //NOT RELIABLE FOR LOYALTY
		,"lifeTransferWarm" : false
		,"campaignType" : ""
		,"numJSErrors" : 0	
		,"valid" : false	
		,"fid" : ""
	},
	init: function (options, flags){		
		$.extend(true,landerUtil.config,options,flags);			
		onerror = landerUtil.handleErr;
		//FIX CASE ISSUES
		landerUtil.config.vendor = landerUtil.config.vendor.toLowerCase();
		landerUtil.config.campaign = landerUtil.config.campaign.toLowerCase();
		landerUtil.config.key = landerUtil.config.key.toLowerCase();	
		landerUtil.config.offerType = landerUtil.config.offerType.toLowerCase();		
		landerUtil.config.grayboxType = landerUtil.config.grayboxType.toLowerCase();	
		landerUtil.config.costType = landerUtil.config.costType.toLowerCase();		
		landerUtil.config.campaignType = landerUtil.config.campaignType.toLowerCase();
						
		//DATA PASSING
		landerUtil.config.userFirstName = landerUtil.gup('firstname');
		landerUtil.config.userLastName = landerUtil.gup('lastname');
		landerUtil.config.userEmail = landerUtil.gup('email');
		landerUtil.config.userAddress = landerUtil.gup('address');
		landerUtil.config.userCity = landerUtil.gup('city');
		landerUtil.config.userState = landerUtil.gup('state');
		landerUtil.config.userZip = landerUtil.gup('zip');		
		landerUtil.config.userPhone = landerUtil.gup('phone');		
		landerUtil.config.randomnumber = Math.floor(Math.random()*100);
		if (landerUtil.config.userZip != ""){
			if (landerUtil.isValidZip(landerUtil.config.userZip, true) == true){		
				$('#contact-zip_code').attr('value',landerUtil.config.userZip);
			}			
		}
		if (landerUtil.config.userEmail != ""){
			if (landerUtil.validateEmail(landerUtil.config.userEmail) == true){		
				$('#email').attr('value',landerUtil.config.userEmail);
			}			
		}
		//For SEO, untracked, and testing purposes 
		if (landerUtil.config.quoteType == ''){
			landerUtil.config.quoteType = 'auto';
		}	
		landerUtil.grayboxCheck();	
		landerUtil.enableForm();
		//100% MT PUSH (ALMOST)
		if (landerUtil.config.quoteType == 'life' || landerUtil.config.quoteType == 'home' || landerUtil.config.vendor == 'ark'){//Exception list 			
			landerUtil.config.fid = 'multi_wrangler';
		}		
		if ($.inArray(landerUtil.config.theme, ['default','boca','wl','fr_tc2','pch','qb','cozi','grn','hy','qp','qs','rq','tc2','tq','typo','bk','blue','eauto','fr_app','job_2','osfa','pk','tc1','ugc']) >= 0){ //Remove themes that are not supported by Motown, use new defaults
			landerUtil.config.theme = '';
		}						
		//END 100% MT PUSH
		
		//HACK FOR PRIVACY/TERMS LINKS, THANK YOU BK+IC+FB
		$('a[href*="privacy"]').each(function(){
			if (landerUtil.config.campaign != ""){	
				var link = $(this).attr("href");
				$(this).attr("href", link + '&c=' + landerUtil.config.campaign);
			}
		});
		
		if (landerUtil.config.campaign != 'c12456'){ //prostv iframe
			$('input:visible:enabled:first').focus();				
		}
	},
	//Grab URL Parameters -- Not Case Sensitive 
	gup: function( name ){
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		name = name.replace(/\s/g,"%20");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp(regexS, "i");
		var results = regex.exec( window.location.href );
		if( results == null )
		return "";
		else
		return results[1];
	},			
	//Checks for graybox
	grayboxCheck: function(){			
		if (landerUtil.config.grayboxType == "full" || landerUtil.config.grayboxType == "currency" || landerUtil.config.grayboxType == "content"){
			landerUtil.fireGraybox( landerUtil.config.grayboxType );
		}			
	},
	fireGraybox: function( type ){
		$( "#confirmPop" ).modal({		
			close: false
			,overlayCss: {backgroundColor:"#000"}
			,opacity:50
		});
		$('#optin').attr('checked',false);
		if (type == "content"){
			$('#confirmPop .small_box').show();
			$('#confirmPop .content').show();
			$('#confirmPop .full_box').hide();
		}
		else if (type == "currency"){
			$('#confirmPop .small_box').show();
			$('#confirmPop .currency').show();
			$('#confirmPop .full_box').hide();
		}
	},
	showSubmit: function(isChecked) { //graybox button behavior
		if (isChecked){
			$("#submit").show();
			$("#fakeButton").hide();
			$("#prompt").hide();
		}
			else {
			$("#fakeButton").show();
			$("#submit").hide();
		}
	},
	showPrompt: function(){ //graybox button behavior
		$("#prompt").show();
	},
	fireError: function(erred){
		$('#general_error').css('display',landerUtil.config.errorDisplay);						
		$(erred).parents('li').addClass('clearfix error');						
		landerUtil.config.valid = false;
	},
	clearError: function(erred){
		$(erred).parents('li').removeClass('error');
	},
	quickCheck: function() {					
		$('input[type=submit]').attr('disabled','disabled'); //Prevent double-submits
		// VALIDATE INPUTS		
		var inputs = $('input[type=text]').not('.optional_field');
		landerUtil.config.valid = true;
		inputs.each(function() {        
			if ($(this).val().length === 0 ){
				landerUtil.fireError(this);
			}
			else if (($(this).hasClass('zip_code') === true) || ($(this).is('#contact-zip_code'))){
				landerUtil.config.userZip = $(this).val();
				if(landerUtil.isValidZip(landerUtil.config.userZip, true) === false){
					landerUtil.fireError(this);
				}
				else {
					landerUtil.clearError(this);			
				}
			}
			else if ($(this).hasClass('email') === true){
				landerUtil.config.userEmail = $(this).val();
				if(landerUtil.validateEmail(landerUtil.config.userEmail) === false){
					landerUtil.fireError(this);
				}
				else {
					landerUtil.clearError(this);			
				}
			}
			else {
				landerUtil.clearError(this);			
			}		
		});					
		if (landerUtil.config.valid){
			if (landerUtil.config.leavebehind == true){
				landerUtil.determineOffer();			
				$('form#Entry').attr('target','_blank');		
				var delay = setTimeout("landerUtil.fireLeaveBehind( landerUtil.config.userZip )", 500);
			}						
			//landerUtil.postQuoteInterval( landerUtil.config.userZip );			
			params = {
				theme: landerUtil.config.theme
				,firstname: landerUtil.config.userFirstName
				,lastname: landerUtil.config.userLastName
				,email: landerUtil.config.userEmail
				,address: landerUtil.config.userAddress				 
				,city: landerUtil.config.userCity 
				,state: landerUtil.config.userState				
				,phone: landerUtil.config.userPhone
				,fid: landerUtil.config.fid				
			};	
			for (key in params) {
				if (params[key] != ""){ //don't pass stuff that is null					
					$('<input>').attr({
						type: 'hidden'
						,name: key
						,value: params[key]
					}).appendTo('form');
				}
			}						
			return true;			
		}
		else {			
			landerUtil.generalFailure();
			landerUtil.enableForm();
			return false;
		}		
	},	
	generalFailure: function(){
		$('#general_error').css('display',landerUtil.config.errorDisplay);
	},
	enableForm: function(){
		$('input[type=submit]').removeAttr('disabled');
	},
	validateEmail: function(s) {
	  rex=true;
	  if (window.RegExp) {
		st="a";ex=new RegExp(st);
		if (st.match(ex)) {
		  r1=new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
		  r2=new RegExp("^([a-zA-Z0-9]|\\.|\\-|\\_)+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
		  b=(!r1.test(s)&&r2.test(s));
		}
		else rex=false;
	  }
	  else rex=false;
	  if(!rex) b=(s.indexOf("@")>0 && s.indexOf(".")>0 && s!="" && s!="enter e-mail");
	  return (b);
	},
	isValidZip: function(zipc, dbvalid) {
		isValid = false;
		var validStates = ['AL','AK','AZ','AR','CA','CO','CT','DC','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
		zipNumeric = parseFloat(zipc);
		if (zipc == "" || zipc.length != 5 || zipNumeric > 99951 || zipNumeric < 401){
			return false;
		}
		else if (dbvalid == false){
			return true;
		}
		//synchronous web svc validation
		if (dbvalid) {
			var url = 'http://' + window.location.hostname + '/act_get_json.cfm';
			var data = {
				"field"		:	"GEO"
				,"ZIP_CODE"	:	zipc
			};
			$.ajax({
				url: url,
				dataType: 'json',
				data: data,
				async: false,
				success: function(dta){
					if (dta.zip != '' && ($.inArray(dta.state, validStates) > -1)){ 
						isValid = true;						
						landerUtil.config.userCity = dta.city;											
						landerUtil.config.userState = dta.state;						
					}
				}
			});
		}			
		if(isValid){
			return true;
		}
		else {
			return false;
		}		
	},	
	determineOffer: function(){
		//AUTO AND HOME RULES
		var bwStates = ['AK','AZ','AR','CA','ID','IL','IN','KS','ME','MD','MA','MS','NE','NV','NH','NY','NC','ND','OH','OK','PA','RI','UT','VT','WA'];
		var shStates = ['AL','CO','CT','DE','FL','GA','HI','IA','KY','LA','MI','MN','MO','MT','NJ','NM','OR','SC','SD','TN','TX','VA','WA','WV','WI','WY'];
		if (landerUtil.config.quoteType == 'auto' || landerUtil.config.quoteType == 'home'){
			landerUtil.config.offerType = 'auto';
			if (landerUtil.config.isLoyalty == false){				
				/*BW OFF 5.25.11
				if (landerUtil.config.randomnumber > 9) {
					if ($.inArray(landerUtil.config.userState, shStates) >= 0) {
						landerUtil.config.offer = 'surehits';
					}
					else {
						landerUtil.config.offer = 'brokersweb';
					}
				}
				else { //SEND 10% TO THE 'WRONG' OFFER TO KEEP TABS
					if ($.inArray(landerUtil.config.userState, shStates) >= 0) {
						landerUtil.config.offer = 'brokersweb';
					}
					else {
						landerUtil.config.offer = 'surehits';
					}
				} 
				*/
				landerUtil.config.offer = 'surehits';
			}
			else if (landerUtil.config.randomnumber <= 2){
				//up from 2
				landerUtil.config.offer = 'admedia';
			}
			else {
				//landerUtil.config.offer = 'brokersweb'; PAUSED 9.30.11
				landerUtil.config.offer = 'admedia';	
			}
		}
		//LIFE RULES
		if (landerUtil.config.quoteType == 'life'){						
			if (landerUtil.config.isLoyalty == false && landerUtil.config.campaign != 'c12445'){
				landerUtil.config.offer = 'surehits';
				landerUtil.config.offerType = 'life';
			}
			else {
				landerUtil.config.offer = 'brokersweb';
				landerUtil.config.offerType = 'auto';
			}
		}	
		//OVERRIDES	
		//All Brokers for PCH
		if (landerUtil.config.campaign == "c12407" || landerUtil.config.campaign == "c12583" || landerUtil.config.campaign == "c12603"){
			landerUtil.config.offer = "brokersweb";			
		}
		/* DO NOT WANT?
		if (landerUtil.config.quoteType == 'home'){	
			landerUtil.config.offer = 'surehits';
			landerUtil.config.offerType = 'home';			
		}
		*/
	},	
	nav2listings: function( zipcode ){
		host = window.location.hostname;
		if (host != 'dev.qwcorp.local'){
			host = 'quote' + 'wizard.com';
		}
		if (landerUtil.config.isLoyalty == false){
			//Wbug test 7.5.11
			if (landerUtil.config.campaign ==  'c12775'){
				window.location = 'http://' + host + '/insurance-options-w&zip=' + zipcode + '&wizsid=' + landerUtil.config.wizsid;
			}
			if (landerUtil.config.quoteType == 'life'){ //TEST CAMPAIGN
				window.location = 'http://' + host + '/life-insurance-options&zip=' + zipcode + '&wizsid=' + landerUtil.config.wizsid;
			}
			
			else {
				window.location = 'http://' + host + '/insurance-options&zip=' + zipcode + '&wizsid=' + landerUtil.config.wizsid;
			}
		}
		else if (landerUtil.config.isLoyalty == true){
			window.location = 'http://' + host + '/insurance-options-l&zip=' + zipcode + '&wizsid=' + landerUtil.config.wizsid;
		}
	},	
	fireLeaveBehind: function( zipcode ){			
		if (landerUtil.config.leaveBehindTest == true){
			nav2listings( zipcode );
		}
		else {
			$('div').remove();
			$('link').remove();
			$('body').css("background-color","#F5F5F5");
			$spinner = '<div id="loading" class="clearfix"><img src="/creative/common/lb/images/loading_01.gif" height="24" width="24" alt="" /><span>Loading results</span></div>'; 		
			$('<link href="/creative/common/ow/styles/styles_02.css" type=text/css rel=stylesheet>').appendTo('head');		
			if (landerUtil.config.vendor == ''){ //SEO OR HOMEPAGE CASE
				$header = '<div id="lb_header"><h1>For Instant Online Quotes<br>Click on the Providers Below</h1></div>';
			}
			else if (landerUtil.config.isLoyalty == true && landerUtil.config.quoteType != 'auto' && landerUtil.config.offerType == 'auto'){
				$header = '<div id="lb_header"><p id="preheader">- Advertisement -</p><h1>Save up to 40% with Online Auto Insurance Quotes</h1><p id="caveat"><strong>Note:</strong> You will not receive any rewards from these offers.</p></div>';	
			}
			else if (landerUtil.config.isLoyalty == true && landerUtil.config.offerType == 'auto'){
				$header = '<div id="lb_header"><p id="preheader">- Advertisement -</p><h1>Save More With Additional Online Quotes</h1><p id="caveat"><strong>Note:</strong> You will not receive any rewards from these offers.</p></div>';	
			}
			else if (landerUtil.config.quoteType != 'auto' && landerUtil.config.offerType == 'auto'){
				$header = '<div id="lb_header"><h1>Save up to 40% on Auto Insurance<br>With Instant Online Quotes</h1></div>';
			}
			else {
				$header = '<div id="lb_header"><h1>For Instant Online Quotes<br>Click on the Providers Below</h1></div>';				
			}	
			if (landerUtil.config.offer == 'pruco'){
				landerUtil.getPruco();
			}
			else {
				//SH or Brokers
				$('<div id="lb_container">' + $header + '<div id="offerContainer">' + $spinner + '</div></div>').prependTo(document.body);						
				landerUtil.getOffer( zipcode );
			}
		}
	},	
	getOffer: function(zip){
		var $ajaxLoader 	=	$("#ajaxLoader");
		var url		=	"/lander/api/";	//URL to the lander API
		var data		=	{ 
			'placement'		: 	landerUtil.config.placement //Required. Sets placement to track properly.
			,'sid'				:	landerUtil.config.wizsid			//Required. Session ID
			,'bestoffer'		:	landerUtil.config.offer		//Required. Offer to display.
			,'zip'				:	zip			//Required. A valid 5-digit zipcode
			,'openaction'	:	landerUtil.config.offerType			//Required. auto, home, or life.  This will control what listings are shown.			
		};	
		$.getJSON(url,data,function(json) {
			var $offerContainer = $("#offerContainer");			
			if (json.STATUS == "SUCCESS") {
				$ajaxLoader.hide();				
				//Set offers
				$offerContainer.html(json.OFFERS);				
				//Remove the standard offer header
				$(".offer_header").remove(); 				
				//Display offers
				$offerContainer.show();
				if (typeof(json.OFFERURL) != "undefined") {
					$('<div id="offerUrl">Offer URL: ' + json.OFFERURL + '</div>').appendTo('#lb_container');					
				}	
			}
			else{
				//Handle errors here.  json.STATUS will be "ERROR"
			}
		});
		$('#offerContainer').ajaxComplete(function() {		
			landerUtil.offerLoaded();	
		});		
	},	
	removeSpinner: function(){
		$('#loading').hide();
	},
	//do this once API has returned offer
	offerLoaded: function(){
		$('#offer_container').css('left','0');		
		 //Adds spans to hold numbering then Adds numbers to the span with CSS class
		$(".ow_item")
		.append('<span class="count"></span>')
		.mouseover(function(){
			   $(this).addClass("ow_item_hover");
		})
		.mouseout(function(){
			   $(this).removeClass("ow_item_hover");
		})
		.each(function(index){
			   //Adds class to highlight the first element
			   if (index==0) $(this).addClass('first');		
			   numbers = ['one','two','three','four','five','six','seven','eight','nine','ten'];
			   addThis = numbers[index];
			   $(this).find('span.count')
			   .addClass(addThis);
		});
		landerUtil.removeSpinner();
	},
	getCookie: function (c_name) {
		if (document.cookie.length > 0) {
			c_start = document.cookie.indexOf(c_name + "=");
			if (c_start != -1) {
				c_start = c_start + c_name.length + 1;
				c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1) c_end = document.cookie.length;
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
		return "";
	},
	/*
	postQuoteInterval: function( zipcode ){
		if (landerUtil.config.postquoteredirect == true){
			lbi = self.setInterval("landerUtil.postQuoteRedirect( zipcode )", 1000);
		}
	},
	postQuoteRedirect: function( zipcode ) {		
		var formCompleted = landerUtil.getCookie("FORMCOMPLETED");
		if (formCompleted == "true" || formCompleted == 2 || formCompleted == 3) {
			lbi = window.clearInterval(lbi);
			if (landerUtil.config.postquoteredirect == true){
				//POSTQUOTE OFFER
			}			
		}		
	},
	*/
	handleErr: function(msg,currentUrl,line) {
		try {
			//Only track up to 10 errors per user
			if (landerUtil.config.numJSErrors >= 10) {
				return false;
			}
			
			var url = "http://" + document.domain +"/auto_home_combo_js/act_json.cfm?";
			var urlParams = {
				'act'			:	"TRACK_JSERROR"
				,'sid'			:	((typeof(landerUtil.config.wizsid) != "undefined") ? landerUtil.config.wizsid : "")
				,'msg'			:	escape(msg)
				,'line'			:	escape(line)
				,'file'			:	escape(currentUrl)
				,'currentUrl'	:	escape(document.location.href)
				,'navAgent'		:	escape(navigator.userAgent)
				,'navName'		:	escape(navigator.appName)
			};

			$.each(urlParams,function(i,val) {
				url += "&" + i + "=" + val;
			});
		
			//Replace all single and double quotes with nothing so the pixel doesn't break
			url = url.replace(/'/g,"");
			url = url.replace(/"/g,"");
			
			//If already fired a JS error pixel, kill it
			$('#jsErrorPixel').remove();

			//Fire pixel
			$('body').append("<img id='jsErrorPixel' src='"+url+"' width='1' height='1' border='0' />");
			
			landerUtil.config.numJSErrors++;
		}catch(e){
			try{
				var createCookie = function(name,value,domain,secure) {var date = new Date();date.setTime(date.getTime()+(100*24*60*60*1000));var expires = "; expires="+date.toGMTString();document.cookie = name+"="+escape(value)+expires+"; path=/";}
				createCookie("JS_ERROR","||m" + msg + "||l" + line + "||b" + navigator.appName + "||v" + navigator.userAgent + "||u" + currentUrl);
			}catch(e){
				//teh suxxorz!
			}
		}		
		return true;
	}
};
