﻿/// <reference path="~/Resources/js/jquery-1.2.6-intellisense.js" />
/// <reference path="~/Resources/js/cart.js" />
/// <reference path="~/Resources/js/common.js" />

$(function() {
    // Add to cart handler
    $("button.buy").click(function() { return addProductToCart($(this)); });

    $(".product-margin").spacer(".product-margin .Item", 230, 0);

    $(".product .resources a.image").click(function() {
        $(".product .picture .popup img").attr("src", $(this).attr("href"));
        $(this).addClass("active").siblings().removeClass("active");
        return false;
    });

    $(".product .picture .popup, .product .resources button.zoom").click(function() {
        var link = jQuery.trim(DetermineLinkByScreenResolution());

        if ($(this).is('.zoom')) {
            CreateAndShowPopupForZoomButton(link);
        } else {
            CreateAndShowPopup(link);
        }
    });

    $('.accessories .accessory').click(function() {
        var a = $(this).find('a');
        var id = a.attr('href').substring(1);

        a.toggleClass('open');
        $('.accessories .details.' + id).toggle();
        updateProductPageHeight();

        return false;
    });

    // Add large picture zoom on accessory
    $('.accessories .details .accessoryPopupclass').click(function() {
        //var link = $(this).attr("rel");
        var link = $(this).attr("href");
        CreateAndShowPopupForAccessory(link);
    });

    // Add scrolling functionality to add-to-cart-panel
    $('#added-to-cart-panel').scrollFollow({ offset: -70 });

    // Add accessory to cart handler
    $('.accessories .buy-accessory').click(function() {
        if (!$(this).hasClass('disabled'))
            addAccessoryToCart($(this));
        return false;
    });

    validateAccessories();
});

function CreateAndShowPopup(link) {
    $("a[rel='popupLink']").attr("href", link);
    $("a[rel='popupLink']").colorbox({ opacity: 0.4 });

    AddCloseEventToCloseButtonAndRemoveOld();
    AddCloseEventToPopupPicture();
}

function CreateAndShowPopupForAccessory(link) {
    $("a[href='" + link + "']").colorbox({ opacity: 0.4 });  
    
    AddCloseEventToCloseButtonAndRemoveOld();
    AddCloseEventToPopupPicture();
}

function CreateAndShowPopupForZoomButton(link) {
    $("a[rel='popupLink']").attr("href", link);
    $("a[rel='popupLink']").colorbox({ opacity: 0.4 });
    $("a[rel='popupLink']").click();

    AddCloseEventToCloseButtonAndRemoveOld();
    AddCloseEventToPopupPicture();
}

function AddCloseEventToPopupPicture() {
    $("#cboxContent").css("cursor", "pointer");
    $("#cboxContent").click(function() {
        $.fn.colorbox.close();
    });
}

function AddCloseEventToCloseButtonAndRemoveOld() {
    $("#cboxClose").remove();
    $("#colorbox").prepend("<div id=\"cboxClose\">close</div>");

    $("#cboxClose").click(function() {
        $.fn.colorbox.close();
    });
}

function DetermineLinkByScreenResolution() {
    var link = $(".product .resources a.image.active").attr("rel");
    var topInterval = 1150;
    var middleInterval = 950;
    var bottomInterval = 750;
    var lowestPictureHeight = 512;

    $(".all-product-images li").each(function() {
        var currentPictureHeight = ParseImageHeight($(this).text());
        var currentUri = $(this).text();
        var screenHeight = screen.height;
        //var screenHeight = 799;

        if (IteratingOverActivePictureLinks(link, currentUri)) {
            if (CheckForBigImage(screenHeight, topInterval, currentPictureHeight, middleInterval)) {
                link = currentUri;
            }
            if (CheckForMiddleImage(screenHeight, topInterval, middleInterval, bottomInterval, currentPictureHeight)) {
                link = currentUri;
            }
            if (CheckForSmallImage(screenHeight, middleInterval, bottomInterval, currentPictureHeight, lowestPictureHeight)) {
                link = currentUri;
            }
            if (CheckForLowestPictureHeight(screenHeight, bottomInterval, currentPictureHeight, lowestPictureHeight)) {
                link = currentUri;
            }
        }

    });
    return link;
}

function ParseImageHeight(imageText) {
    var numberOfCharsToStrip = imageText.indexOf('.');
    var parsed = imageText.substring(numberOfCharsToStrip + 1);
    return parseInt(parsed);
}

function IteratingOverActivePictureLinks(link, currentUri) {
    var activePictureCharsToStrip = link.indexOf('.');
    var activePictureResourceId = link.substring(activePictureCharsToStrip - 36, activePictureCharsToStrip);

    var currentIteratingImageCharsToStrip = currentUri.indexOf('.');
    var currentIteratingImageLink = currentUri.substring(currentIteratingImageCharsToStrip - 36, currentIteratingImageCharsToStrip);

    return activePictureResourceId == currentIteratingImageLink;
}

function CheckForBigImage(screenHeight, topInterval, currentPictureHeight, middleInterval) {
    return screenHeight >= topInterval && currentPictureHeight >= middleInterval;
}

function CheckForMiddleImage(screenHeight, topInterval, middleInterval, bottomInterval, currentPictureHeight) {
    return screenHeight >= middleInterval && screenHeight < topInterval && currentPictureHeight >= bottomInterval;
}

function CheckForSmallImage(screenHeight, middleInterval, bottomInterval, currentPictureHeight, lowestPictureHeight) {
    return screenHeight >= bottomInterval && screenHeight < middleInterval && currentPictureHeight <= bottomInterval && currentPictureHeight > lowestPictureHeight;
}

function CheckForLowestPictureHeight(screenHeight, bottomInterval, currentPictureHeight, lowestPictureHeight) {
    return screenHeight < bottomInterval && currentPictureHeight < bottomInterval && currentPictureHeight >= lowestPictureHeight;
}

function addProductToCart(button) {
    if (!addToCartForButton(button))
        return false;
        
    showAddToCartPanel();
    showAccessoryTipPanel();
    return false;
}

function addAccessoryToCart(button) {
    if (!addToCartForButton(button))
        return false;
        
    showAddToCartPanel();
    return false;
}

function addToCartForButton(button) {
    var itemNo = button.attr("rel");
    //var itemPrice = $(".price", button.parent()).text().replace(".", "");
    var itemPrice = 0;
    
    if (button.hasClass("buy-accessory")) {
        itemPrice = parseInt(button.parents("tr").find("td.price").text().replace(".", ""));
    } else {
        itemPrice = $(".price", button.parent()).text().replace(".", "");
    }
    
    var itemPriceListId = $(".price-list-id", button.parent()).text();
    if (typeof (itemNo) == 'undefined') {
        return false;
    }

    VVM.cart.add({ id: itemNo, price: itemPrice, priceListId: itemPriceListId });
    VVM.renderCart();
    
    return true;
}

function showAddToCartPanel() {
    var panel = $("#added-to-cart-panel");
    var pos = $("#mini-cart").outerOffset();
    var offset = panel.outerWidth() - $("#mini-cart").outerWidth();
    panel.css({ "left": pos.left - offset })
         .data("doHide", panel.css("display") == "none")
         .show();

    setTimeout(function() {
        if (panel.data("doHide"))
            panel.fadeOut();
        panel.data("doHide", true);
    }, 5000);
}

function showAccessoryTipPanel() {
    var panel = $("#accessory-tip-panel");
    var accessories = $(".accessories");
    if (accessories.length == 0) return;
    
    var accessoryOffset = panel.outerWidth() - accessories.outerWidth() + 10;
    var leftOffset = accessories.outerOffset().left - accessoryOffset;
    var topOffset = accessories.outerOffset().top - panel.outerHeight() - 15;
    panel.css({ "left": leftOffset, "top": topOffset })
         .data("doHide", panel.css("display") == "none")
         .show();

    setTimeout(function() {
        if (panel.data("doHide"))
            panel.fadeOut();
        panel.data("doHide", true);
    }, 7000);

    enableBuyAccessory();
}

function enableBuyAccessory() {
    $('.accessories .buy-accessory')
        .removeClass('disabled');
}

function validateAccessories() {
    if ($('#cart').length > 0) {
        enableBuyAccessory();
        return;
    }

    var productId = $('.product button.buy').attr('rel');
    var priceListId = $('.price-info .price-list-id').text();

    var item = VVM.cart.getItem({ id: productId, priceListId: priceListId });
    if (item != null) {
        enableBuyAccessory();
    }
}

function updateProductPageHeight() {
    var pictureHeight = $(".picture").height();
    var infoHeight = $(".info").height();

    if (pictureHeight > infoHeight) {
        $(".product").spacer(".product .picture", 500, 20);
    } else {
        $(".product").spacer(".product .info", 500, 20);
    }
}


