﻿//
//  ON PAGE LOAD
//

$(document).ready(function () {


    // restritcs all inputs with a class of 'numeric' to numbers only
    $(".numeric").numeric();


    // select all text in textbox on selection
    $(".selectAllOnFocus").focus(function () { $(this).select(); });
    $(".selectAllOnFocus").mouseup(function (e) {
        e.preventDefault();
    });

    //
    //  HOVER
    //


    // set as selected
    setSelectedMenuItem = function (elToSet) {

        var t = $(elToSet);
        var imgSrc = t.attr('src');

        // get the file extension and use that in the replace
        if (t.attr('src') != undefined) {
            if (imgSrc.indexOf('_over') == -1) {
                var fileExt = imgSrc.substring(imgSrc.length - 4);
                t.attr('src', imgSrc.replace("" + fileExt + "", "_over" + fileExt));
                $(this).css('cursor', 'pointer');
            }
        }

        // remove the hover class of the img
        $(elToSet).removeClass("hover");

        // remove the hover event binding
        $(elToSet).unbind('mouseenter mouseleave');
    }

    // generic hover image effect
    var hoverMouseOver = function () {
        var t = $(this);
        var imgSrc = t.attr('src');

        // get the file extension and use that in the replace
        if (t.attr('src') != undefined) {
            if (imgSrc.indexOf('_over') == -1) {
                var fileExt = imgSrc.substring(imgSrc.length - 4);
                t.attr('src', imgSrc.replace("" + fileExt + "", "_over" + fileExt));
                $(this).css('cursor', 'pointer');
            }
        }
    }
    var hoverMouseout = function () {
        var t = $(this);
        if (t.attr('src') != undefined) {
            t.attr('src', t.attr('src').replace('_over', ''));
        }
    }
    $('.hover').hover(hoverMouseOver, hoverMouseout).click(hoverMouseout);

    // preload images from the hover class automatically
    $('.hover').each(function () {
        // get each of the hover class images on the pagse
        var t = $(this);
        // get the source of each of these images
        var imgSrc = t.attr('src');
        if (imgSrc != undefined) {

            // get the file extension and use that in the replace
            var fileExt = imgSrc.substring(imgSrc.length - 4);
            var newfilesource = imgSrc.replace("" + fileExt + "", "_over" + fileExt);

            jQuery("<img>").attr("src", newfilesource);
        }
    });

    // define the preloader function
    jQuery.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", arguments[i]);
        }

    }


    // clear the find a dealer selector when selected
    $(function () {

        $('.txtSearchBoxFooter').focus(function () {
            $(this).val('');
        });
    });


    // SUBURB FINDER

    //    $('.postcodeSearch').keyup(function () {

    //    });

    var prevValForAutoSuggest = "";

    $(".postcodeSearch").keyup(function (e) {
        //window.alert(prevValForAutoSuggest);
        // store the text field value
        if (($('.postcodeSearch').val() != prevValForAutoSuggest) && ($('.postcodeSearch').val().length > 1)) {
            postCodeLookup();
            prevValForAutoSuggest = $('.postcodeSearch').val();
        }

    });

    $(".postcodeSearch").keydown(function (e) {

        if (e.keyCode == 38) { // up
            var selected = $(".selected");
            $(".resultsList li").removeClass("selected");
            if (selected.prev().length == 0) {
                selected.parent().children().last().addClass("selected");
            } else {
                selected.prev().addClass("selected");
            }
        }

        if (e.keyCode == 40) { // down
            var selected = $(".selected");
            $(".resultsList li").removeClass("selected");
            if (selected.next().length == 0) {
                selected.parent().children().first().addClass("selected");
            } else {
                selected.next().addClass("selected");
            }
        }


        if (e.keyCode == 13) { // enter
            if ($(".resultsList").is(":visible")) {
                selectOption();
            } else {
                $(".resultsList").show();
            }

        }

    });

    function selectOption() {
        var locString = "../Find-A-Dealer.aspx?loc=" + $(".selected a").text() + "";
        window.location.href = locString;
    }

    postCodeLookup = function () {

        var txtSearch = $('.postcodeSearch').val();

        if (txtSearch.length > 1) {

            $('.resultsPanel').show();

            var dataString = "{'prefixText' : \"" + txtSearch + "\", 'count' : \"10\"}";

            $.ajax({
                type: "POST",
                url: "AutoCompleteTownWS.asmx/GetCompletionList",
                data: dataString,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var results = msg.d;
                    // clear the results
                    $('.resultsList').html('');


                    // check if we got a result
                    if (results == "") {
                        $('.resultsList').append("<span style='padding-left:240px; color: #EC1C24; font-size:12px;'>No result was found for this postcode or suburb.</span>");
                    }
                    else {
                        // we got result(s) back, show it
                        var tempStr = "";
                        tempStr = "<ul>";
                        for (var i = 0; i < results.length; i++) {
                            var rowClass = i % 2 != 0 ? "alt" : "";
                            //$('.resultsList').append('<li><a class="' + rowClass + '" href="../Find-A-Dealer.aspx?loc=' + results[i] + '">' + results[i] + '</a></li>');
                            tempStr += '<li><a class="' + rowClass + '" href="?loc=' + results[i] + '">' + results[i] + '</a></li>';
                        }
                        tempStr += "</ul>";

                        // append the dynamically built ul/li
                        $('.resultsList').append(tempStr);


                        // add the selected class to the first item
                        $(".resultsList li:first").addClass("selected");

                        // set up the mouseover handler
                        $(".resultsList ul li a").mouseover(function () {
                            $(".resultsList li").removeClass("selected");
                            $(this).parent().addClass("selected");
                        }).click(function () {
                            selectOption();
                        });
                    }
                }
            });
        }
        else {
            $('.resultsPanel').hide();
            $('.resultsList').html('');
        }
    }

    // handle keyboard nav on the find a dealer page


    // initialisation of the colour palette
    $("#color_car_holder img").first().addClass("active").css("height", "450px");
    $("#color_palette li").first().addClass("active");
    $("#color_name").html($("#color_palette li.active").attr("title"));

    // Showroom Color Swapper
    $(".color_car").not(".active").hide(); //fade all but the active one
    $(".color_swatch").each(function () {
        $(this).click(function () {
            if (!$(this).hasClass('active')) {
                //update car
                var old_active = $("#color_car_holder img.active")
                $(old_active).css("z-index", 1).removeClass("active");

                // TODO: needs some 'tweaking' for alpha issues
                // see http://lidevserver.isuzuute2011.dev/Showroom-4x4-Space-Cab-Chassis-SX-Overview.aspx

                if (jQuery.browser.msie) {

                    $(".color_car[id*=" + this.id + "]")
                    .css("z-index", 2)
                    .addClass("active").css("height", "450px")
                    .show();
                    $(old_active).hide();

                } else {

                    $(".color_car[id*=" + this.id + "]")
                    .css("z-index", 2)
                    .addClass("active")
                    .fadeIn(200, function () { $(old_active).fadeOut(50); });

                }


                //update swatch
                $("#color_palette li.active").removeClass("active");
                $(this).addClass("active");
            }
        });
        $(this).hover(function () {
            $("#color_name").html($(this).attr("title"));
        }, function () {
            $("#color_name").html($("#color_palette li.active").attr("title"));
        });
    });

    //add popup link to
    $(".price_prefloader a").colorbox({ html: $("#set_pricing").contents(), width: "750px", height: "520px", close: "CLOSE <span class='cboxCloseX'>X</span>" });


    $(".showroom_gallery li a").colorbox({ photo: true,
        href: function () { return $(this).find("img").attr("src").replace('thumbs', 'full') },
        title: function () { return $(this).find("span").text() },
        close: "CLOSE <span class='cboxCloseX'>X</span>",
        rel: "gallery",
        next: "<span> </span>",
        previous: "<span> </span>",
        width: "820px",
        height: "720px"
    });

    $(".emaildealer_colorbox").colorbox({ inline: true,
        href: $("#emailDetailsForm").contents(),
        title: "Email dealer Details",
        close: "CLOSE <span class='cboxCloseX'>X</span>",
        width: "520px",
        height: "220px"
    });

    $("#colorbox").appendTo('form:first');


});
