﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
    $(".datepicker").datepicker({ defaultDate: +1, dateFormat: 'yy-mm-dd', duration: 'fast', firstDay: 1, monthNames: ['Januari', 'Februari', 'Mars', 'April', 'Maj', 'Juni', 'Juli', 'Augusti', 'September', 'Oktober', 'November', 'December'], dayNamesMin: ['Sö', 'Må', 'Ti', 'On', 'To', 'Fr', 'Lö'], beforeShowDay: $.datepicker.noWeekends });
    $("#productgroupmenu a[href='#']:last").click(function() {
        if ($(this).hasClass("ce")) {
            $(this).removeClass("ce");
            $(this).addClass("e");
        }
        else {
            $(this).removeClass("e");
            $(this).addClass("ce");
        }
        $(this).parent("li").next("li").toggleClass("Hide")
    });

    
    //window.setTimeout("HideWarningMessage()", 4000);
});

function HideWarningMessage(){
    $(".warning").hide("fast");
}



/// <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) {
        $("#jCartData", context).MiniCart({ onBuyEffect: function() {
            bounceCart();
        }
        });
    }
    //makes a form control able to post the form if it has one of this classes
    $(".submitOnChangeBehavior", context).bind("change", function() { $(this).submitParentForm(); });
    $(".submitOnClickBehavior", context).bind("click", function() { $(this).submitParentForm(); });

    $(".AjaxBehavior", context).AjaxLink();

    //    $(".LazyLoadBehavior", context).LazyLoad(); //this row must be after AjaxLink because of LazyLoad is dependent of AjaxLink
    $("#jCartData").MiniCart("registerBuyButttons", context); //collect all and new buy buttons
    //    $(".AjaxBehavior",context).AjaxLink("setDebug",true); //turn on debugging

    //enable as-you-type-search
    $("#id_searchinput").AsYouTypeSearch({ closeOnBlur: true, doPositioning: false, searchResult: "#jSearchResult", closeButton: "#search-close" });

}

function hideMenuNode() {
    //$("#menu_li");
    $("#menuitem").addClass("Hide");
    alert("hoppsan");
}

function SendToFriend() {
    //$("#jSendToFriendForm").submit();
    var form = $("#jSendToFriendForm");
    $.post(
        form.attr("action"),
        form.serialize(),
        function(data) {
            if (data.Status == "OK") {
                $("#jSendContent").addClass("displayNone");
                $("#jMailSuccess").removeClass("displayNone");
                form.empty;
                setTimeout(function() { location.reload(true) }, 1000);
            }
            else {
                $("#jSendContent").addClass("displayNone");
                $("#MailFailed").removeClass("displayNone");
                form.empty;
                setTimeout(function() { location.reload(true) }, 1000);
            }
        }
    )
}

function jMiniLoginLoad(isAjax, context, element) {
    if (isAjax) {
        //Check if the returned content contains any html
        if (context.html().indexOf("</") == -1) {
            data = eval('(' + context.html() + ')');
            if (data.Status && data.Status == "OK") {
                context.html('');
                document.location = data.Redirect;
                return false;
            }
        }
        else if ($("#highslide-farstagangen").length > 0) {
            var col = $("#col2");
            hs.htmlExpand(col.get(0), { contentId: 'highslide-farstagangen', width: '500', height: '450' });
            hs.onDimmerClick = function() {
                return false;
            }

        }
    }

    //$(".AjaxBehaviorMiniLogin").AjaxLink({ loadingClass: "jMiniLoginLoading" });
    $.log("Jminilogn end");
}

function jProductVariantsLoad(isAjax, context, element) {

    // check if hiddenfield exists, otherwise just exit.
    if (isAjax && $("#myCartQuantitySpan", context).length > 0 && $("#myCartQuantitySpan", context).html() != "0") {
        updateMiniCartQuantity($("#myCartQuantitySpan").html());
    }

    if (isAjax) {
        oTable = $('#bestallning').dataTable({
            "bJQueryUI": true,
            "bPaginate": false,
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": false,
            "bAutoWidth": false,
            "oLanguage": {
                "sProcessing": "Laddar...",
                "sLengthMenu": "Visa _MENU_ rader",
                "sZeroRecords": "Inga matchande resultat funna",
                "sInfo": "Visar _START_ till _END_ av totalt _TOTAL_ rader",
                "sInfoEmpty": "Visar 0 till 0 av totalt 0 rader",
                "sInfoFiltered": "(filtrerade från totalt _MAX_ rader)",
                "sInfoPostFix": "",
                "sSearch": "Sök:",
                "sUrl": "",
                "oPaginate": {
                    "sFirst": "Första",
                    "sPrevious": "Föregående",
                    "sNext": "Nästa",
                    "sLast": "Sista"
                }
            }
        });
    }
}

function bounceCart() {
    $("#smallcart").effect("bounce", { times: 3 }, 300);
}

function updateMiniCartQuantityFromServer() {
    $.post("/cart/CartQuantity", {}, function(data) { updateMiniCartQuantity(data) }, "text");
}

function updateMiniCartQuantity(quantity) {
    $("#jMiniCartQuantity").html(quantity);
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    bounceCart();
}

function submitSearch() {
    $("#jMiniSearchForm").submit();
}

function FirstLoginSubmit() {
    var form = $("#jFirstLoginForm");
    $.post(
        form.attr("action"),
        form.serialize(),
        function(data) {
            if (data.Status == "OK") {
                $("#jFirstLoginContent").addClass("displayNone");
                $("#jFirstLoginSuccess").removeClass("displayNone");
                setTimeout(function() { location.reload(true) }, 5000);

            }
            else {
                $("#jFirstLoginValidationContainer").html(data); //Update with result
            }
        }
    )
}

function ajaxifyForm(formId) {
    var form = $("#" + formId);
    form.bind("submit", function(event) {
        var ajaxLink = form.find(".jAjaxLink")              // Two ways to hook up ajax links, first a class selector inside the form tag...
        ajaxLink = ajaxLink.add("#" + formId + "AjaxLink"); // ...secondly, naming convention with ajaxlink outside of form tag.
        if (ajaxLink.length > 0) {
            event.preventDefault();
            ajaxLink.trigger('click');
        }
    });
}


function openAndPrintWin(pictureUrl) {
    $("#prodImage").jqprint();
}

// -----------------------------------------------------------------------
// Eros Fratini - eros@recoding.it
// jqprint 0.3
//
// - 19/06/2009 - some new implementations, added Opera support
// - 11/05/2009 - first sketch
//
// Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
// requires jQuery 1.3.x
//
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------

(function($) {
    var opt;

    $.fn.jqprint = function (options) {
        opt = $.extend({}, $.fn.jqprint.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);
        
        if (opt.operaSupport && $.browser.opera) 
        { 
            var tab = window.open("","jqPrint-preview");
            tab.document.open();

            var doc = tab.document;
        }
        else 
        {
            var $iframe = $("<iframe  />");
        
            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");
            var doc = $iframe[0].contentWindow.document;
        }
        
        if (opt.importCSS)
        {
            if ($("link[media=print]").length > 0) 
            {
                $("link[media=print]").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
                });
            }
            else 
            {
                $("link").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
                });
            }
        }
        
        if (opt.printContainer) { doc.write($element.outer()); }
        else { $element.each( function() { doc.write($(this).html()); }); }
        
        doc.close();
        
        (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
    }
    
    $.fn.jqprint.defaults = {
		debug: false,
		importCSS: true, 
		printContainer: true,
		operaSupport: true
	};

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    } 
})(jQuery);

