﻿/// <reference path="jquery-1.3.2-vsdoc.js" /> // jQuery Intellisense

$(document).ready(function() {

    var windowSizeArray = ["width=620,height=650",
                               "width=620,height=450,scrollbars=yes"];

    $('.newWindow').click(function(event) {

        var url = $(this).attr("href");
        var windowName = "popUp"; //$(this).attr("name");
        var windowSize = windowSizeArray[$(this).attr("rel")];

        window.open(url, windowName, windowSize);
        event.preventDefault();

    });

    // FORM VALIDATION ( ref: http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/ )
    // Initialize validation on the entire ASP.NET form.
    $("form").validate({
        //errorPlacement: function(error, element) {
        //    error.appendTo(element.parent("div.rowinput").next("div.rowerror"));
        //},
        // This prevents validation from running on every
        //  form submission by default.
        onsubmit: false
    });

    // Search for controls marked with the causesValidation flag 
    //  that are contained anywhere within elements marked as 
    //  validationGroups, and wire their click event up.
    $('.validationgroup .causesvalidation').click(ValidateAndSubmit);

    // Select any input[type=text] elements within a validation group
    //  and attach keydown handlers to all of them.
    $('.validationgroup :text').keydown(function(evt) {
        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            ValidateAndSubmit(evt);
        }
    });

    // Label inside input « Marc Watts Web Development:
    // http://www.marcwatts.com.au/web-development/label-inside-input.html
    (function($) { $.fn.extend({ labelToInput: function() { return this.each(function() { var id = $(this).attr('id'); $('label').each(function() { if ($(this).attr('for') == id) { $(this).css('display', 'none'); if ($('#' + id).val() == '') { $('#' + id).val($(this).html()); } } }); $(this).focus(function() { $('label').each(function() { if ($(this).attr('for') == id) { if ($(this).html() == $('#' + id).val()) { $('#' + id).val(''); } } }); }); $(this).blur(function() { var id = $(this).attr('id'); if ($(this).val() == '') { $('label').each(function() { if ($(this).attr('for') == id) { $('#' + id).val($(this).html()); } }); } }); }); } }); })(jQuery);

    // CART
    $(".activatecode label").inFieldLabels({ fadeOpacity: 0.1 });

    // PRODUCT COLORS
    var str_orig = $("#proddetails .productgallery img").attr("src"); // store original product image

    /*
    Replace jquery selector with replacement image name
    */
    function swap_img(jq_original, str_replace) {
        var img = new Image();

        // wrap our new image in jQuery, then:
        $(img).load(function() { // once the image has loaded, execute this code
            $(this).css("opacity", "0"); // set the image transparent by default
            $(jq_original).replaceWith(this);
            $(this).animate({ opacity: 1.0 }, 500); // fade our image in to create a nice effect
        }).error(function() { // if there was an error loading the image, react accordingly
            // if there was an error loading the image, react accordingly
        }).attr('src', str_replace); // *finally*, set the src attribute of the new image to our image
    }

    $(".product-color").hover(function(event) {
        var str_replace = $(this).attr("src");
        var eos = str_replace.indexOf("_color");
        str_replace = str_replace.substring(0, eos) + "_1.jpg";

        if (str_replace !== str_orig)
            swap_img("#proddetails .productgallery img", str_replace);
    });

    $(".product-color").mouseout(function(event) {
        if ($("#proddetails .productgallery img").attr("src") !== str_orig)
            swap_img("#proddetails .productgallery img", str_orig);
    });

    $(".gallery-select .gallery-item a").click(function(event) {
        str_orig = $(this).attr("href");
        swap_img("#proddetails .productgallery img", str_orig);
        event.preventDefault();
        $(this).parents(".gallery-item").siblings(".gallery-item").children("a").removeClass("gallery-active");
        $(this).addClass("gallery-active");
        // set summary
        //alert($(this).parents(".gallery-items").children(".gallery-item").children().index(this)+1);
        var tmp_summary_text = gallery_summary_text.replace("{%SUM%}", $(this).parents(".gallery-items").children(".gallery-item").length);
        tmp_summary_text = tmp_summary_text.replace("{%CUR%}", $(this).parents(".gallery-items").children(".gallery-item").children().index(this) + 1);
        $(this).parents(".gallery-select").children(".gallery-summary").html(tmp_summary_text); //gallery_summary_text;
    });

    $('.pack-leaflet-trigger').click(function(event) {
        if ($('#pack-leaflet-container').attr('src') != $(this).attr('href'))
            $('#pack-leaflet-container').attr('src', $(this).attr('href'));
        $('#pack-leaflet-container').toggle();
        event.preventDefault();
    });

    $('.footnote-marker a').hover(function(event) {
        event.preventDefault();
        var p = $(this).position();
        $($(this).attr('href')).parent().toggle().css({ 'top': p.top + 20, 'right': 0 });
    });

    // CR
    $('.cr-container a.cr-item[id]').click(function(e) {
        var href = $(this).attr("href");
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/Misc/CRHandler.ashx",
            data: "id=" + $(this).attr('id'),
            complete: function() {
                location.href = href;
            }
        });
    });

});

// Uniqe radiobutton select in repeaters
function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}

function ValidateAndSubmit(evt) {
    // Ascend from the button that triggered this click event 
    //  until we find a container element flagged with 
    //  .validationGroup and store a reference to that element.
    var $group = $(evt.currentTarget).parents('.validationgroup');

    var isValid = true;

    // Descending from that .validationGroup element, find any input
    //  elements within it, iterate over them, and run validation on 
    //  each of them.
    $group.find(':input').each(function(i, item) {
        if (!$(item).valid())
            isValid = false;
    });

    // If any fields failed validation, prevent the button's click 
    //  event from triggering form submission.
    if (!isValid)
        evt.preventDefault();
    return isValid;
}
