﻿/// <reference path="Plugins/jquery-1.3.2-vsdoc.js" />

//change to your needs 
//please read the section defaults on each plugin of available customizations


//run MasterLoad on the whole page after document ready
$(document).ready(function() {
    //show a progress bar during each ajax request
    $("#loading").ajaxStart(function() {

        $(".dropdown").hide();
        $("#loading").show();
    });
    $("#loading").ajaxStop(function() {
        $(this).hide();
        $(".dropdown").show();
    });

    //enable as you type search //searchResult: "#sdsds"
    $("#SearchTextBox").AsYouTypeSearch({ doPositioning: false, closeOnBlur: true, closeButton: "#AsYouTypeSearchResultCloseButton", ignoreText: $("#SearchTextBox").attr("hintText") });

    //enable ajax on mini cart
    $("#cartContainer").MiniCart({ onBuyEffect: function() {
        $("#cartContainer").fadeOut().fadeIn();
        //        if ($("#CART_BUYCONFIRMATION").html() != "") {
        //            alert($("#CART_BUYCONFIRMATION").html());
        //        }
    }
    });

    //        $("#top-menu").TopMenu(); TODO create top menu and left menu plugins if needed
    //        $("#SectionMenu").SectionMenu();
    $(".AOMenu > li").click(function() { $(this).toggleClass("expanded"); });
    $(".AOMenu a").click(function(event) { event.stopPropagation(); }); //dont collapse the menu

    // Check so we show vy the user cant add product that are minimum qunatity and bulkpack.
    checkQuantity();

    // Focus username.
    $("a.thickbox").click(function() {
        $("input[name='username']").focus();
    });

    var options = {
        target: '#jImageUpload',
        success: function() { $('#uploadImage').ajaxForm(options); }
    };
    if ($('#uploadImage').size() > 0) {
        $('#uploadImage').ajaxForm(options);
    }

    $('#uploadImage').ajaxForm(options);
    $(".closeThickboxBehavior").click(function() {
        tb_remove();
    });
    $(".cancelThickbox").click(function() {
        if ($("#editAddress").size() > 0) {
            $(".address-add").slideUp();
            $(".disabled").hide();
        }
        else {
            self.parent.tb_remove();
            $(".disabled").hide();
        }
    });

//    $("#InvoiceAddress_PostalCode").keyup(function(e) {

//    $.post("/SelfRegister/GetValidCitys", { zipCode: $(this).val(), country: countryIsoCode }, function(data) {
//            if (data != null) {
//                alert(data);
//                SetValue(data.city, "#InvoiceAddress_City");
//                SetValue(data.state, "#InvoiceAddress_State");
//                SetValue(data.county, "#InvoiceAddress_County");
//                SetValue(data.countryisocode, "#InvoiceAddress_CountryIsoCode");

//                if (data.city == undefined && $('#InvoiceAddress_City_temp').length)
//                    SetValue("", "#InvoiceAddress_City");

//                if (data.state == undefined)
//                    SetValue("", "#InvoiceAddress_State");

//                if (data.county == undefined)
//                    SetValue("", "#InvoiceAddress_County");

//                if (data.countryisocode == undefined)
//                    SetValue("", "#InvoiceAddress_CountryIsoCode");

//                if ($('#InvoiceAddress_City_temp').length) {
//                    //Ok view for InvoiceAddress_City
//                    if ($('#InvoiceAddress_City_temp').val()) {
//                        setOkView('InvoiceAddress_City_temp');
//                        setOkView('InvoiceAddress_PostalCode');
//                    }
//                    else {

//                        setErrorView('InvoiceAddress_City_temp');
//                        setErrorView('InvoiceAddress_PostalCode');
//                    }
//                }

//                if ($('#InvoiceAddress_City').length) {

//                    if ($('#InvoiceAddress_City').val()) {
//                        setOkView('InvoiceAddress_City');
//                    }
//                }

//                if ($('#InvoiceAddress_State').val()) {
//                    setOkView('InvoiceAddress_State');
//                }
//                else {
//                    setErrorView('InvoiceAddress_State');
//                }

//                if ($('#InvoiceAddress_County').val()) {
//                    setOkView('InvoiceAddress_CountyMandatory');
//                }
//                else {
//                    setErrorView('InvoiceAddress_CountyMandatory');
//                }


//            }


//        });

//    });
    //    $(".numericCode").numeric();
    //    $('.dropdown li').click(function() {
    //        $(this).siblings("li").removeClass("selected");
    //        $(this).addClass("selected");

    //        var selectedID = $(this).attr("id");
    //        var option = $(this).parent().parent().next(".variantAttribute");
    //        option.val(selectedID);
    //        $(option).change();
    //        //alert($(option).html());
    //    });
    //    $('.dropdown .arrow').click(function() {
    //        $(this).siblings("ul").children("li.selected:not").toggle("scroll");
    //    });

    //CART
    $("#CartComment").focus(function() {
        $("#CartName").removeClass("hide");
        $("#CartCommentSubmit").removeClass("hide");
    });
    $("#CartComment").blur(function() {
        var val = $("#CartComment").text();
        if ($(this).attr("hinttext") == $(this).val()) {
            $("#CartName").addClass("hide");
            $("#CartCommentSubmit").addClass("hide");
        }
    });
    $(".showHideHistory").click(function() {
        $(".cart-comment-edit").toggleClass('hide');
        $(".cart-comment-add").toggleClass('hide');
        $(".cart-comment-delete").toggleClass('hide');

        SetHistory();
    });
    SetHistory();

    $('#target').keyup(function() {
        alert('Handler for .keyup() called.');
    });
});
function SetHistory() {
    var actions = $("#cart-comments").children(".action").size();
    if (actions == 0) {
        $(".showHideHistory").children(".on").hide();
        $(".showHideHistory").children(".off").hide();
    }
    else if ($(".action").hasClass('hide')) {
        $(".showHideHistory").children(".on").show();
        $(".showHideHistory").children(".off").hide();
    } else {
        $(".showHideHistory").children(".off").show();
        $(".showHideHistory").children(".on").hide();
    }
}
function mainAreaLoad(isAjax, context) {
    //CART
    $("#CartComment", context).focus(function() {
        $("#CartName", context).removeClass("hide");
        $("#CartCommentSubmit", context).removeClass("hide");
    });
    $("#CartComment", context).blur(function() {
        var val = $("#CartComment']", context).text();
        if ($(this).attr("hinttext") == $(this).val()) {
            $("#CartName", context).addClass("hide");
            $("#CartCommentSubmit", context).addClass("hide");
        }
    });
    if (isAjax) {
        tb_init('a.thickbox, area.thickbox, input.thickbox');

        $(".showHideHistory", context).click(function() {
            $(".cart-comment-edit", context).toggleClass('hide');
            $(".cart-comment-add", context).toggleClass('hide');
            $(".cart-comment-delete", context).toggleClass('hide');

            SetHistory();
        });
        SetHistory();
    }
}

/// <summary>
/// This function runs on every load and after all ajax request made by AjaxLink plugin.
/// if you want to rebind events or other stuff after a ajax update on a specific div please create a function called dividLoad with arguments isAjax, context
/// </summary>
///<param name="isAjax">true if after a ajax request</param>
///<param name="context">parent jquery object so the function dont have to be evaluated on the whole document after a ajax update</param>
function MasterLoad(isAjax, context) {
    //PLEASE NOTE dont forger the ,context argument or the plugin will be created on the whole page after each ajax request
    if (!isAjax) {
        //code to execute on the specified div only the first time when no ajax
        //enable ajax on mini cart
        $("#cartContainer", context).MiniCart({ onBuyEffect: function() {
        }
        });
    }
    //makes a form control able to post the form if it has one of this classes
    $(".submitOnChangeBehavior", context).each(function() { $(this).data("val", $(this).val()).bind("change", function() { $.log("data:" + $(this).data("val") + ",val:" + $(this).val()); if ($(this).data("val") != $(this).val()) { $(this).data("val", $(this).val()).submitParentForm(); } }); });

    $(".submitOnClickBehavior", context).bind("click", function() { $(this).submitParentForm(); });

    $(".HoverBehavior", context).Hover();

    $(".JHoverProduct", context).mouseenter(function(e) {
        var element = this;
        if ($(element).parents(".detail").length == 0) {
            $(".JHoverProductMore", element).removeClass("Hide");
            PositioningMore(element, e.pageX, e.pageY);
            if (!$(element).hasClass("Loaded")) {
                $(element).addClass("Loaded");
                $(".JHoverProductLink", element).AjaxLink("load");
            }
        }
    }).mouseleave(function() {
        var element = this;
        $(element).removeData("mx").removeData("my");
        $.log("out");
        $(".JHoverProductMore", element).addClass("Hide");
    });
    //    $(".numericCode").numeric();

    $(".HintBehavior", context).Hint();
    $(".AjaxBehavior", context).AjaxLink();
    $(".AjaxMoreBehavior", context).AjaxLink({ enableHistory: false, loadedFunction: function(isAjax, context) {
        if (isAjax) {
            var element = $(context).parents(".JHoverProduct")[0];
            window.setTimeout(function() { PositioningMore(element); }, 0);
            window.setTimeout(function() { PositioningMore(element); }, 2000); //JHoverProductMore should have fixed width and height so dont lazy image loading resizes the div
            /*            window.setTimeout(function() { PositioningMore(context); }, 5000); */
        }
    }
    });
    //    $(".LazyLoadBehavior", context).LazyLoad(); //this row must be after AjaxLink because of LazyLoad is dependent of AjaxLink
    $("#cartContainer").MiniCart("registerBuyButttons", context); //collect all and new buy buttons
    //    $(".AjaxBehavior",context).AjaxLink("setDebug",true); //turn on debugging  

    if (jQuery().MultiSubmitForm) {
        $("Form.MultiSubmit").MultiSubmitForm();
    }

    // Close thickbox
    $(".closeThickboxBehavior").click(function() {
        tb_remove();
    });
    $(".cancelThickbox").click(function() {
        if ($("#editAddress").size() > 0) {
            $(".address-add").slideUp();
            $(".disabled").hide();
        }
        else {
            self.parent.tb_remove();
            $(".disabled").hide();
        }
    });

    //CART
    $("#CartComment").focus(function() {
        $("#CartName").removeClass("hide");
        $("#CartCommentSubmit").removeClass("hide");
    });
    $("#CartComment").blur(function() {
        var val = $("#CartComment").text();
        if ($(this).attr("hinttext") == $(this).val()) {
            $("#CartName").addClass("hide");
            $("#CartCommentSubmit").addClass("hide");
        }
    });
}
function PositioningMore(element, mx, my) {
    $.log("over top:id:" + $(element).attr("id") + "class:" + $(element).attr("class") + "wheight" + $(window).height() + "scrollTop" + $(window).scrollTop());

    if (typeof ($(element).data("mx")) != "undefined") {
        mx = $(element).data("mx");
    }
    if (typeof ($(element).data("my")) != "undefined") {
        my = $(element).data("my");
    }

    /*    if (typeof (mx) != "undefined") {
    $(element).data("mx", mx);
    }
    else*/
    {
        if (typeof ($(element).data("mx")) != "undefined") {
            mx = $(element).data("mx");
        }
        else {
            mx = $(element).offset().left;
        }
    }
    /*    if (typeof (my) != "undefined") {
    $(element).data("my", my);
    }
    else */
    {
        if (typeof ($(element).data("my")) != "undefined") {
            my = $(element).data("my");
        }
        else {
            my = $(element).offset().top;
        }
    }

    $.log("mx:" + mx + ",my:" + my);
    //    var x = mx + 63;
    //    var y = my + 23;
    var x = mx + 246;
    var y = my + 0;


    if ($(element).parents(".searchResult").length != 0) {
        var parent = $(element).parents(".searchResult")[0];
        x -= $(parent).offset().left;
        y -= $(parent).offset().top
    }
    if (x + $(".JHoverProductMore", element).width() > $(window).width() + $(window).scrollLeft() - 20) {
        x = $(window).width() - $(".JHoverProductMore", element).width() - $(window).width() + $(window).scrollLeft() - 20;
    }
    if (y + $(".JHoverProductMore", element).height() > $(window).height() + $(window).scrollTop() - 20) {
        y = $(window).height() + $(window).scrollTop() - $(".JHoverProductMore", element).height() - 20;
    }

    //    $(".JHoverProductMore", element).css({ top: (y - $(element).offset().top) + "px", left: (x - $(element).offset().left) + "px" });
    $(".JHoverProductMore", element).css({ top: y + "px", left: x + "px" });

}
/*
function ProductContainerLoad(isAjax, context) {

$("option[value=]", context).addClass("disabledOption").attr("disabled", "disabled");
$("select", context).change(function(event) {
if ($(this).val() == '') {
$(this).val($("option[class!=disabledOption]:first", this).attr("value"));
}
});
var repost = false;
$("select", context).each(function() {
if ($(this).val() == '') {
repost = true;
$(this).val($("option[class!=disabledOption]:first", this).attr("value"));
}
});

//ful lösning  i sista fall om datat inte stämde.....


}
*/

//kommenteras bort för den nya inloggningen, ta tillbaka ifall den nya inte fungerar som den ska
//function loginPartialLoad(isAjax, context, element) {
//    if (isAjax) {
//        //Check if the returned content contains any html
//        if (context.html().indexOf("</") == -1) {
//            data = eval('(' + context.html() + ')');
//            $.log("JSON tillbaka");
//            if (data.Status && data.Status == "OK") {
//                context.html('');
//                document.location = data.Redirect;
//                return false;
//            }
//        }
//    }

//    //$(".AjaxBehaviorMiniLogin").AjaxLink({ loadingClass: "jMiniLoginLoading" });
//    $.log("Jminilogn end");
//}

function checkQuantity() {
    $("#bulkpackError").hide();
    // If we type in a new value in quantity.

    $(".productQuantityInput").keyup(function() {

        var isvalid = true;
        var quantity = $(this).val();
        var bulkpack = $(this).siblings("#bulkpack").val();
        var minimumQuantity = $(this).siblings("#minimumQuantity").val();


        if (!(quantity % bulkpack == 0)) {
            isvalid = false;
        }

        if (bulkpack == 0) {
            isvalid = false;
        }
        var quantityFloat = parseFloat(quantity);
        var minimumQuantityFloat = parseFloat(minimumQuantity);
        if (quantityFloat < minimumQuantityFloat) {
            isvalid = false;
        }
        if (isvalid == true) {
            $("#bulkpackError").hide();
        } else {
            $("#bulkpackError").show();
        }
    });

}
function GetQueryStringValue(name) {
    var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) {
        return 0;
    }
    return results[1] || 0;
};

