/**
 * @author carlosg
 */
$(document).ready(function() {
  var location = IU.getLocation();
  IU.loadHeader(location);
  IU.loadFooter();
  IU.formValidator = stepFormValidator;
  $("#accordion").accordion({
    autoHeight: false
  });
  IU.loadLocations();
  // Remove all the required Messages
  jQuery.validator.messages.required = "";
  jQuery.validator.messages.email = "";
  Boxy.DEFAULTS.title = 'Title';
  if (location == 'formSelect'){
    IU.updateNavigationIcons();
  }
});

String.prototype.capitalize = function(){
    return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
};

/* Namespace for IU*/
var IU = {
  getLocation: function(){
    var location = document.location.toString().match(/[a-zA-Z]*(?=\.[a-z]{3}$)/);
    location = (location) ? location.toString() : 'index' ;
    return location;
  },
  locations: null,
  loadHeader: function(location){
    $('#header').insertBefore('#mainSection');
    var imgs = { 
      "index" : ["auto_03.jpg","smallAutoQuote.png"],
      "about" : ["auto_03.jpg","smallAutoQuote.png"],
      "auto" : ["auto_03.jpg","smallAutoQuote.png"],
      "life" : ["life_03.jpg","smallLifeQuote.png"],
      "home" : ["homeowners_03.jpg","smallHomeownersQuote.png"],
      "renters" : ["renters_03.jpg","smallRentersQuote.png"],
      "recreational" : ["recreational_03.jpg","smallRecreationalQuote.png"],
      "smallCommercial" : ["smallCommercial_03.jpg","smallCommercialQuote.png"],
      "formSelect" : ["smallCommercial_03.jpg",""]
    };
    $("#mainPhoto").children("img").attr("src","images/"+ imgs[location][0]);
    IU.updateNavs(location);
    IU.bindHeaderEvents();
    $("#smallQuoteIcon").css("background-image","url(images/"+imgs[location][1] +")");
    if (location == "auto"){
      $("#smallQuoteIcon").click(IU.showAutoForm);
    }
    else if (location == "home") {
      $("#smallQuoteIcon").click(IU.showHomeOwnerForm);
    }
    else if (location == "smallCommercial"){
      $("#smallQuoteIcon").click(function(){
        IU.showModal("Get a Commercial Insurance Quote", "Provide us you information and we'll get back with you.");
      });
    }
    else{
      $("#smallQuoteIcon").click(function(){
        IU.showModal("Get a "+ location.capitalize() +" Insurance Quote", "Provide us you information and we'll get back with you.");
      });
    }
    return false;
  },
  loadFooter: function(){ 
    $.get('includes/footer.php', {  }, function(result) {
      $("#footer").append($(result).html());
    });
    return false;
  },
  loadLocations: function(){
    $.post("./includes/Utah.php",  null, function(data){
      IU.locations = (data);
      var list = $("#listLocations");
      var li;
      var anchor;
      var index;
      for (index in IU.locations){
        anchor = IU.createElement("a", {href: "#", title: index + " County"}, null, index + " County");
        if (index.match(/Insurance Office|Family First/)){
          anchor.html(anchor.html().replace(/\ County/, ""));
        }
        anchor.click(function(){ 
          $("#storeLocations").remove();
          var self = $(this);
          var param = self.html().match(/^(.*)\ County$/);
          if (param == null){
//            param = self.html().match(/(Insurance\ Office)|(Family\ First)/);
            param = [null, self.html()];
          }
          self.append(IU.createLocations(param[1]));
          return false;
        });
        li = IU.createElement("li", {}, null, anchor);
        list.append(li);
      }
      
    }, "json");
  },
  boxy : null,
  createLocations: function(county){
    var div = IU.createElement("div", {id : "storeLocations"}, "smallText", null);
    var list = IU.createElement("ul", {}, null, null);
    var locations = IU.locations[county];
    var index;
    var anchor;    
    for (index in locations){
      anchor = IU.createElement("a", {href: "#"}, null, index);
      anchor.click(function(){
        var self = $(this);
        var county = self.parents("a").attr("title").replace(/\sCounty/,"");
        var locationName = self.html();
        if (IU.boxy != null){
          IU.boxy.unload();
        }
        Boxy.load("includes/locations.php", {
          afterShow: function() {
            this.moveTo(404, null);
            IU.boxy = this;
            var locationObj = IU.locations[county][locationName];
            $("#locationAddress").html("<br/>" + locationObj["address"] + 
                                       "<br/>" + locationObj["city"] + 
                                       " , UT<br/>" +  locationObj["zip"]);
            $("#locationHours").html("<br/>" + locationObj["storehours"]);
            $("#locationTelephone").html("<br/>" + locationObj["phonenumber"]);
            $("#locationFax").html("<br/>" + locationObj["faxnumber"]);
            var latlng = new google.maps.LatLng(locationObj["x"], locationObj["y"]);
            var myOptions = {
              zoom: 15,
              center: latlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              mapTypeControl: false
            };
            var image = (county.match(/Insurance|Family/)) ? null : 'images/ccIcon_03.png';
            var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
            var beachMarker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: image
            });
          },
          afterHide: function() {
            this.unload();
          },
          title: locationName + ' Location',
          draggable: true
        }); 
        return false;
      });
      li = IU.createElement("li", {}, null, anchor);
      list.append(li);
    }
    div.append(list);
    return div;
  },
  updateNavs:function(location){
    var topNav = $("ul.topNav");
    var subNav = $("ul.subNav");
    switch(location){
      case 'index':
        topNav.find("a:contains('Insurance')").addClass('selected');
        break;
      case 'about':
        topNav.find("a:contains('About')").addClass('selected');
        break;
      case 'auto':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Auto')").addClass('selected');
        break;
      case 'life':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Life')").addClass('selected');
        break;
      case 'home':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Homeowners')").addClass('selected');
        break;
      case 'renters':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Renters')").addClass('selected');
        break;
      case 'recreational':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Recreational')").addClass('selected');
        break;
      case 'smallCommercial':
        topNav.find("a:contains('Policies')").addClass('selected');
        subNav.find("a:contains('Small Commercial')").addClass('selected');
        break;
    };
  },
  showAutoForm: function(){
    $.get('includes/autoQuoteForm.php', {}, function(data, textStatus) {
      $("#contentText").html(data);
      IU.formValidator.prepareQuoteForm( 
        { validateFunction : IU.validateStep,
          submitFunction   : IU.submitForm,
          updateElement    : $("#contentText"),
          caller           : "auto" }
      );
      IU.autoForm.initialize();
    }, "xhtml");
  },
  showHomeOwnerForm: function(){
    $.get('includes/homeOwnersQuoteForm.php', {}, function(data, textStatus) {
      $("#contentText").html(data);
      IU.formValidator.prepareQuoteForm( 
        { validateFunction : IU.validateStep,
          submitFunction   : IU.submitForm,
          updateElement    : $("#contentText"),
          caller           : "home" }
      );
      IU.homeOwnerForm.initialize();
    }, "xhtml");
  },
  updateNavigationIcons: function(){
    $("#insuranceQuoteIcon-Auto").click(function(){
      IU.showAutoForm();
    });
    $("#insuranceQuoteIcon-Renters").click(function(){ 
      IU.showModal("Get a Renters Insurance Quote", "Provide us you information and we'll get back with you.", "renters");
    });
    $("#insuranceQuoteIcon-Life").click(function(){ 
      IU.showModal("Get a Life Insurance Quote", "Provide us you information and we'll get back with you.", "life");
    });
    $("#insuranceQuoteIcon-Rec").click(function(){ 
      IU.showModal("Get a Recreation Insurance Quote", "Provide us you information and we'll get back with you.", "recreational");
    });
    $("#insuranceQuoteIcon-Home").click(function(){ 
      IU.showHomeOwnerForm();
    });
    $("#insuranceQuoteIcon-Commer").click(function(){ 
      IU.showModal("Get a Commercial Insurance Quote", "Provide us you information and we'll get back with you.", "smallCommercial");
    });
  },
  showModal: function(titleText, headerText, location){
    IU.mailForm.initialize({ 
      title: titleText,
      header: headerText
    });
    if (location){
      IU.mailForm.show(location);
    }
    else{
      IU.mailForm.show(IU.getLocation());
    }
  },
  bindHeaderEvents: function(){
    $('#accordion').bind('accordionchange', function(event, ui) {
      ui.newHeader.next().effect('highlight', {}, 1000); 
    });
    $("#onlineIconDiv").click(
      function() { IU.accordionExternalClick('Quotes'); }                                                        
    );
    $("#phoneIconDiv").click(
      function() { IU.accordionExternalClick('Phone Contact'); }  
    );
    $("#onSiteIconDiv").click( 
      function() { IU.accordionExternalClick('Locations'); }  
    );
    $("a:contains('email')").click(function(){
      IU.showModal("Send Us an Email!");
    } );
    $("li:contains('Contact')").click(
      function() { IU.accordionExternalClick('Phone Contact'); }  
    );
    $("#quoteButtonDiv").click(function(){
      IU.showModal("Get a Free Quote!");
    } );
  },
  createElement: function(el, attribs, cssClass, innerHTML){
    var element = $(document.createElement(el));
    if (attribs) {
      element.attr(attribs);
    }
    if (cssClass) {
      element.addClass(cssClass);
    }
    if (innerHTML) {
      element.append(innerHTML);
    }
    return element;
  },
  loadVals: function(){
    $("#Full_Name").val("Carlos");
    $("#Address").val("Leadgenix Street");
    $("#City").val("Provo");
    $("#State").val("UT");
    $("#Zip").val("12345");
    $("#Phone").val("(123) 456-7890");
    $("#Years_At_Address").val("2");
    $("#Homeowner").val("Yes");
  },
  accordionExternalClick: function(elem) {
    var element = $("#accordion").find("a:contains('"+elem+"')");
    if (element.parent().hasClass( 'ui-state-active' )){
      element.parent().next().effect('highlight', {}, 1000);
    }
    element.click();
  },
  validateStep: function(stepDiv){
    var validationObj = $("#"+stepDiv).find("form").validate({
      invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
          var message = errors == 1
            ? 'You missed 1 field. It has been highlighted'
            : 'You missed ' + errors + ' fields. They have been highlighted';
          $("div.error span").html(message);
          $("div.error").show();
          $("label.error").hide();
        } else {
          $("div.error").hide();
        }
      },
      submitHandler: function() {
        $("div.error").hide();
      }
    });
   // alert(variable);
    if (stepDiv == "step2" && $("#Number_Cars").val() == ""){
      return false;
    }
    if (stepDiv == "step4" && $("#Number_Drivers").val() == ""){
      return false;
    }
    return validationObj.form(); 
  },
  createFinalForm: function(){
    var form = $(document.createElement("form"));
    form.attr({method:"post", id: "applicationForm", name: "applicationForm"});
    form.css("display", "none");
    return form;
  },
  submitForm: function(element){
    //Only use this function if validation has been approved
    if ($("#applicationForm").length == 0){
      $(".content").append(IU.createFinalForm());
    }
    else{
      $("#applicationForm").html("");
    }
    IU.formValidator.prepareFinalForm($("#applicationForm"));
    var div = element; //$("#contentText");
    var age = $("#Age").val();
    div.html("");
    if (age == "" ){
      $.post("includes/FormMailer.php", $("#applicationForm").serializeArray(), function(text) {
        $.get("includes/thank-you.php", {}, function(data){
          div.append(data);
          div.find("#thankYouImg").append(text);
        }, "html");
      }, "text");
    }
    else{
      div.html("<div id='thankYouImg'>Thank you!</div>");
    }
  }
};

