﻿$(function(){
  // IE Hacks:
  //$("#quote_forms .tabs a").first().css("margin-right", "2px");
  
  if ($.browser.webkit) {
    $("#quote_forms .tabs").css("height", "34px");
  }

  /*
  $("div.controls a").hover(function(){
    var parent = $("#"+$(this).parent().attr("to"));
    if ($(this).hasClass("control-left")){
      parent.stop().scrollTo(0, 5000);
    } else {
      parent.stop().scrollTo('max', 5000);
    }
  }, function(){
    $("#"+$(this).parent().attr("to")).stop();
  });
  */
  $("div.controls a").click(function(){
    var parent = $("#"+$(this).parent().attr("to"));
    if ($(this).hasClass("control-left")){
      parent.stop().scrollTo('-=450', 150);
    } else {
      parent.stop().scrollTo('+=450', 150);
    }
    return false;
  });

  $(".banners").each(function(){
    var that = $(this);
    var i = 0;
    $(this).find(".banner").each(function(){
      i++;
      that.find(".banner-controls").append("<a href=''>" + i + "</a> ");
    });
    $(this).find(".banner-controls a:eq(0)").addClass("selected");
    var intId = setInterval(function(){ nextItem(that, "div.banner"); }, $(this).attr("pauseTime"));
  });
  $(".banner-controls a").live("click", function(){
    var eq = $(this).index();
    $(this).parent().find("a").removeClass("selected");
    $(this).addClass("selected");
    var banners = $(this).parent().parent();
    banners.find(".banner").hide();
    banners.find(".banner:eq("+eq+")").show();
    return false;
  });

  $(".carousel").each(function(){
    var that = this;
    $(this).data("carousel", $(this).find(".carousel-child").length);
    setInterval(function(){ carousel(that); }, $(this).attr("pauseTime"));
  });

  $(".tabs a").click(function(){
    var parent = $(this).parent();
    if (parent.attr("to") == "href"){
      return true;
    }
    var divToShow = $("#"+parent.attr("to")+" .tab-content").eq($(this).index());
    if (parent.hasClass("fade")){
      $("#"+parent.attr("to")+" .tab-content:visible").stop(true, true).fadeOut("fast", function(){
        divToShow.fadeIn("fast");
      });
    } else {
      $("#"+parent.attr("to")+" .tab-content").addClass("hide");
      divToShow.removeClass("hide");
    }
    parent.find("a").removeClass("selected");
    $(this).addClass("selected");
    if (parent.hasClass("tab-resize")){
      resizeDiv(divToShow, divToShow.find("a"), true);
    }
    if (parent.attr("to") == "quote_form"){
      //html5form("form.lead-form");
    }
    return false;
  });

  $(".show-pop-up").hover(function(){
    var popup = $("#popup");
    popup.html($("#"+$(this).attr("alt")).html());
    var offset = $(this).offset();
    var left = offset.left - 70;
    var arrowLeft = 115;
    var mainOffset = $("#main div.content:first").offset();
    var mainWidth = $("#main div.content:first").width();
    if ($(this).context.tagName == "AREA"){
      var coords = $(this).attr("coords").split(",");
      var imgLeft = parseInt(coords[2]) + $("#research_tab div:visible").offset().left - 90;
      var imgTop = parseInt(coords[1]) + $("#research_tab div:visible").offset().top - 10;
      offset.top = imgTop;
      mainOffset = { left: imgLeft, top: imgTop };
      //var offset = { left: imgLeft, top: imgTop };
    }
    if (left < mainOffset.left) {
      left = mainOffset.left;
      arrowLeft = $(this).width() / 2 + 30;
    } else if (popup.width() + left > mainWidth + mainOffset.left) {
      left = (mainWidth + mainOffset.left) - popup.width();
      arrowLeft = popup.width() - ($(this).width() / 2) - 30;
    }
    var top = offset.top - popup.height();
    popup.stop(true, true).fadeIn(100).css({ top: top, left: left });
    popup.append("<div class='pop-up-arrow'></div>");
    popup.find("div.pop-up-arrow").css({ left: arrowLeft });
    if ($.browser.msie && $.browser.version < 9){
      popup.css("border", "3px solid #e9e9e9");
    }
  }, function(){
    $("#popup").delay(500).fadeOut(100);
  });

  $("#popup").hover(function () {
    $(this).stop(true, true).fadeIn(100);
  }, function () {
    $(this).fadeOut(100);
  });

  $("#top_links a").click(function(){
    $("#top_links a").removeClass("selected");
    if ($($(this).attr("href")).is(":visible")){
      $($(this).attr("href")).slideUp(200, function(){
        $("#top_popup").hide();
      });
    } else {
      $(this).addClass("selected");
      $("#top_popup > div").hide();
      if ($("#top_popup").is(":visible")){
        $($(this).attr("href")).show();
      } else {
        $("#top_popup").show().css("right", $("#main div.content:first").offset().left);
        $($(this).attr("href")).slideDown(200);
      }
    }
    return false;
  });
  $("#top_popup .close").click(function(){
    $("#top_links a").removeClass("selected");
    $("#top_popup").slideUp(200);
    return false;
  });

  $(".video-player").click(function () {
    $("#VideoPlayer").html("");
    if ($(this).attr("video")) {
      if ($(this).attr("video") == "embed") {
        $("#VideoPlayer").html($(this).find("span.embed").attr("embed"));
      } else {
        var src = "swf/VideoPlayer.swf?videoSkin=swf/skin.swf&videoPath=" + $(this).attr("video");
        $("#VideoPlayer").html("<object width='798' height='420'><param name='movie' value='" + src + "'><param name='wmode' value='transparent'>" +
          "<embed src='" + src + "' type='application/x-shockwave-flash' wmode='transparent' width='798' height='420'></embed></object>");
      }
      _gaq.push(['_trackEvent', 'Video', 'Play', CurrentPage]);
      //$.ajax({ url: "include/analytics.asp", type: "POST", data: "video=true" });
    }
  });

  $(".fancy").fancybox({
    'speedIn': 100,
    'speedOut': 50,
    'centerOnScroll': true,
    'onClosed': function () { $("#VideoPlayer").html(""); }
  });

  $(".fancy-iframe").fancybox({
    'type': 'iframe',
    'hideOnOverlayClick': false,
    'hideOnContentClick': false,
    'speedIn': 100,
    'speedOut': 50,
    'width': 820,
    'height': 600,
    'centerOnScroll': true
  });

  $(".calc-iframe").fancybox({
    'type': 'iframe',
    'hideOnOverlayClick': false,
    'hideOnContentClick': false,
    'speedIn': 100,
    'speedOut': 50,
    'width': 735,
    'height': 550,
    'centerOnScroll': true
  });

  $(".leadform-iframe").fancybox({
    'type': 'iframe',
    'speedIn': 100,
    'speedOut': 50,
    'width': 720,
    'height': 550,
    'centerOnScroll': true
  });

  $(".leadform").fancybox({
    'speedIn': 100,
    'speedOut': 50,
    'centerOnScroll': true
  });

  $(".leadform").click(function(){
    if ($(this).hasClass("leadform-stock")){
      $($(this).attr("href")+" input[name=LeadStock]").val($(this).attr("alt"));
    }
    if ($(this).hasClass("leadform-title")){
      $($(this).attr("href")+" h4").text($(this).attr("title"));
    }
  });

  $("#search_bar select").change(function () {
    $.ajax({
      url: "include/inventory-ajax.asp",
      dataType: "html",
      data: $("#search_bar form").serialize(),
      success: function(r){
        var selectedModel = $("#search_bar select[name=model]").val();
        $("#search_bar select[name=model] option:not(.keep)").remove();
        var selectModel = $("#Models", r).html();
        if (selectModel == null) { selectModel = $(r).filter(function () { return $(this).is("select#Models"); }).html(); }
        $("#search_bar select[name=model]").append(selectModel);
        if ($("#search_bar select[name=model] option[value=" + selectedModel + "]").length == 0) { selectedModel = ""; }
        $("#search_bar select[name=model]").val(selectedModel);

        var selectedMake = $("#search_bar select[name=make]").val();
        $("#search_bar select[name=make] option:not(.keep)").remove();
        var selectMake = $("#Makes", r).html();
        if (selectMake == null) { selectMake = $(r).filter(function () { return $(this).is("select#Makes"); }).html(); }
        $("#search_bar select[name=make]").append(selectMake);
        if ($("#search_bar select[name=make] option[value=" + selectedMake + "]").length == 0) { selectedMake = ""; }
        $("#search_bar select[name=make]").val(selectedMake);
      }
    });
  });

  $(".icon-print").click(function(){
    window.print();
    _gaq.push(['_trackEvent', 'Print Page', CurrentPage]);
    return false;
  });

  $(".duplicate").each(function(){
    $(this).html($("#"+$(this).attr("from")).html());
  });

  $(".input-labels input:text, .input-labels textarea").each(function(){
    $(this).val($(this).attr("title"));
  }).focus(function(){
    if ($(this).val() == $(this).attr("title")) $(this).val("");
  }).blur(function(){
    if ($(this).val() == "") $(this).val($(this).attr("title"));
  });
  $("form.lead-form").submit(function(){
    var form = $(this);
    var error = false;
    form.find(":input").each(function(){
      if ($(this).hasClass("required") != ""){
        if ($(this).val() == $(this).attr("title") || $(this).val() == ""){
          alert("Please enter this field: " + $(this).attr("title"));
          $(this).focus();
          error = true;
          return false;
        }
      }
    });
    if (!error){
      $.ajax({
        url: form.attr("action"),
        type: form.attr("method"),
        dataType: "jsonp",
        data: form.serialize(),
        error: function(){
          alert("There was an error, please contact us using the phone number on the website.");
        },
        success: function(data){
          form.find(":input").not(":hidden, :button, :submit, :radio, :checkbox, select").each(function(){
            $(this).val($(this).attr("title"));
          });
          alert("Thank you, we will contact you shortly.");
          if (form.attr("action") == "include/leads.asp"){
            _gaq.push(['_trackEvent', 'Lead', 'Lead Form', CurrentPage]);
          } else {
            _gaq.push(['_trackEvent', 'Lead', 'Finance Form', CurrentPage]);
          }
          $.fancybox.close();
        }
      });
    }
    return false;
  });

  if (window.location.hash){
    var elem = $(window.location.hash.replace("-",""));
    if (!elem.hasClass(".hide")){
      //$(document).find("div[to=car_detail_tab] a").eq(elem.index()).click();
      elem.click();
      $(document).scrollTo(elem, 1000);
    } else {
      $(document).scrollTo(elem, 500);
    }
  }

  $(".showHideIncentive").click(function(){
    $($(this).attr("href")).toggle();
    return false;
  });

  if ($("#ActivEngageChatButton").length > 0){
    intActivEngage = setInterval(activEngageInt, 2000);
  }

});

var intActivEngage;

function activEngageInt(){
  if ($("#ActivEngageChatButton img").length > 0){
    if ($("#ActivEngageChatButton img").attr("src").indexOf("offline") > -1){
      $("#ActivEngageChatButton a").addClass("offline");
    }
    $("#ActivEngageChatButton").fadeIn(200);
    clearInterval(intActivEngage);
  }
}

function func(obj){ } // dummy function for jsonp submit

window.onload = function(){
  resizeDiv($("#home_search_tab > div:not(.hide):first"), $("#home_search_tab div:not(.hide):first > a"), true);
  resizeDiv($("#model_images_content .horz-content"), $("#model_images_content .horz-content div"));
}

function resizeDiv(obj, child, extra){
  var len = child.length;
  if (extra){
    obj.css("width", child.outerWidth(true)*len+(len*3));
  } else {
    obj.css("width", child.outerWidth(true)*len);
  }
}

function nextItem(elem, sel) {
  var i = $(elem).find(sel+":visible").index();
  if (i >= $(elem).find(sel).length) { i = 0; }
  $(elem).find(sel+"-controls a").removeClass("selected");
  $(elem).find(sel).hide();
  $(elem).find(sel).eq(i).show();
  $(elem).find(sel+"-controls a").eq(i).addClass("selected");
}

function carousel(elem){
  var total = $(elem).data("carousel")+0;
  var cur = $(elem).find(".carousel-child:not(.hide)").index();
  cur = (cur < total-1) ? cur+1 : 0;
  $(elem).find(".carousel-child:not(.hide)").fadeOut(500, function(){
    $(this).addClass("hide");
    $(elem).find(".carousel-child:eq("+cur+")").show().removeClass("hide");
  });
}

function map_directions(start, end) {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var directionsMap;
  var myOptions = {
    zoom:7,
    scrollwheel: false,
    panControl: false,
    mapTypeControl: false,
    draggable: false,
    zoomControl: false,
    streetViewControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  directionsMap = new google.maps.Map(document.getElementById("map_directions"), myOptions);
  directionsDisplay.setMap(directionsMap);
  var request = {
      origin: start,
      destination: end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

