﻿/// <reference path="jquery-1.3.1-vsdoc.js" />
/// <reference path="Stats.js" />

$.postJSON = function (url, data, callback) {
    $.post(url, data, callback, "json");
};

//if (!window.console) {
//    var console = {
//        init: function () {},
//        hide: function () {},
//        show: function () {},
//        log: function (o) {},
//        clear: function () {}
//    }   
//}

// Firebug degrade
if (!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function () { };
}

$(document).ready(function() {

    $.ajaxSetup({ cache: false });
    
    //SetupDisplayStyleLink()

    LoadFrontBanners();
    LoadFrontNewsletter();

    LoadImageLists();
    LoadDeliveryInfoTip();
    LoadBuyLinks();
    LoadBuyForm();
    LoadGoRandomProductLinkTracking();
    LoadRobotSearchClickTracking();
    SetupSelectedGroupInfo();

    LoadTagsTracking();

    LoadCategoryTree();
});


function SetupDisplayStyleLink() {
    if ($.cookie("fullwidth")) {
        $("body").addClass("fullwidth");
    }


    $("#fullwidthLink").click(function () {
        if ($.cookie("fullwidth")) {
            $.cookie("fullwidth", null);
            $("body").removeClass("fullwidth");
            return false;
        }
        else {
            $.cookie("fullwidth", "true");
            $("body").addClass("fullwidth");
            return false;
        }
    });
}

function LoadCategoryTree() {
    $(".treeview.productcategory").treeview({
        collapsed: true,
        animated: "normal",
        prerendered: true
    });
}

function LoadFrontNewsletter() {

    $("#newsletter-subscribe form").submit(function() {
        TrackNewsletterSubscribe();
    });

    $("#newsletter-unsubscribe form").submit(function() {
        TrackNewsletterUnsubscribe();
    });

    $("#newsletter-unsubscribe").hide();

    $("#newsletter-unsubscribelink").show();

    $("#newsletter-unsubscribelink").click(function() {

        $("#newsletter-unsubscribelink").hide(0)
        $("#newsletter-unsubscribe").show(0);
        $("#newsletter-unsubscribe #email").focus();
        
        return false;
    });
}

function LoadRobotSearchClickTracking() {
    $("#robot-search-button").click(function() {
        TrackRobotSearched();
    });
}

function LoadFrontBanners() {
    $(document).ready(function() {

        $("#frontbanners a").click(function () {
            TrackFrontBannerClicked($(this).attr("title"));
        });


        $("#frontbanners").innerfade({
            speed: 'slow',
            timeout: 7000,
            type: 'sequence',
            containerheight: '200px'
      	});
      

    });
}


function LoadGoRandomProductLinkTracking() {
    $("#GoRandomProductLink").click(function() {
        TrackRandomProductClicked();
    });
}

function LoadTagsTracking() {
    $(".product-tags a").each(function() {
        $(this).click(function() {
            TrackProductTagClicked($(this).text());
        });
    });
}

function SetupSelectedGroupInfo() {
    // Add onchange on selector
    $("input[name='groupoption']").click(function() {
        ShowSelectedGroupInfo(false);
    });

    // Preload selected
    ShowSelectedGroupInfo(true);
}


function ShowSelectedGroupInfo(startup) {
    var selectedId = $("input[name='groupoption']:checked").val();

    if (!startup) {
        var selected = $("label[for=" + selectedId + "]").text()
        TrackProductOptionSelected(selected);
    }

    $(".group-info").hide(0);
    $(".info-for-" + selectedId).show(0);
    return false;
}
/*
    $(".group-info").slideUp(0, function() {
        $(".info-for-" + selectedId).slideDown(0);
        return false;
    });

*/
/*** 
Simple jQuery Slideshow Script
Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, 
not responsible for anything, etc.  Please link out to me if you like it :)
***/

function SlideSwitch() {
    var $active = $('.product-slideshow IMG.active');

    if ($active.length == 0) $active = $('.product-slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next()
        : $('.product-slideshow IMG:first');

    $active.addClass('last-active');

    $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 100, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval("SlideSwitch()", 300);
});

function LoadBuyLinks() {

    $(".group-buy-link").each(function () {

        $(this).click(function () {
            groupid = $(this).attr("groupid");

            var requestUrl = "/ProduktGruppe/VisMiniGruppe?id=" + groupid;
            $.fn.colorbox({ href: requestUrl, innerWidth: "590px", innerHeight: "60%" });

            return false;
        });
    });

    $(".buy-link").each(function() {
        $(this).click(function() {
            productid = $(this).attr("productid");
            AddToBasket(productid, 1);
            return false;
        });
    });
}


function LoadBuyForm() {

    $(".buy-form").each(function () {
        var form = $(this);

        $(this).find("#addbutton").click(function () {

            productid = form.find("#productid").val();
            quantity = form.find("#antal").val();

            var optionData = form.find(".product-options input, .product-options select").serialize()

            parsedQuant = parseInt(quantity);

            if (isNaN(parsedQuant)) {
                parsedQuant = 1;
                form.find("#antal").val(1);
            }

            AddToBasket(productid, parsedQuant, optionData);

            return false;
        });
    });
}


function LoadImageLists() {

    $(".product-media a, a.DetailDefaultPictureLink").click(function() {
        TrackProductMediaOpened($(this).attr("href"));
    });
    
    $(".product-media a, a.DetailDefaultPictureLink").colorbox(
        {
            transition: "elastic",
            maxWidth: "75%",
            maxHeight: "75%",
            next : "Næste",
            previous : "Forrige",
            close : "Luk",
            current : "Billede {current} af {total}"
        }
    );

}


////////////////////////////////
// Basket

function UpdateProductNotifier(publicid, newQuantity, callback) {

    var basketinfo = $(".product" + publicid + " .basket-status");
    var quantity = basketinfo.find(".product-quantity");

    if (basketinfo.is(':visible')) {

        quantity.text(newQuantity);
        $(this).dequeue();

    }
    else {
        
        quantity.text(newQuantity);
        basketinfo.slideDown();
    }

    $(".product-mini.product" + publicid + " .notifier .product-quantity").text(newQuantity);
    $(".product-mini.product" + publicid + " .notifier").slideDown(800);   
}



function ShowBasket(callback) {
    var basketBox = $("#basketbox");
    var hidden = basketBox.is(":hidden");

    if (hidden) {
        basketBox.slideDown();
    }
    else 
    {
        $("#basket-updatetext").fadeOut(200, function () {
            $("#basket-info").fadeIn(200, callback);
        });
    }
}



function AddToBasket(publicid, quantity, optionsdata) {
    $.postJSON("/Kurven/Tilfoej/?productid=" + publicid + "&antal=" + quantity, optionsdata, function (data) {

        if (data.ErrorMessage != null) {
            ShowBasketError(publicid, data.ErrorMessage);
        }
        else 
        {
            UpdateProductNotifier(publicid, data.Quantity);
            UpdateBasket(data);
            TrackProductAddedBasket(quantity, productid);
        }

    });
}

String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

function ShowBasketError(publicid, error) {
    var errorinfo = $(".product" + publicid + " .add-error");
    var errormessage = errorinfo.find("span.error-message");

    errormessage.text(error);

    errorinfo.slideDown();

    setTimeout(function () { errorinfo.slideUp() }, 2000);

}

function UpdateBasket(data) {

    if (data != null) {

        var basketText = GetBasketText(data.TotalQuantity, data.FormattedPrice);
        $("#basketbox span.content").html(basketText);

        //            if (data.Quantity == 0) {
        //                $("#basket-quantity-label").hide();
        //                $("#basket-total-label").hide();
        //                $("#basket-empty-label").show();
        //            }
        //            else {
        //                $("#basket-total-label").find(".price").html(data.FormattedPrice);
        //                $("#basket-total-label").show();

        //                $("#basket-quantity-label").find(".quantity").html(data.TotalQuantity);
        //                $("#basket-quantity-label").show();

        //                $("#basket-empty-label").hide();
        //            }


        //            $("#basket-text .vat").html(data.VatText);

        ShowBasket();
    }
    else {
        $.postJSON("/Kurven/Json", function (data) {
            var basketText = GetBasketText(data.TotalQuantity, data.FormattedPrice);
            $("#basketbox span.content").html(basketText);

            ShowBasket();
        });
    }

  
}


function LoadDeliveryInfoTip()
{
    $(".product-mini .product-deliveryinfo").each(
		function() {
		    image = $(this).find("img");
		    message = $(this).find(".Status");

		    cssclass = "InventoryToolTip " + $(this).find(".Status").attr("class");

		    image.easytooltip(message, cssclass);
		}
	);
}

function LoadStandartFlashVideo(filename, previewfile, target, id, autoplay) {
    LoadSizableFlashVideo(filename, previewfile, target, id, 1, autoplay);
}

function LoadSizableFlashVideo(filename, previewfile, target, id, size, autoplay) {
    if (size == 1) {
        LoadFlashVideo(filename, previewfile, target, id, "320", "184", "240", autoplay)
    }
}

function LoadFlashVideo(filename, previewfile, target, id, width, height, displayheight, autoplay) {
    var so = new SWFObject("/Data/Media/mediaplayer.swf", id, width, height, "7", "#202020");
    so.addParam('allowfullscreen', 'true');
    so.addParam('allowscriptaccess', 'always');
    so.addVariable('file', filename);
    so.addVariable('image', previewfile);
    so.addVariable('width', width);
    so.addVariable('height', height);
    so.addVariable('autostart', autoplay);
    so.addVariable('displayheight', displayheight);
    so.addVariable('frontcolor', '0xFFFFFF');
    so.addVariable('backcolor', '0x202020');
    so.addVariable('lightcolor', '0xFF0000');
    so.addVariable("javascriptid", id);
    so.addVariable("enablejs", "false");
    so.addVariable('screencolor', '0x202020');
    so.addVariable('showdigits', 'false');
    so.addVariable('repeat', 'true');
    so.addVariable('usefullscreen', 'false');
    so.write(target);
} 
