/* Version 2 - Astonish Specific */
// var lead_SEM="",lead_Keyword="",lead_EmailID="",lead_QR="",formPost="http://www.insurancemm.com/datacatch.aspx";
var lead_SEM="",lead_Keyword="",lead_EmailID="",lead_QR="",formPost="http://www2.astonishlive.com/astonish/siteFormSplit.php";

/*=== Helpers ===*/
function setCookie(cookie_Name, val, days) {
  var dtCur = new Date();
  dtCur.setTime(dtCur.getTime() + (days * 24 * 60 * 60 * 1000));
  document.cookie = cookie_Name + "=" + escape(val) + ";expires=" + dtCur.toGMTString() + ";path=/";
}
function getCookie(val) {
  if (document.cookie.length > 0) {
    var valStart = document.cookie.indexOf(val + "="),
      valEnd;
    if (valStart !== -1) {
      valStart = valStart + val.length + 1;
      valEnd = document.cookie.indexOf(";", valStart);
      if (valEnd === -1) {
        valEnd = document.cookie.length;
      }
      return unescape(document.cookie.substring(valStart, valEnd));
    }
  }
  return "";
}

/*=== Lead Source ===*/
function setSEM(days) {
  /* Vars */
  var phone=semNum,selectVal;
  /* Gears */
  setCookie("ldsrc", "ppc", days);
  setCookie("ppc", lead_SEM, days);
  setCookie("kw", lead_Keyword, days);
  $('form').append('<input type="hidden" name="CRM_Leads_Notes" value="PPC:' + lead_SEM + '" /><input type="hidden" name="CRM_Leads_Notes" value="KW:' + lead_Keyword + '" /><input type="hidden" name="Search_Engine" value="' + lead_SEM + '" /><input type="hidden" name="Search_Keyword" value="' + lead_Keyword + '" />');
  /* Update form contact types */
  /*$('form').append('<input type="hidden" name="CRM_Lead_ContactType" value="189" />');*/
  $("#hearSelect option").each(function(){
    selectVal=$(this).attr("value");
    if(selectVal!=="7"&&selectVal!==""){
      $(this).attr("value","8"+selectVal.slice(1));
      try{console.log(selectVal.slice(1));}catch(err){}
    }else if(selectVal=="7"){
      $(this).attr("value","805");
    }
  });
  /* Adds Standard PPC Number(s) & Form Types */
  if (phone !== "") {
    $('#phoneNumber,.asiPhoneNumber').text(phone);
    var p;
    for (p = 2; p > 1; p++) {
      if (typeof window["nPPCNum" + p] === "undefined") {
        p = 0;
        break;
      } else {
        $('#phoneNumber' + p + ',.asiPhoneNumber' + p).html(window["nPPCNum" + p]);
      }
    }
  }
}
function setEID(days) {
  setCookie("ldsrc", "eid", days);
  setCookie("eid", lead_EmailID, days);
  $('form').append('<input type="hidden" name="CRM_Leads_Notes" value="E-Mail ID:' + lead_EmailID + '" /><input type="hidden" name="Email_Id" value="' + lead_EmailID + '" />');
}
function setQR(days) {
  setCookie("ldsrc", "qr", days);
  setCookie("qr", lead_EmailID, days);
  $('form').append('<input type="hidden" name="CRM_Leads_Notes" value="QR Campaign:' + lead_QR + '" />');
}
function fnLeadSrcCheck() {
  lead_SEM = query("ppc");
  lead_Keyword = query("kw");
  lead_EmailID = query("eid");
  lead_QR = query("qr");
  /* 1. Thru queries */
  if (lead_SEM !== ""&&lead_SEM) {
    try{console.log(lead_SEM);}catch(err){}
    setSEM(45);
  } else if (lead_EmailID !== ""&&lead_EmailID) {
    setEID(5);
  } else if (lead_QR !== ""&&lead_QR) {
    setQR(5);
  } else {
    /* 2. Then Cookies */
    lead_Source = getCookie('ldsrc');
    if (lead_Source === "ppc") {
      lead_SEM = getCookie('ppc');
      lead_Keyword = getCookie('kw');
      setSEM(45);
    } else if (lead_Source === "eid") {
      lead_EmailID = getCookie('eid');
      setEID(5);
    } else if (lead_Source === "qr") {
      try{console.log("QR");}catch(err){}
      lead_QR = getCookie('qr');
      setQR(5);
    }
  }
}
/* Outbound Link Recording */
function outboundRecord(link, category, action) {
  try {
    var pageTracker = _gat._getTracker(analyticsNum);
    pageTracker._trackEvent(category, action);
    setTimeout(window.open(link), 100);
  } catch (err) {}
}
/*=== Speakers Page ===*/
function fnVidReplace(vid, title) {
  var w = 647,
    h = 400;
  $("#video").html('<object width="' + w + '" height="' + h + '"><param name="movie" value="http://www.youtube.com/v/' + vid + '?version=3&amp;hl=en_US&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + vid + '?version=3&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" width="' + w + '" height="' + h + '" wmode="transparent" allowscriptaccess="always" allowfullscreen="true"></embed></object>');
  $("h1").text(title);
}

/* === DOM Ready === */
jQuery.fn.ready(function($){
  /* Lead Source Grab */
  fnLeadSrcCheck();
  
  /* Meta Set */
  $.metadata.setType("attr", "validate");
  
  /* Form Adjust */
  $('[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);
    }
  });
  
  /* Nav Fader */
  $("#navMenu ul a").hover(function () {
    $(this).next().stop().fadeTo(250, 0);
  }, function () {
    $(this).next().stop().fadeTo(200, 1);
  });
  $(".btnGFXOn").hover(function () {
    $(this).children().stop().fadeTo(250, 0);
  }, function () {
    $(this).children().stop().fadeTo(200, 1);
  });
  /* Tracking and opening outbound links in a new window */
  if (analyticsNum !== "") {
    $("a[href^='http']").not("a[href*='" + location.host + "']").click(function () {
      outboundRecord($(this).attr("href"), menuName + " - Outbound", $(this).attr("href"));
      return false;
    });
  } else {
    $("a[href^='http']").not("a[href*='" + location.host + "']").attr("target", "_blank");
  }
  /* IE Fix */
  $("noscript").remove();
  /* Form Validator */
  $.tools.validator.fn("[type='phone']", "Valid phone required", function (input, value) {
    return (/^\(?([0-9]{3})\)?\s*[\. \-]?\s*([0-9]{3})\s*[\. \-]?\s*([0-9]{4})$/).test(value);
  });
  $.tools.validator.fn('[type="fullName"]','Valid full name required', function (input,value) {
    return (/[A-Za-z]+\s[A-Za-z].+/).test(value);
  });
  $.tools.validator.fn('[required]','Required', function (input,value) {
    if($(input).attr("placeholder")==value&&$(input).attr("placeholder")!==undefined){
      return false;
    }else if(value=""){
      return false;
    }else{
      return true;
    }
  });
  $.tools.validator.localize("en",{'*':'Required',':email':'Valid email required'});
  $("form").attr("novalidate","novalidate").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;
    }
  });
  /* Writing POST action for forms to drop bogus leads */
  $('form').each(function () {
    var formAction = $(this).attr("action");
    if(formAction==undefined){formAction=""}
    if (formAction.indexOf("php") == -1 && formAction.indexOf("login")==-1 && $(this).attr('name')!=='listItemForm') {
      $(this).attr("action",unescape(formPost));     
    }
    /* Adding PPC Style */
    $(".applyBox>select").addClass("BoxDesign");
  });
  /* Certain iterations of IE7 fail when encountering the $(":date") method */
  if (!$(".ie7").length) {
    $(".dateInput").change(function () {
      console.log($(this).val());
    });
    $(":date").addClass("dateInput").dateinput({
      format: 'mm/dd/yyyy'
    });
  }
  
   /* Convert multiple Notes fileds to custom names. */
 $("form").each(function(){
  var cln=0;
   $(this).find("*[name='CRM_Leads_Notes']").each(function(){
      $(this).attr('name','CRM_Leads_Notes_'+cln);
      cln++;
   });
});
 /* On Submit, merge custom notes into one. 
     Also to be merged are inputs having the class 'notes'.
     They will be displayed first, and use the input name attribute as the label. */
 $('form').submit(function(e){
   var finalString='',i=0;
   $(this).find(".notes").each(function(){
      if(i!==0){finalString+=",";}
      finalString+=$(this).attr('name')+':'+$(this).attr('value');
      i++;
   });
   $(this).find("*[name^='CRM_Leads_Notes_']").each(function(){
      if(i!==0){finalString+=",";}
      finalString+=$(this).attr('value');
      i++;
   });
   $('.note-merge').remove();
   $(this).append('<input class="note-merge" type="hidden" name="CRM_Leads_Notes" value="'+finalString+'">');
   return true;
 });
  
  /* Enables form buttons on ready */
  $(':submit').removeAttr('disabled');
  /* Home Form */
  if ($("#cForm").length) {
    $('#cForm input[placeholder]').each(function () {
      if ($(this).val() === '') {
        $(this).val($(this).attr('placeholder'));
      }
      $(this).focus(function () {
        if ($(this).val() === $(this).attr('placeholder')) {
          $(this).val('').addClass('focused');
          $(this).css('color', '#4b7394');
        }
      });
      $(this).blur(function () {
        if ($(this).val() === ''||$(this).val()===$(this).attr('placeholder')){
          $(this).val($(this).attr('placeholder')).removeClass('focused');
          $(this).css('color', 'red');
        }
      });
    });
    $("#cForm span.select").blur(function () {
      if ($(this).val()===''||$(this).val()===$(this).attr('placeholder')) {
        $(this).val($(this).attr('holder')).removeClass('focused');
        $(this).css('color','red');
      }
    });
  }
  /* Modal Window */
  $('.modalCall[rel]').click(function (event) {
    $(".error").removeClass("hide");
    if ($($(this).attr('rel') + ' .modClose').length === 0) {
      $($(this).attr('rel')).prepend('<a href="#" class="modClose"><img src="viaClose.gif" alt="x"></a>');
    }
    $($(this).attr('rel')).lightbox_me({
      centered: true,
      closeSelector: '.modClose',
      onClose: function () {
        $(".error").addClass("hide");
      },
      overlaySpeed: 5
    });
    return false;
  });
  /* Speaker Page */
  fnVidReplace($("#vidList li:first-child").find("img").attr("longdesc"), $("#vidList li:first-child").find("img").attr("alt"));
  $("#vidList li").click(function () {
    fnVidReplace($(this).find("img").attr("longdesc"), $(this).find("img").attr("alt"));
  });
  /* Vendor Page */
  $(".listItem a img").each(function () {
    if (!$("#catSelect option[value='" + $(this).attr("alt") + "']").length) {
      $("#catSelect").append("<option value='" + $(this).attr("alt") + "'>" + $(this).attr("alt") + "</option>");
    }
  });
  $("#catSelect").change(function () {
    var menuVal = $("#catSelect").attr("value");
    if (menuVal === "all") {
      $(".listItem").show();
    } else {
      $(".listItem").hide();
      $(".listItem a img[alt='" + menuVal + "']").closest('.listItem').show();
    }
  });
  $("#catMenu").scrollFollow({
    easing: 'easeOutCubic',
    offset: 5
  });
  /* Home Vid */
  if(menuName=="Home"){
    $("#navLeft").html("<img style='margin:0;padding:0;border:none;cursor:pointer' id='homePlay' alt='Press Play to Watch the 180 Second Tour' src='/vimeoPlay.jpg' />");
  }
  $("#homePlay").click(function(){
    var vimW=601,vimH=338;
    if(!$("#homeVid").length){
      $("body").append('<div id="homeVid" style="display:none;border:2px solid #fff"><a class="closeBtn"><img src="http://cdn.astonishlive.com/viaClose.gif" alt="X"></a><div id="homeVimeo" style="width:'+vimW+'px;height:'+vimH+'px"></div></div>');
    }
    $("#homeVid").lightbox_me({
      centered:true,
      closeSelector:".closeBtn",
      closeClick:true,
      closeEsc:true,
      onLoad:function () {
        $("#homeVimeo").html('<iframe src="http://player.vimeo.com/video/28202483?color=c9ff23&amp;autoplay=1" width="'+vimW+'" height="'+vimH+'" frameborder="0"></iframe>')
      },
      onClose:function (){
        $("#homeVimeo").html("");
      }
    });
  });  
});

