/**
* Copyright (C) 2009 TopCoder Inc., All Rights Reserved.
*
* Auto Application Prototype Conversion
* Author TCSASSEMBLER
* Version 1.0
*/

// The document's ready handler
var h = 199, w = 375;
$(document).ready(function() {

    if (navigator.appName == "Microsoft Internet Explorer") {

        if (navigator.appVersion >= "7.0") {
            h = 370;
        }
        else {

            w = 375;
            h = 205;
        }
    }

    // Open the zip code window if no zip code saved in cookie
    if (enableZipCodeDialog.toLowerCase() == "true" && $.cookie('zipcode') == null) {
        tb_show("Your ZipCode", basePath + "ZipPopup.aspx?placeValuesBeforeTB_=savedValues&amp;TB_iframe=true&amp;height=" + h + "&amp;width=" + w + "&amp;modal=true", "test");
    }

    /*
    $('#tabvanilla_reviews').tabs({selected: 7});
    $('#tabvanilla').tabs();
    */
    var current_tab = $('#tabvanilla .tabs a.current').attr('tabindex');
    $('#tabvanilla').tabs({ selected: current_tab - 1 });

    $('#tabCarDetails').tabs({ selected: 0 });

    //addImagePreviews();
    highlightTableRows();
    addSuperGraphics();
    //uncomment to preload every image referenced by css
    // $.preloadCssImages();


    // toggle box
    $(".toggle").click(function() {
        var table = $(this).attr('href');
        if ($(this).html() == '-') {
            $(table + ' tbody').fadeOut('fast');
            $(this).html('+');
        } else {
            $(table + ' tbody').fadeIn('fast');
            $(this).html('-');
        }
        return false;
    });

    // toggle all
    $(".toggleAll").toggle(
    function() {
        $(".category tbody").fadeIn('fast');
        $(this).html('Close All Categories');
        $(".category .toggle").html('-');
        return false;
    },
    function() {
        $(".category tbody").fadeOut('fast');
        $(this).html('Open All Categories');
        $(".category .toggle").html('+');
        return false;
    }
  );


    // green marketplace
    $("#greenNav a").click(function() {
        var div = $(this).attr('href');

        $(".greenWelcome").fadeOut();
        $(div).fadeIn();

        $("#greenNav a").removeClass('current');
        $(this).addClass('current');

        return false;
    });



    /**
    * Modal Functionalities
    **/
    positionModal = function() {
        var wWidth = window.innerWidth;
        var wHeight = window.innerHeight;

        if (wWidth == undefined) {
            wWidth = document.documentElement.clientWidth;
            wHeight = document.documentElement.clientHeight;
        }

        var boxLeft = parseInt((wWidth / 2) - ($("#modal").width() / 2));
        var boxTop = parseInt((wHeight / 2) - ($("#modal").height() / 2));

        // position modal
        $("#modal").css({
            'margin': boxTop + 'px auto 0 ' + boxLeft + 'px'
        });
    }

    loadModal = function(url) {
        $("body").append('<div id="modalBackground"></modal>');
        $("#modalBackground").css("opacity", "0.75");
        $("body").append('<div id="modalWrapper"></modal>');
        $("#modalWrapper").append('<div id="modal"></div>');

        var wHeight = window.innerHeight;
        if (wHeight == undefined) {
            wHeight = document.documentElement.clientHeight;
        }
        $("#modalBackground").height(wHeight + 'px');
        $("#modalWrapper").height(wHeight + 'px');

        positionModal();
        $.ajax({
            url: url,
            success: function(html) {
                $("#modal").html(html).fadeIn('slow');

                // Load jcarousel
                function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
                    var idx = carousel.index(i, mycarousel_itemList.length);
                    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
                    $("#mycarousel img").click(function() {
                        $("#mainImage").attr("src", $(this).attr("src"));
                    })
                };

                function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
                    carousel.remove(i);
                };

                function mycarousel_getItemHTML(item) {
                    if (item.url != null) {
                        return '<a href="#"><img src="' + item.url + '" width="73" height="55"/></a>';
                    }
                };
                if (window.mycarousel_itemList && mycarousel_itemList.length > 0) {
                    jQuery('#mycarousel').jcarousel({
                        wrap: 'circular',
                        itemVisibleInCallback: { onBeforeAnimation: mycarousel_itemVisibleInCallback },
                        itemVisibleOutCallback: { onAfterAnimation: mycarousel_itemVisibleOutCallback }
                    });

                    $("#mycarousel img").click(function() {
                        $("#mainImage").attr("src", $(this).attr("src"));
                    })

                    if (mycarousel_itemList.length > 0) {
                        $("#mainImage").attr("src", mycarousel_itemList[0].url);
                    }
                }
                positionModal();
            },
            error: function() {
                alert("Error loading page");
                closeModal();
            }
        });
    }

    closeModal = function() {
        $("#modalWrapper").remove();
        $("#modalBackground").remove();
    }

    $(".closeModal").live('click', function() {
        closeModal();
    });

    $(".camera_link").click(function() {
        loadModal('/NewCars/CarPreview.aspx?ID=' + this.id.substr(5, this.id.length - 5)); // id pattern is "photo{vehicleId}"
        return false;
    });


    // change car
    $("#quoteMake, #quoteModel").change(function() {
        if ($("#quoteCarPreview").length > 0) {
            var carMake = $("#quoteMake").val();
            var carModel = $("#quoteModel").val();
            var path = './images/vehicles/';

            $("#quoteCarPreview").attr('src', path + carMake + '-' + carModel + '.png');
        }
    });

    // toggle steps open and close on steps
    /*$(".step .header h2").click(function() {
    if ($(this).parent().parent().children(".content").css("display") == "none") {
    $(this).css("background-image", "url(/images/large_black_arrow_tilted.gif)");
    $(this).css({ backgroundPosition: "8px 12px" });
    $(this).parent().parent().children(".content").css("display", "block");
    } else {
    $(this).css("background-image", "url(/images/large_black_arrow.gif)");
    $(this).css({ backgroundPosition: "12px 8px" });
    $(this).parent().parent().children(".content").css("display", "none");
    }
    });*/

    $("#expand").click(function() {
        if ($("#content #newCarBasics .boxbody").css("height") == '310px') {
            $("#content #newCarBasics .boxbody").css("height", "auto");
            $("#expand").css("display", "none");
            $("#part2").css("display", "block");
        }

        if ($("#content #usedCarBasics .boxbody").css("height") == '310px') {
            $("#content #usedCarBasics .boxbody").css("height", "auto");
            $("#expand").css("display", "none");
            $("#part2").css("display", "block");
        }

        if ($("#content #autoLoanBasics .boxbody").css("height") == '315px') {
            $("#content #autoLoanBasics .boxbody").css("height", "auto");
            $("#expand").css("display", "none");
            $("#part2").css("display", "block");
        }

        if ($("#content #autoInsuranceBasics .boxbody").css("height") == '315px') {
            $("#content #autoInsuranceBasics .boxbody").css("height", "auto");
            $("#expand").css("display", "none");
            $("#part2").css("display", "block");
        }

        if ($("#content #autoWarrantyBasics .boxbody").css("height") == '315px') {
            $("#content #autoWarrantyBasics .boxbody").css("height", "auto");
            $("#expand").css("display", "none");
            $("#part2").css("display", "block");
        }

        /*if ($("#content #greenBasics .boxbody").css("height") == '188px') {
        $("#content #greenBasics .boxbody").css("height", "auto");
        $("#expand").css("display", "none");
        $("#part2").css("display", "block");
        }*/
        return false;
    });
    $("#collapse").click(function() {
        $("#content #newCarBasics .boxbody").css("height", "310px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");

        $("#content #usedCarBasics .boxbody").css("height", "310px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");

        $("#content #autoLoanBasics .boxbody").css("height", "315px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");

        $("#content #autoInsuranceBasics .boxbody").css("height", "315px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");

        $("#content #autoWarrantyBasics .boxbody").css("height", "315px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");

        /*$("#content #greenBasics .boxbody").css("height", "188px");
        $("#expand").css("display", "block");
        $("#part2").css("display", "none");*/
        return false;
    });

    // hide bottom line in case of firefox for main boxes
    if ($.browser.msie) {
        $(".car-details .box-bottom").css("display", "block");
    }
});

function highlightTableRows() {
    $('table tr:odd').addClass('odd');
    $('table.used-car-results tr').removeClass('odd');
    $('table tr').mouseover(function() {
        if ($(this).attr('class') != undefined && $(this).attr('class').indexOf('ignore') >= 0) {
            return;
        }
        $(this).addClass('highlight');
    });
    $('table tr').mouseout(function() {
        $(this).removeClass('highlight');
    });
}

function addSuperGraphics() {
    $.each([{ id: '#sAboutUs', classname: 'aboutUs' }, { id: '#sCarLoanRequest', classname: 'carLoanRequest' },
          { id: '#sDealerQuote', classname: 'dealerQuote' }, { id: '#sAutoInsurance', classname: 'autoInsurance' },
          { id: '#sAutoWarranty', classname: 'autoWarranty' }, { id: '#sMake', classname: 'make' },
          { id: '#sVehicleType', classname: 'vehicleType' }, { id: '#sPrice', classname: 'sPrices' },
          { id: '#sNewCarDealerQuote', classname: 'newDealerQuote' }, { id: '#sUsedCarSearch', classname: 'usedCarSearch' },
          { id: '#sMPG', classname: 'mpg' }, { id: '#sUsedCarGarage', classname: 'usedCar'}], function(i, o) {
              if ($(o.id)) {
                  $(o.id).click(function() {
                      $("#supergraphic").attr('class', '');
                      $("#supergraphic").addClass(o.classname);
                      $("#new_car_supergraphic").attr('class', '');
                      $("#new_car_supergraphic").addClass(o.classname);


                      // added for section content
                      $(".superbox").hide();
                      if ($("#supergraphic").length > 0) {
                          $("#" + o.classname).show();
                      }
                      if ($("#new_car_supergraphic").length > 0) {
                          $("#" + o.classname).fadeIn();
                      }


                      if ($(o.id)) {
                          $("#supernav li").attr('class', '');
                          $(o.id).parent().addClass('current');
                      }
                  });
                  if ("#" + o.classname + "Tab" == location.hash) {
                      $(o.id).click();
                  }
              }
          });
}

function openInPopup(url, type) {
    if (type == 1) {
        if ($("#loanType").val() == "5") {
            url = "https://secure.lendingtree.com/auto/ctl_Borrower.asp?page=loan_selection&verb=continue&O_loan_type=LOAN_TYPE_AUTO&bp=v3&init=1&intro=0&ICODE=2660&ESOURCEID=451070&SOURCE=451070&COMPCODE=3180&SITEID=&PARTNER=lendingtree&LOCID=14000&KWCODE=&SOURCEID=310&REFERER=&PROP_STATE_CONST=&ADDR_STATE_BO_CONST=&AUTO_STATE_ACQUIRED_CONST=&AUTO_OWNERSHIP_TYPE_CONST=5&LOAN_PURPOSE_CONST=";
        } else if ($("#loanType").val() == "2") {
            url = "https://secure.lendingtree.com/auto/ctl_Borrower.asp?page=loan_selection&verb=continue&O_loan_type=LOAN_TYPE_AUTO&bp=v3&init=1&intro=0&ICODE=2660&ESOURCEID=451070&SOURCE=451070&COMPCODE=3180&SITEID=&PARTNER=lendingtree&LOCID=14000&KWCODE=&SOURCEID=310&REFERER=&PROP_STATE_CONST=&ADDR_STATE_BO_CONST=&AUTO_STATE_ACQUIRED_CONST=&AUTO_OWNERSHIP_TYPE_CONST=2&LOAN_PURPOSE_CONST= ";
        } else if ($("#loanType").val() == "1") {
            url = "https://secure.lendingtree.com/auto/ctl_Borrower.asp?page=loan_selection&verb=continue&O_loan_type=LOAN_TYPE_AUTO&bp=v3&init=1&intro=0&ICODE=2660&ESOURCEID=451070&SOURCE=451070&COMPCODE=3180&SITEID=&PARTNER=lendingtree&LOCID=14000&KWCODE=&SOURCEID=310&REFERER=&PROP_STATE_CONST=&ADDR_STATE_BO_CONST=&AUTO_STATE_ACQUIRED_CONST=&AUTO_OWNERSHIP_TYPE_CONST=1&LOAN_PURPOSE_CONST= ";
        } else if ($("#loanType").val() == "4") {
            url = "https://secure.lendingtree.com/auto/ctl_Borrower.asp?page=loan_selection&verb=continue&O_loan_type=LOAN_TYPE_AUTO_REFI&bp=v3&init=1&intro=0&ICODE=2660&ESOURCEID=451070&SOURCE=451070&COMPCODE=3180&SITEID=&PARTNER=lendingtree&LOCID=14000&KWCODE=&SOURCEID=310&REFERER=&PROP_STATE_CONST=&ADDR_STATE_BO_CONST=&AUTO_STATE_ACQUIRED_CONST=&AUTO_OWNERSHIP_TYPE_CONST=4&LOAN_PURPOSE_CONST= ";
        }
        window.location = url;
    } else if (type == 2) {
        window.location = url;
    } else if (type == 3) {
        window.location = url + "?VIN=" + $("#carHistoryVIN").val();
    } else if (type == 4) {
        window.location = url + "&zip=" + $("#insuranceQuoteZip").val() + "&insured=" +
            ($("input[name*='HaveAutoInsurance']:checked").val() == "YesRadio" ? 'y' : 'n');
    } else {
        window.location = url;
    }
}

function updateBlogText(id) {
    $.ajax({
        url: 'ArticleHandler.ashx?ID=' + id,
        success: function(html) {
            $("#ArticleBodyLiteral").html(html);
        }
    });
}

function validatePhone(source, args) {
    args.IsValid = $("#homephone1").val().length == 3 && $("#homephone2").val().length == 3 && $("#homephone3").val().length == 4;
}

function validateCityState(source, args) {
    args.IsValid = $("#city").val().length > 0 && $("#state").val().length > 0;
}

function validateVIN(source, args) {
    var vin = $("#carHistoryVIN").val().toUpperCase();
    var isValid = vin.length == 17 && vin.indexOf(' ') == -1 && vin.indexOf('I') == -1 && vin.indexOf('O') == -1 &&
        vin.indexOf('Q') == -1;
    if (args) {
        args.IsValid = isValid;
    }
    else {
        return isValid;
    }
}

function isInt() {
    var code;
    var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if ((code > 47 && code < 58)) {
        return true;
    }
    return false;
}

/* Compare Queue functions */
function saveCompareQueueToCookie(idsInQueue) {
    var str = idsInQueue.join('_');
    $.cookie('compareVehicles', str);
}

function updateCompareQueue(cb) {
    var checkBox = $(cb);
    var flag = checkBox.attr('checked'); // whether check box is checked
    var curId = checkBox.parent().attr("class");
    var idsInQueue;

    // Parse compare queue in cookie
    var compareQueueStr = $.cookie('compareVehicles');
    if (compareQueueStr == null) {
        idsInQueue = [0, 0, 0];
    } else {
        idsInQueue = compareQueueStr.split('_');
    }

    if (flag) {
        // Set and save
        flag = false; // whether the queue has empty slot
        for (var i = 0; i < idsInQueue.length; ++i) {
            if (idsInQueue[i] == 0) {
                idsInQueue[i] = curId;
                flag = true;
                saveCompareQueueToCookie(idsInQueue);
                break;
            }
        }
        if (!flag) {
            checkBox.attr('checked', false);
            alert('The compare queue is full, please remove a vehicle first and add again!');
        }
    } else {
        // Clear and save
        for (var i = 0; i < idsInQueue.length; ++i) {
            if (idsInQueue[i] == curId) {
                idsInQueue[i] = 0;
                saveCompareQueueToCookie(idsInQueue);
                break;
            }
        }
    }
}
/* End - Compare Queue functions */