﻿$(function() {
    initialize();
});

// Initialize the page
function initialize() {
    
    // Bind events to the menu items for interactivity.
    $("ul#categories li").each(function() {
        // Click event to fold the item in or out
        $(this).bind('click', function(event) {
            if(event.target.tagName == "SPAN" || event.target.tagName == "IMG") {
                if($(this).find("table").is(':hidden')) {
                    $(this).find("img").attr("src", "../Pics/Static/fold-button.png");
                    $(this).find("img").attr("alt", "Verberg opties");
                    $(this).find("img").attr("title", "Verberg opties");
                    $(this).find("table").slideDown(300);
                } else if($(this).find("table").is(':visible')) {
                    $(this).find("img").attr("src", "../Pics/Static/expand-button.png");
                    $(this).find("img").attr("alt", "Toon opties");
                    $(this).find("img").attr("title", "Toon opties");
                    $(this).find("table").slideUp(300);
                }
            }
        });
        
        // Mouse enter event to change the style of the item
        $(this).find("span").bind('mouseenter', function(event) {
            $(this).css({
                cursor: 'pointer',
                textDecoration: 'underline',
                color: '#ff0000'
            });
        });
        // Mouse leave event to change the style of the item
        $(this).find("span").bind('mouseleave', function() {
            $(this).css({
                cursor: 'default',
                textDecoration: 'none',
                color: '#000000'
            });
        });
    });
    
    // Bind mouse enter and leave events to labels to change the style
    $("label").each(function() {
        $(this).bind('mouseenter', function() {
            $(this).css({
                cursor: 'pointer',
                textDecoration: 'underline',
                color: '#ff0000'
            });
        });
        
        $(this).bind('mouseleave', function() {
            $(this).css({
                cursor: 'default',
                textDecoration: 'none',
                color: '#000000'
            });
        });
    });
    
    // Fold in all of the items by default.
    $("ul#categories li.foldout table").each(function() {
        if(!$(this).hasClass("open")) {
            $(this).hide();
            $(this).parent().find("img").attr("src", "../Pics/Static/expand-button.png");
            $(this).parent().find("img").attr("alt", "Toon opties");
            $(this).parent().find("img").attr("title", "Toon opties");
        } else {
            $(this).show();
            $(this).parent().find("img").attr("src", "../Pics/Static/fold-button.png");
            $(this).parent().find("img").attr("alt", "Verberg opties");
            $(this).parent().find("img").attr("title", "Verberg opties");
        }
    });
    
    
}

function loadStock(articleId, colorId, sizeId, busy) {
    $.ajax(
        {
            type: 'post',
            url: '../XMLGetStock.ashx',
            data: {
                articleid: articleId,
                sizeid: sizeId == null ? '' : sizeId,
                colorid: colorId
            },
            dataType: 'xml',
            success: function(xml) { loadStock_success(xml,articleId,colorId,sizeId,busy);},
            error: function(xml) {}
        }
    );
}

function loadStock_success(xml, articleId, colorId, sizeId, busy) {
    if (sizeId == null) {
        var options = "";
        $(xml).find("sizes").children().each(function(){
            options += "<option value=\"" + $(this).attr("id") + "\">" + $(this).attr("text") + "</option>";
        });
        $("#articleSizes").html("<select id=\"ddlSizes\" class=\"list\" onchange=\"loadStock('" + articleId + "','" + colorId + "',this.value,'" + busy + "');\">" + options + "</select>");
        sizeId = $(xml).find("size:first").attr("id");
    }
    
    var offerPrice = $(xml).find("size[id=" + sizeId + "]").attr("offerprice");
    
    if (offerPrice != null) {
        $("#articlePrice").html(
            '<p class="price"><span class="offer">&nbsp;' + $(xml).find("size[id=" + sizeId + "]").attr("price") + '&nbsp;</span> ' + offerPrice + '</p>');
    } else {
        $("#articlePrice").html('<p class="price">' + $(xml).find("size[id=" + sizeId + "]").attr("price") + '</p>');
    }
    $("#articleStatus").html($(xml).find("size[id=" + sizeId + "]").attr("status"));
    if(Number($(xml).find("size[id=" + sizeId + "]").attr("stock")) <= 0) {
        $("#addToBasket").hide();
    } else {
        $("#addToBasket").show();
    }
}

function addToBasket(articleId) {
    var colorId = $("#ddlColors").val();
    var sizeId = $("#ddlSizes").val();
    
    $.ajax(
        {
            type: 'post',
            url: '../XMLAdd2Basket.ashx',
            data: {
                articleid: articleId,
                sizeid: sizeId == null ? '' : sizeId,
                colorid: colorId
            },
            dataType: 'xml',
            success: addToBasket_success,
            error: function(xml) { }
        }
    );
}

function addToBasket_success(xml) {
    if($(xml).find("basket").attr("result") == "success") {
        location.href = "Basket.aspx";
    } else {
    
    }
}

function processBasket(form, genericError, targetUrl, shopPrefix){

    $("#btnSubmit").attr("disabled", "disabled");
    $("#discountCouponAlert").css({"display":""});

    var selectedTitle = $('input[name=orderTitle]:checked').val();
    var toggleAdress = $('input[name=toggleAdress]:checked').val();
    var orderPayMethodValue = $('#orderPayMethod').val();
    var orderPayMethodText = $('#orderPayMethod:selected').text();
    var orderGrosAmount = $('input[name=amount]').val();
    
    //Get correct country
    //country = (form.elements["orderCountrySelection"].value == 0? "Nederland": form.elements["orderCountry"].value);
    var country = $('#countrySelection').val() == 0 ? "Nederland" : $('#country').val();
    //var countryDelivery = (form.elements["orderCountryDeliverySelection"].value == 0? "Nederland": form.elements["orderCountryDelivery"].value);
    var countryDelivery = $('#countryDeliverySelection').val() == 0 ? "Nederland" : $('#countryDelivery').val();
    
    var shipForeign = ((toggleAdress == 1 && $("#countryDeliverySelection").val() == 1) || (toggleAdress == 0 && $("#countrySelection").val() == 1));
    var giftPaper = ($('input[name=orderPaper]:checked').val() == 1);
    var registerNewsletter = ($('input[name=orderNews]:checked').val() == 1);

    var dataFromForm = 
        "orderTitle=" + selectedTitle +
        "&orderInitials=" + $("#initials").val() +
        "&orderInsertion=" + $("#insertion").val() +
        "&orderLastname=" + $("#lastName").val() +
        "&orderMail=" + $("#email").val() +
        "&orderPhone=" + $("#phone").val() +
        "&orderComments=" + $("#comments").val() +
        "&orderAddress=" + $("#address").val() +
        "&orderZip=" + $("#zip").val() +
        "&orderCity=" + $("#city").val() +
        "&orderCountry=" + country +
        "&orderNameDelivery=" + $("#nameDelivery").val() +
        "&orderAddressDelivery=" + $("#addressDelivery").val() +
        "&orderZipDelivery=" + $("#zipDelivery").val() +
        "&orderCityDelivery=" + $("#cityDelivery").val() +
        "&orderCountryDelivery=" + countryDelivery +
        "&toggleAdress=" + toggleAdress +
        "&orderPayMethodValue=" + orderPayMethodValue +
        "&orderPayMethodText=" + orderPayMethodText +
        "&orderGrosAmount=" + orderGrosAmount +
        "&orderCurrency=" + $("#currency").val() +
        "&orderLanguage=" + $("#language").val() + 
        "&shipForeign=" + ((shipForeign) ? 1 : 0) + 
        "&orderDiscountCoupon=" + $("#discountCoupon").val() +
        "&giftPaper=" + ((giftPaper) ? 1 : 0)+
        "&registerNewsletter=" + ((registerNewsletter) ? 1 : 0) + 
        "&orderPrefix=" + shopPrefix;
    
    $.ajax({
        type: "POST",
        url: "../XMLOrderBasket.ashx",
        data: dataFromForm,
        datatype: "xml",
        success: function(xml){onSuccess_processBasket(xml, form, targetUrl, shopPrefix);},
        error: function(){onError_processBasket(genericError);}
    })
}

function onSuccess_processBasket(xml, form, targetUrl, shopPrefix){
    var id = $(xml).find("orderId").text();
    var sha1 = $(xml).find("sha1").text();
    var qsVal = $(xml).find("id").text();
    var amount = $(xml).find("amount").text();
    var pspid = $(xml).find("pspid").text();
    
    if(id!=""&&sha1!=""){
        $('input[name=PSPID]').val(pspid);
        $('input[name=orderID]').val(shopPrefix + '' + id);
        $('input[name=SHASign]').val(sha1);
        $('input[name=amount]').val(amount);
        $('input[name=accepturl]').val(targetUrl+'?id='+qsVal);
        $('input[name=declineurl]').val(targetUrl+'?id='+qsVal);
        $('input[name=exceptionurl]').val(targetUrl+'?id='+qsVal);
        $('input[name=cancelurl]').val(targetUrl+'?id='+qsVal);
        // Automatic redirect to the relevant RIK payment method page
        switch(Number($('#orderPayMethod').val())){
            case 3:
                $('input[name=PM]').val('iDEAL');
                break;
            case 4:
                $('input[name=PM]').val('CreditCard');
                $('input[name=BRAND]').val('MasterCard');
                break;
            case 5:
                $('input[name=PM]').val('CreditCard');
                $('input[name=BRAND]').val('VISA');
                break;
        }
        var target = $(xml).find("target").text();
        $(form).attr('action', target);
        form.submit();
    }
    else {
        $(xml).find("outofstock").children().each(function(){
            $("#"+$(this).attr("key")).css({"display":"block"});
        });
        if($(xml).find("invalidCoupon").text()!=""){
            $("#discountCouponAlert").html($(xml).find("invalidCoupon").text());
            $("#discountCouponAlert").css({"display":"block"});
        }
    }
    $("#btnSubmit").removeAttr("disabled");
}
function onError_processBasket(genericError){
    alert("not okay!");
    $("#btnSubmit").removeAttr("disabled");
    alert(genericError);
}

function newSearch(artId){
    $("#contentLeft input[type=checkbox]").each(function() { 
        this.checked = false; 
    });
    $("#contentLeft #" + artId)[0].value="";
}
