/**
* Name: Core 2.1
* Version: 2.1.2
* Modified: 02/01/2012
* Author(s): Chris L, Derek P, Ryan G
* URI: http://www.astonishresults.com
* 
* Description: Controls many aspects of the VIO.
  2.1.2 - Added CRM_Leads_Debug to track form page URLs & User Agents. Cleaned code.
**/

var jsPPC="",jsKW="",jsEID="",swfArea="",swfObjectID='',slidedownZ="",cdn_url="http://cdn.astonishlive.com/",cur_url=window.location,protocol=cur_url.protocol;

/* console.log hander */
if (window.console){
      if (!window.console.write){
      console.write = function(msg) {
        try{console.log(msg);}catch(err){}
      };
    }
  }else {
    console = {};
    console.write = function(){};
  }        
/* === Helpers === */
if(protocol=="https:"){cdn_url="/";}
if(typeof window.sMenuName==="undefined"){var sMenuName="Home";}
if(typeof window.analyticsNum==="undefined"){var analyticsNum="UA-12698842-1";}
$.queryVal=function(name){
  var results=new RegExp('[\\?&]'+name+'=([^&#]*)').exec(window.location.href);
  if(!results){return"";}
  return results[1]||"";
};
function fnSetCookie(sName,sVal,nDays){
  var dtCur=new Date();
  dtCur.setTime(dtCur.getTime()+(nDays*24*60*60*1000));
  document.cookie=sName+"="+escape(sVal)+";expires="+dtCur.toGMTString()+";path=/";
}
function fnGetCookie(sVal){
  if(document.cookie.length>0){
    nValStart=document.cookie.indexOf(sVal+"=");
    if(nValStart!==-1){
      nValStart=nValStart+sVal.length+1;
      nValEnd=document.cookie.indexOf(";",nValStart);
      if(nValEnd===-1){
        nValEnd=document.cookie.length;
      }
      return unescape(document.cookie.substring(nValStart,nValEnd));
    }
  }
  return"";
}
function trim(stringToTrim){
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}
/* SWF Methods */
function fnCacheBust(){
  var cacheBust="";
  if($(".ie").length){
    cacheBust="?rnd="+Math.floor(Math.random()*99999+1);
  }
  return cacheBust;
}
function fnSwfVer(){
  try{
    try{
      var axo=new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
      try{
        axo.AllowScriptAccess='always';
      }catch(a){
        return '6,0,0';
      }
    }
    catch(b){}
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  }
  catch(c){
    try{
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
        return (navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
      }
    }
    catch(d){}
  }
  return '0,0,0';
}
function fnSwfReady(){
  var swfVer=fnSwfVer().split(',').shift();
  if(swfVer>9){
    return true;
  }else{
    return false;
  }
}
function fnSwfUnload(swfID){
  if($(".ie").length){
    $("#"+swfID).removeAttr("data").html("");
    $("#"+swfID).parent().flashembed({src: cdn_url+"core_Silent.swf?rnd="+fnCacheBust(),width:'10',height:'10',wmode:'transparent',id:swfID,allowScriptAccess:'always'});
  }else{
    $("#"+swfID).parent().html("");
  }
}
function fnReturnSwfName(swfName) {
  var isIE=navigator.appName.indexOf("Microsoft")!==-1;return (isIE) ? window[swfName] : document[swfName];
}
/* Support for Spanish, French, Portuguese, and of course English */
function fnPageLang(){
  if(location.href.indexOf("spanol")!==-1){
    return "esp";
  }else if(location.href.indexOf("rancais")!==-1){
    return "fr";
  }else if(location.href.indexOf("ortuguese")!==-1){
    return "pt";
  }else{
    return "en";
  }
}
$.fn.calcSubWidth=function(){
  rowWidth=0;
  $(this).find(".sub ul").not(".sub ul li ul").each(function () {
    rowWidth += $(this).width();
  });
};
/* Outbound link tracking */
function fnRecOutbound(link,category,action){
  try{
    var pageTracker=_gat._getTracker(analyticsNum);
    pageTracker._trackEvent(category,action);
    setTimeout(window.open(link),100);
  }catch(err){}
}
/* SmartResize w/ Debouncing(function from John Hann - http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/)*/
(function($,sr){
  var debounce = function (func,threshold,execAsap){
    var timeout;
    return function debounced (){
      var obj = this, args = arguments;
      function delayed (){
        if (!execAsap){
          func.apply(obj, args);
        }
        timeout = null;
      }
      if (timeout){
        clearTimeout(timeout);
      }else if (execAsap){
        func.apply(obj, args);
      }
      timeout=setTimeout(delayed,threshold||100);
    };
  };
  jQuery.fn[sr] = function(fn){
    return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
  };
})(jQuery,'smartresize');

/* Clear media object data */
function mediaClear(empty_element){
  var content_store=$(empty_element).html(),empty_file=cdn_url+'core_Silent.swf';
  $(empty_element).find('iframe').attr('src',empty_file);
  $(empty_element).find('param[name=movie]').attr('value',empty_file);
  $(empty_element).find('object').attr('data',empty_file);
  $(empty_element).find('video').attr('src',empty_file);
  $(empty_element).find('audio').attr('src',empty_file);
  $(empty_element).find('source').attr('src',empty_file);
  setTimeout(function(){
    $(empty_element).remove('iframe').remove('object').remove('video').remove('audio').html("");
    try{console.log(empty_element+' : Modal content clear complete');}catch(err){}
  },50);
  setTimeout(function(){
    $(empty_element).html(content_store);
    try{console.log(empty_element+' : Modal content reload complete');}catch(err){}
  },100);
}
/*=== Lead Source ===*/
function fnPPCSet(nDays){
  fnSetCookie("ldsrc","ppc",nDays);
  fnSetCookie("ppc",jsPPC,nDays);
  fnSetCookie("kw",jsKW,nDays);
  $('form').append('<input type="hidden" name="CRM_Leads_Notes" value="PPC:'+jsPPC+'" /><input type="hidden" name="CRM_Leads_Notes" value="KW:'+jsKW+'" /><input type="hidden" name="Search_Engine" value="'+jsPPC+'" /><input type="hidden" name="Search_Keyword" value="'+jsKW+'" />');
  if(typeof window.campaignType==="undefined"){
   /* Adds Standard PPC Number(s) & Form Types */
    var phone="877-254-5756";
   if(phone!==""){
    $('#phoneNumber,.asiPhoneNumber').text(phone);
    $('form').append('<input type="hidden" name="CRM_Lead_ContactType" value="189" />');
    var p=0;
    for(p=2;p>1;p++){
     if(typeof window["nPPCNum"+p]==="undefined"){
      p=0;
      break;
     }else{
      $('#phoneNumber'+p+',.asiPhoneNumber'+p).html(window["nPPCNum"+p]);
     }
    }
   }
  /* Changes contact type & phone for specific campaigns */
  }else if(window.campaignType==="progressive"){
   /* Progressive Campaign */
   $('#phoneNumber,.asiPhoneNumber').text("");
   $('form input[name="CRM_Lead_ContactType"]').attr('value','472');
   $('form input[name="CrossLead_Status_Name"]').attr('value','Progressive SEM PPC');
  }
}
function fnEIDSet(nDays){
  fnSetCookie("ldsrc","eid",nDays);
  fnSetCookie("eid",jsEID,nDays);
  $('form').append('<input type="hidden" name="CRM_Leads_Notes" value="E-Mail ID:'+jsEID+'" /><input type="hidden" name="Email_Id" value="'+jsEID+'" />');
}
function fnLeadSrcCheck() {
  jsPPC=$.queryVal("ppc");
  jsKW=$.queryVal("kw");
  jsEID=$.queryVal("eid");
  /* 1. Thru queries */
  if (jsPPC!=="") {
    fnPPCSet(45);
  }else if (jsEID!=="") {
    fnEIDSet(5);
  }else{
    /* 2. Then Cookies */
    jsLdSrc=fnGetCookie('ldsrc');
    if (jsLdSrc==="ppc") {
      jsPPC=fnGetCookie('ppc');
      jsKW=fnGetCookie('kw');
      fnPPCSet(45);
    }else if(jsLdSrc==="eid"){
      jsEID=fnGetCookie('eid');
      fnEIDSet(5);
    }
  }
}
/* === MP4 Support === */
function fnVidLoadFail(target){$(target).css("background","url("+cdn_url+"pathError.jpg) no-repeat");}
function fnVideoEmbed(videoTarget,mediaURL){
    /* SWF AutoPause Support : <script>swfAutoPlay='f';</script> in DOM OR ap=true in query */
    html5AutoPlay="";
    swfArea=videoTarget;
    if(typeof window.swfAutoPlay==="f"||$.queryVal('ap')==="true"){swfPause="true";}else{swfPause="false";hmtl5AutoPlay="autoplay='autoplay'";}
    /* Activating videos */
    $(videoTarget).css("background","url("+cdn_url+"tmb_"+mediaURL+".jpg) no-repeat");
    if(fnSwfReady()){
        swfObjectID='swfMP4';
        $(videoTarget).flashembed({src: cdn_url+"core_MP4Handler.swf",width:'480',height:'176',id:swfObjectID,allowScriptAccess:'always',wmode:'transparent'},{mediaPath:cdn_url+mediaURL,posterImg:cdn_url+mediaURL,autoPause:swfPause,domElem:videoTarget,cache:fnCacheBust()});
    }else if ($.browser.webkit && navigator.platform.indexOf("inux arm")===-1) {
        $(videoTarget).html("<video src='"+cdn_url+mediaURL+".mp4' class='video-js' height='176' poster='"+cdn_url+"tmb_"+mediaURL+".jpg' width='480' controls "+hmtl5AutoPlay+"></video>");
    }else{
        $(videoTarget).html("<img  src='"+cdn_url+"videoError.jpg' width='480' height='176' alt='Unsupported Device' title='No video playback capabilities' />");
    }
    /* Adding company logo to videos */
    if(typeof window.videoLogoCSS==="undefined"){videoLogoCSS="top:5px;right:5px;width:80px;opacity:.6;";}
    if(!!window.custom_brand===false){custom_brand='logo.png';}
    $(videoTarget).prepend("<div id='branding' style='width:480px;position:absolute'><img style='position:absolute;-ms-interpolation-mode:bicubic;"+videoLogoCSS+"' src='"+custom_brand+"'></div>");
}
function fnVidJsLoad() {
  $(".error").addClass("oldError").removeClass("error");
  /* Purging inline, rocking dynamic DOM */
  $("#vidModal").remove();
  $("body").append('<div  class="hide"  id="vidModal"><div  id="actionStorage"></div><a  class="actionClose  modClose  modBtnStyle"><img  src="viaClose.gif"  alt="Close the  Window"></a><div  class="modVidBkg"><div  id="videoLocation"></div></div></div>');
  /* Begin Lightbox, storing close actions on #actionStorage for fast closing (IE issue?) */
  $("#vidModal").lightbox_me({
    centered:true,
    closeSelector:"#actionStorage",
    closeClick:false,
    closeEsc:false,
    destroyonclose:true,
    onLoad: function () {
        fnVideoEmbed("#videoLocation",mediaURL);
        $("#vidModal").removeClass('hide');
        $(".lb_overlay").addClass("actionClose");
        $(".actionClose").click(function(){
            $(".actionClose").removeClass("actionClose");
            if(fnSwfReady()){
                fnSwfUnload(swfObjectID);
            }else{
                $("video").remove();
            }
            $("#actionStorage").triggerHandler("click");
        });
    },
    onClose:function (){
        $(".oldError").addClass("error").removeClass("oldError");
    }});
}
/* === VIA === */
function fnVIAQuery(){if($.queryVal('via')==="f"){fnSetCookie("siteVIAOn","f",365);return true;}if(typeof window.viaOn!=="undefined"&&!window.viaOn){fnSetCookie("siteVIAOn","f",365);window.viaOn=true;return true;}else{return false;}}
function fnVIASiteCheck(){if(fnGetCookie('siteVIAOn')==='f'){fnSetCookie("siteVIAOn","f",365);return true;}else{return false;}}
function fnVIAPageCheck(){if(fnGetCookie(sPage+'VIAOn')==='f'){fnSetCookie(sPage+"VIAOn","f",45);return true;}else{return false;}}
function fnVIAClosePage(){
    $("#revealForm, #revealPhone, #revealCombine, #revealHome, #revealAuto").hide();
    $(".error").addClass("viaError").removeClass("error");
    $(".viaError").hide();
    fnSwfUnload(swfObjectID);
}
function fnVIALoad(sAction) {
    if (!$("#playVIA").length){
        $("body").append('<div  id="playVIA"><a  class="modBtnStyle"  id="openVIAPage">Activate Virtual Agent &nbsp;<img alt="" src="viaIcon.gif" /></a></div>');
        $("#openVIAPage").click(function(){fnVIAPlay();return false;});
    }
    if(sAction==="off"){fnSetCookie("siteVIAOn", "f", 365);}
    /* Check query, site, and page cookie. If all false then set page cookie & play vid. */
    if (!fnVIAQuery() && !fnVIASiteCheck() && !fnVIAPageCheck()) {
        fnSetCookie(sPage + "VIAOn", "f", 45);
        /* Create & Destroy DOM Elements */
        if(!$("#closeVIA").length){
            $("#modalVIA").prepend('<div  id="closeVIA"><div  id="actionViaStorage"></div><a  class="actionViaClose  modClose  modBtnStyle"><img  src="viaClose.gif"  alt="X"></a><a  class="modBtnStyle"  id="closeVIASite">Don\'t  Show Agent  Again</a></div>');
             /* VIA Close Btn Adjust for small windows*/
            $(window).smartresize(function(){
                fnVIABtnPos();
            });
        }
        /* Label Fix for Slide-down */
        $("#playVIA").hide();
        slidedownZ=$("#slidepanel").css("z-index");
        $("#slidepanel").css("z-index","998");
        $("#modalVIA").lightbox_me({
            centered:true,
            closeSelector:"#actionViaStorage",
            closeClick:false,
            closeEsc:false,
            onLoad:function () {
                swfObjectID="swfVIA";
                $("#swfVideoP").flashembed({
                  src:cdn_url+"core_VIAHandler.swf",
                  width:'860',
                  height:'484',
                  id:swfObjectID,
                  wmode:'transparent',
                  allowScriptAccess:'always'},{
                  sMediaURL:cdn_url+sPerson+"_"+sPage+".swf",
                  domElem:"#swfVideoP",
                  cache:fnCacheBust()});
                $(".lb_overlay").addClass("actionViaClose");
                $(".actionViaClose").click(function(){fnVIAClosePage();$("#actionViaStorage").triggerHandler("click");});
                $("#closeVIASite").click(function(){fnSetCookie("siteVIAOn","f",365);fnVIAClosePage();$("#actionViaStorage").triggerHandler("click");});
                fnVIABtnPos();
                $("#modalVIA").removeClass('hide');
        },
        onClose:function (){
            /* Label Fix for Slide-down */
            $("#slidepanel").css("z-index",slidedownZ);
            $("#swfVideoP").html("");
            $(".oldError").addClass("error").removeClass("oldError");
            $("#playVIA").show();
        }});
    }else{
        $("#playVIA").show();
    }
}
function fnVIAPlay(){
  $("#playVIA").hide();
  fnSetCookie("siteVIAOn","t",365);
  fnSetCookie(sPage+"VIAOn","t",45);
  /* Page errors are dropped behind the modal window */
  $(".error").addClass("oldError").removeClass("error");
  fnVIALoad("on");
}
function fnSwfFormCall(){
  $("#revealForm").show();
  /* Old errors are revealed here */
  $(".viaError").show();
  $(".viaError").addClass("error").removeClass("viaError");
}
function fnSwfPhoneCall(){$("#revealPhone").show();}
function fnSwfCombineCall(){$("#revealCombine").show();}
function fnSwfHomeCall(){$("#revealHome").show();}
function fnSwfAutoCall(){$("#revealAuto").show();}
function fnVIABtnPos(){
    if($(window).height()<620){
        $("#modalVIA").addClass("viaSnap");
        $("#closeVIA").addClass("viaSmall");
    }else{
        $("#modalVIA").removeClass("viaSnap");
        $("#closeVIA").removeClass("viaSmall");
    }
}

/* === DOM Ready === */
$(function() {
 fnLeadSrcCheck();
 if ($.browser.msie){$('body').addClass("ie");$('body').addClass("ie"+jQuery.browser.version.slice(0,jQuery.browser.version.indexOf(".")));}
  /* Setting Presentation GFX */
  if(typeof window.mediaURL!=="undefined"){
    var sVidBlurb="Press play to watch the "+sMenuName+" presentation!";
    if(window.mediaURL==="general_Partners"||window.mediaURL==="general_ComPartners"){
      sVidBlurb="Learn more about our Partners Program. Watch the presentation!";
    }
    if(fnPageLang()==="esp"){sVidBlurb="Mira la presentación "+sMenuName+" para aprender más!";}
    $("#vidBlock").append("<div  id='videoAction'><a  class='modalCall'  id='videoThumb'><div  id='videoIcon'></div><img  id='videoImg'  src='"+cdn_url+"tmb_"+mediaURL+".jpg' /></a><p class='fClear'>"+sVidBlurb+"</p></div>");
    $("#videoThumb").css("cursor","pointer").click(function() {fnVidJsLoad();});
  }
 /* Modal Window */
$('.modalFrCall[rel]').click(function(event){
  if($("#modFrame").length===0){$('body').append('<div id="modFrame" class="hide modBkg"><a href="#" class="modClose modBtnStyle"><img src="viaClose.gif" alt="x"></a><iframe frameborder="0"><p>Your browser does not support iframes.</p></iframe></div>');}
  var element_name=$(this).attr('rel');
  $(element_name+' iframe').attr('src', $(this).attr('href'));
  $(element_name).lightbox_me({
    centered:true,
    closeSelector:'.modClose',
    onClose:function(){
      mediaClear(element_name);
    }
  });
  return false;});
$('.modalCall[rel]').click(function (event){
  var element_name=$(this).attr('rel');
  if($(element_name+' .modClose').length===0){$($(this).attr('rel')).prepend('<a href="#" class="modClose modBtnStyle"><img src="viaClose.gif" alt="x"></a>');}
  $(element_name).lightbox_me({
    centered:true,
    closeSelector:'.modClose',
    onClose:function(){
      mediaClear(element_name);
    }
  });
  return false;});
  
 /* Form Validation & Lang Update */
 $.tools.validator.fn("[type='phone']","Requires xxx-xxx-xxxx",function(input,value){return (/^\(?([2-9])([0-9]{2})\)?\s*[\. \-]?\s*([0-9]{3})\s*[\. \-]?\s*([0-9]{4})$/).test(value);});
 $.tools.validator.fn('[required="fullName"]','Valid full name required',function(input,value){return (/[A-Za-z]+\s[A-Za-z].+/).test(value);});
 if(fnPageLang()==="esp"){/* Spanish */
   $.tools.validator.localize("esp",{'*':'Entrada Válida Requerida','[required]':'Entrada Válida Requerida','[type="phone"]':'Número De Teléfono Válido Requerido',':email':'Correo Electronico Válido Requerido'});
  $("form").validator({position:'top right',lang:'esp',message: '<div><em/></div>'});
 }else{/* English */
  $.tools.validator.localize("en",{'*':'Required field','[required]':'Required field',':email':'Valid email required'});
  $("form").validator({position:'top right',lang:'en',message:'<div><em/></div>'});
 }
 /* Prevents string or numeric input in input/textarea boxes */
 $(".numVal").keypress(function(evt){if(evt.which!==8 && evt.which!==0 && evt.which!==32 && evt.which!==40 && evt.which!==41 && (evt.which<45||evt.which>57)){return false;}});
 $(".strVal").keypress(function(evt){if(evt.which!==8 && evt.which!==0 && evt.which!==32 && evt.which!==46 && evt.which!==45 && (evt.which<65||evt.which>90) && (evt.which<97||evt.which>122)){return false;}});
 /* Enables form buttons on ready */
 $("form[action='#']").attr('action','https://www.insurancemm.com/datacatch.aspx');
 $(':submit').removeAttr('disabled');
 $('form').attr("novalidate","novalidate");
  /* Track debug info */
  $('form').each(function(){
    $(this).append('<input type="hidden" name="CRM_Leads_Debug" value="URL:'+window.location+' - UA:'+navigator.userAgent+'" />');
  });
  /* Full Name Splitter */
  $('[name="jsFullName"]').change(function(){
    var full = $(this).val(),first,last;
    if(full.indexOf(" ") !== -1){
      first=full.slice(0,full.indexOf(" "));
      last=full.slice(full.indexOf(" ")+1);
      $("[name='CRM_Leads_Name']").val(first);
      $("[name='CRM_Leads_Surname']").val(last);
    }
  });
 /* Pauses Thanks Vid on Quote Based, Instant Auto, Instant Home Thanks Pages */
 $(".quoteSpec input[name='Tustena_thankspage']").attr("value",$(".quoteSpec input[name='Tustena_thankspage']").attr("value")+"?lt=q&ap=true");
 $(".quoteAutoSpec input[name='Tustena_thankspage']").attr("value",$(".quoteAutoSpec input[name='Tustena_thankspage']").attr("value")+"?lt=qa&ap=true");
 $(".quoteHomeSpec input[name='Tustena_thankspage']").attr("value",$(".quoteHomeSpec input[name='Tustena_thankspage']").attr("value")+"?lt=qh&ap=true");
  
 /* Tracking and opening outbound links in a new window */
 if(analyticsNum!==""){
   $("a[href^='http']").not("a[href*='"+location.host+"']").click(function(){
     fnRecOutbound($(this).attr("href"),sMenuName+" - Outbound",$(this).attr("href"));
     return false;
   });
}else{
  $("a[href^='http']").not("a[href*='"+location.host+"']").attr("target","_blank");
}
  
/* IE Hax */
$("noscript").remove();
if(!$(".ie7").length){
  /* Certain iterations of IE7 fail when encountering the $(":date") method */
  $(".dateInput").change(function(){console.log($(this).val());});
  $(":date").addClass("dateInput").dateinput({format:'mm/dd/yyyy'});
}else{
  /* Slidedown Error Label Fix*/
  $("#topnav,nav").mouseenter(function(){
    $(".error").hide();
  }).mouseleave(function(){
    $(".error").show();
  });
}
  
/* Bootstrap-based Alert Message Functions */
$('.message').prepend('<a class="close" href="#">×</a>');
$('.message .close').click(function(){$(this).parent().hide();});
  
/* Style over-rides */
$("head").append("<style type='text/css'>#slidepanel{z-index:1200}#closeVIA{width:860px;margin:0 auto}#modalVIA .modClose{float:right;position:static !important}#closeVIASite{margin:0 5px !important;float:right !important}.viaSmall{position:absolute !important;top:0 !important;margin-top:0 !important}#modalVIA.viaSnap{top:0 !important;margin-top:0 !important;max-height:550px !important}</style>");
  
/**
 * If you're on the partner edit page, add http:// to the url fields that dont have it on submit
 */

if( $('#partSiteURL').length ){
  $('form[name=listItemForm]').submit(function(){
    var url_fields = ['#partSiteURL', '#partFacebookURL', '#partTwitterURL', '#partYoutubeURL', '#partLinkedInURL', '#partWordpressURL'],i;
    for(i = 0; i < url_fields.length; i++ ){
      current_value = $(url_fields[i]).val();
      if( current_value != '' && current_value.indexOf('http://') == -1 && current_value.indexOf('https://') == -1 ) {
        new_value = 'http://'+current_value;
        $(url_fields[i]).val(new_value);
      }
    }
  });
}
});
