


function executeHandlers() {
    handleRelAttr();
    handleProduct();

}


function handleRelAttr() {

    $("a[rel='external']")
      .bind("click", function () {
          $("#login-box").css({ display: "none" });
      });

    $("a[rel='open-login']")
      .bind("click", function () {
          // $('#login-box').load('/account/logon', function (html) { $('#login-box')[0].value = html; });
          $('#login-box').slideDown('fast');
          // $("#login-box").css({display:"block"});
      });

    $("a[rel='close-login']")
      .bind("click", function () {
          $('#login-box').slideUp('fast');
      });

    $("a[rel='open-sizechart']").find("img").css({ "display": "inline" });
    $("a[rel='open-sizechart']")
      .bind("click", function () {
          $("#showcase").hide();
          $(".size-chart").css({ display: "block" });
          return false;
      });

    $("a[rel='close-sizechart']")
      .bind("click", function () {
          $("#showcase").show();
          $(".size-chart").css({ display: "none" });
          return false;
      });

    $("a[rel='external']")
      .bind("click", function () {
          this.target = "_blank";
      });
}



function handleProduct() {


    var options = {
        zoomWidth: 270,
        zoomHeight: 500,
        xOffset: 20,
        yOffset: 0,
        position: "right",
        title: false,
        showPreload: true,
        showEffect: 'fadein',
        fadeInSpeed: 'slow'
    };

    if ($(".zoomer").length > 0)
        $(".zoomer").jqzoom(options);

    $("#showcase ul li a").live("click", function () {

        $("#preview img").attr("src", $(this).attr("href"));
        $("#preview a").attr("href", $(this).attr("rel"));
        //        $("#viewfull").attr("href", $(this).attr("rel"));



        return false;

    });


    if ($("#viewfull").length > 0)
        $("#viewfull").colorbox({ width: "100%", height: "100%", iframe: true });


    //  $("#viewfull").live("click", function () {
    //   $(this).attr("href", $("#preview a").attr("href"));

    //      $(this).colorbox({ iFrame: "true",transition: "fade", width: "100%", height: "100%" });
    //        return false;
    //     });

    $("#preview a")
      .live("click", function () {
          return false;
      });



}



(function ($) {

    $.fn.innerfade = function (options) {
        return this.each(function () {
            $.innerfade(this, options);
        });
    };

    $.innerfade = function (container, options) {
        var settings = {
            'animationtype': 'fade',
            'speed': 'normal',
            'type': 'sequence',
            'timeout': 2000,
            'containerheight': 'auto',
            'runningclass': 'innerfade',
            'children': null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length - i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function () {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
                var last = Math.floor(Math.random() * (elements.length));
                setTimeout(function () {
                    do {
                        current = Math.floor(Math.random() * (elements.length));
                    } while (last == current);
                    $.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
            } else if (settings.type == 'random_start') {
                settings.type = 'sequence';
                var current = Math.floor(Math.random() * (elements.length));
                setTimeout(function () {
                    $.innerfade.next(elements, settings, (current + 1) % elements.length, current);
                }, settings.timeout);
                $(elements[current]).show();
            } else {
                alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
            }
        }
    };

    $.innerfade.next = function (elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function () {
                removeFilter($(this)[0]);
            });
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function () {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
    if (element.style.removeAttribute) {
        element.style.removeAttribute('filter');
    }
}


// Cookie Plugin
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';

        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function () {



    // Cufon Font Replacement
    if (lang == "en-US") {
        Cufon.replace("#nav0 a, #nav2 a", { fontFamily: "Helvetica Neue", hover: true });
        Cufon.replace("h1, h2, h4, .button, .size-chart th, .product-nav .subnav li", { fontFamily: "Helvetica Neue" });
    }

    // Submit Wishlist Removal Form
    $(".wishlist-remove").submit(function () {

        $.post("/wishlist/remove", $(this).serialize(),
         function () {
         }
         , 'json');
        var row = $(this).parent().parent();
        row.addClass('removing').fadeOut(1000);

        return false;
    });

    // Editable text fields
    if ($('.quantity-editable').length > 0)
        $('.quantity-editable').editable($(this).parent().attr("rel"));


    $('#add-note-button').click(function () {

        $('#add-note').slideToggle();

    });

    $('#AddressSelection').change(function () {

        // Ajax call to retrieve address
        $.post("/addressbook/get/", { "id": $(this).val() },
   function (data) {

       // Update address fields
       $("#ShippingAddress1").val(data.Line1);
       $("#ShippingAddress2").val(data.Line2);
       if (data.Line2 == null) { $("#ShippingAddress2").val(""); }

       $("#ShippingCity").val(data.City);
       $("#ShippingPostalCode").val(data.PostCode);
       $("#ShippingCountryCode").val(data.CountryCode);

   }, "json");

    });


    //    $("a.confirm-delete").easyconfirm({ locale: { title: 'Are you sure you want to delete this address?', button: ['No', 'Yes']} });

    executeHandlers();




    if ($('a.cart-update').length > 0)
        $('a.cart-update').colorbox({ href: $(this).attr('href') });






    $("#pageSize")
      .bind("change", function () {
          var pageSize = $(this).val();
          var url = $(this).attr("rel");

          $.get('/Home/SetPageSizeInCookie/' + pageSize, function (data) {
              //$.cookie('3aps', $(this).val());

              if (url != undefined)
                  location.replace(url);
              else
                  location.reload(true);
          });


      });

    if ($('#pageSize').length > 0) {

        if ($.cookie('3aps') != null && $.cookie('3aps') != '')
            $('#pageSize').val($.cookie('3aps'));
        else
            $('#pageSize').val('9'); //default
    }

    if ($('#RememberMe').form)
        $('#RememberMe').rules('remove', 'required');

    $("#nav0 li").hover(function () {
        $(this).addClass("hover");
        //$('ul:first', this).css('visibility', 'visible');
        $('ul:first', this).css('display', 'inline');

    }, function () {

        $(this).removeClass("hover");
        //$('ul:first', this).css('visibility', 'hidden');
        $('ul:first', this).css('display', 'none');

    });


    if ($("#accordion").length > 0)
        $("#accordion").accordion({
            autoHeight: false,
            navigation: true
        });
});

function changeCurrency(newCurrencyCode) {
    $.get('/ChangeCurrency/' + newCurrencyCode, function (data) {
        location.reload();
    });
}

function changeLanguage(newLanguageCode) {
    $.get('/ChangeLanguage/' + newLanguageCode, function (data) {
        location.reload();
    });
}

function InitHoverImages(){
    
    var offsetX = 20;
    var offsetY = 10;

    $('img.productThumbnail').live("mouseenter", function (e) {
       
        if (!userAuthorized) return;

        var src = $(this).parent().attr('rel').replace('/small', '/large');

        $('<img id="largeImage" src="' + src + '" alt="image" />')
        .css({ 'position': 'absolute', 'top': e.pageY + offsetY, 'left': e.pageX + offsetX, 'height': '400px', 'border': '1px solid #000' })
        .appendTo('body');
    });

    $('img.productThumbnail').live("mouseleave", function (e) {
        $('#largeImage').remove();
    });


    $('img.productThumbnail').live("mousemove", function (e) {
        $('#largeImage').css({ 'top': e.pageY + offsetY, 'left': e.pageX + offsetX });
    });
}
