﻿

var pageScroll = null,
			scrollable = null,
			scrollSize = 24 + 8 + 2,

			currentPage = 1;


$(document).ready(function () {

	// Add pdf icons to pdf links
	$(".attachments a").addClass("download"); //default icon, might be overridden later    
	$(".attachments a[href$='.pdf']").addClass("pdf");
	$(".attachments a[href$='.mp3'], .attachments a[href$='.wav']").addClass("audio");
	$(".attachments a[href$='.doc'], .attachments a[href$='.rtf'], .attachments a[href$='.docx']").addClass("word");
	$(".attachments a[href$='.xls'], .attachments a[href$='.xlsx'], .attachments a[href$='.csv']").addClass("excel");
	$(".attachments a[href$='.jpg'], .attachments a[href$='.png'], .attachments a[href$='.gif'], .attachments a[href$='.tif'], .attachments a[href$='.tiff'], .attachments a[href$='.bmp']").addClass("picture");
	$(".attachments a[href$='.avi'], .attachments a[href$='.flv'], .attachments a[href$='.wmv'], .attachments a[href$='.mov'], .attachments a[href$='.divx'], .attachments a[href$='.mpeg']").addClass("video");
	$(".attachments a[href$='.zip'], .attachments a[href$='.rar']").addClass("zip");

	$("#blocker").click(closePopup);

	$(".dropShoppingLists").live('change', function () {
		$(".dropShoppingLists").val() == "" ? $(".newlist").show() : $(".newlist").hide();
	});

	pageScroll = $('div.page-scroll');
	scrollable = $('div.scrollable');

	makeShoppingScroll();
	wishlistPostPostback();

	userMessage = $('#userMessage');
	userMessageText = $('#userMessageText');
});

function setCartCount(amount) {
	amount = amount || 0;
	$("#cartItemCount").text('(' + amount + ')');
}


function addToCart(el) {
	var id = $(el).parents(".big-product").data("pid");
    var amount = $(el).parents(".big-product").find("input.buy-count").val();
    var size = $(el).parents(".big-product").find("input.buy-size").val();
    log(amount);
    log(size);
    addProductToCart(id, amount, size);
}



function addProductToCart(id, amount, size) {
	amount = amount || 1;
	size = size || -1;
    //set amount
    $("#shoppingcart input:hidden:first").val(amount);
    $("#shoppingcart input#hiddenSize").val(size);


    //set id and click add
    $("input.addToCart").next().val(id);
    $("input.addToCart").click();
}




function fillTextBox(place) {
    switch (place) {
        case 'name':
            $(".delName").val($(".newName").val());
            if ($(".invoName").length) {
                $(".invoName").val($(".newName").val());
            }
            break;
        case 'surname':
            $(".delSurname").val($(".newSurname").val());
            if ($(".invoSurname").length) {
                $(".invoSurname").val($(".newSurname").val());
            }
            break;
        default:
            break;
    }
};

function wishlistPostPostback() {

    if ($("#shoppingcart .items > div").height() > $("#shoppingcart .items").height()) {
        $("#shoppingcart .shoppinghelp").animate({ height: 50 })
    }
}

function makeShoppingScroll() {
    $("#shoppingcart .items > div").draggable({
        axis: "y",
        stop: function (event, ui) {
            var $this = $(this);
            if (($this.height() <= $this.parent().height() && ui.position.top < 0) || ui.position.top > 0) $this.animate({ top: 0 }, "normal");
            else if ($this.height() > $this.parent().height() &&
                     $this.parent().height() - ($this.position().top + $this.height()) > 0) {

                $this.animate({ top: $this.parent().height() - ($this.height()) }, "normal");

            }
        },
        snap: true
    }).bind("mousedown", function () { $(this).css("cursor", "move"); })
            .bind("mouseup", function () { $(this).css("cursor", "auto"); });
}

function wishlistitemadded(p, sid) {
    $(".dropShoppingLists").val() == "" ? $(".newlist").show() : $(".newlist").hide();
    $("#success").html("Produktet " + p + " ble lagt til i ønskelisten. <a href='/onskelister?sid=" + sid + "'>Trykk her for å gå til ønskelisten</a>").fadeIn();
}

function closePopup() {
    $("#blocker").fadeOut();
    $(".popup").fadeOut(function () {
        $("#success").hide();
        $(".popup span.msg").html("");
    });
}

var preloadPagesCount = 5;

function GotoPrev() {

    GotoPage(getCurrentPage() - 1);
    return false;
}
function GotoNext() {

    GotoPage(getCurrentPage() + 1);
    return false;
}

var GotoPage = function (pageNumber) {
    log("Goto page", pageNumber, "from page " + currentPage);


    if ($(".scrollable a:nth-child(" + pageNumber + ")").length == 0) return;

    var right = pageNumber > currentPage;



    var foundPage = $(".pages .page_" + (pageNumber)).length;

    var scroller = function () {
        doScrolling(pageNumber);
    }

    log("moving " + (right ? "right" : "left"));

    if (pageNumber > 0 && !foundPage) {
        log("Page not found, need to get more pages..");

        var arr = window.currentString.split('&');
        arr.pop();
        arr.pop();
        arr.push("pages=" + preloadPagesCount);
        arr.push("pagenumber=" + pageNumber);
        var newstring = arr.join('&');
        showProducts(newstring, scroller);
    } else {
        scroller();
    }

};
function doScrolling(pageNumber) {

    //must reselect here or else newx will be 0
    var newx = $(".pages .page_" + (pageNumber)).prevAll().length * 966;
    log("scrolling pages to new x: ", newx);
    $('div.pages').stop().animate({ scrollLeft: newx }, 1000, function () {
        animating = false;
    });
    if (pageNumber > 0) {
        window.location.hash = "p/" + pageNumber;
        setPagersCss(pageNumber);
        scrollable[0].scrollLeft = scrollSize * (getCurrentPage() - 3)
    }

}
function getCurrentPage() {

    return currentPage = parseInt(window.location.hash.split('/')[1]) || 1;
}

function reloadProductPageAjax() {
    //remove all pages
    $(".allpages").empty();

    //remove product details
    $(".big-product").remove();

    LoadPages(window.q, true);
}
//product pages js starts here:
function LoadPages(querystring, reload) {
    log("loadPages(" + querystring + ")");
    var pageNumber = getCurrentPage();
    if (pageNumber > 0 && !reload) {
    	querystring += "&pages=" + 7 + "&pagenumber=" + pageNumber;
    }

    //querystring = encodeURI(querystring);

    window.q = querystring;
    var showProductsFn = function () {
        showProducts(querystring, function () { doScrolling(getCurrentPage()); });

    };
    // find a product, make it show. this is how my day go!
    if (typeof (productID) != "undefined" && productID > 0) {
        log("Showing product page with id", productID);
        // find a product, make it show. this is how my day go!
        if (typeof (productID) != "undefined" && productID > 0) {

            showProduct(productID, showProductsFn);

        }

    } else {
        showProductsFn();
    }

}


function removeFromCart(el) {
    $(".removefromcart").prev().val($(el).data("pid"));
    $(".removefromcart").click();
};
function uiShowProduct(el) {

    // position of big product previews
    //el.css({ 'top': $('div.pages').position().top });

    el.children('div.top-utils a').click(function (e) {
        var $this = $(this);
        $this.parent().parent().fadeOut('fast');
    });

    el.fadeIn(function () {

        $(".big-products .big-product").not(el).fadeOut();
    });
};
function showProduct(id, callback) {
   
	if (typeof (id) === 'undefined') { return; }

	var p = $(".big-products .big-product[data-pid=" + id + "]");

	if (p.length == 0) {
	    $.get("/ajax/productinfo.aspx?pid=" + id + "&" + window.currentString, function (html) {

	        var el = $(html).filter("#bigProduct");	        

	        $(".big-products").append(el);
	        $('a.fancybox').fancybox();
	        uiShowProduct(el);
	        el.find(".ellipsis").ellipsis();
	        if (callback)
	            callback();
	    });

    } else {
        uiShowProduct(p);
        if (callback)
            callback();
    }


};
function closeProduct(el) {
    $(el).parents(".big-product").fadeOut();
};


function scrollshow() {
    var el = $("#shoppingcart .items > div").css("top", -123);

    el.animate({ top: 0 }, "normal");
    wishlistPostPostback();
};


function showProducts(querystring, callback) {

    log("showing product pages", querystring);
    if (querystring == null) return;
    $("#loader:hidden").fadeIn();
    $.get("/ajax/productpage.aspx?" + querystring, function (html) {
        try {

            var dhtml = $(html);


            var pagecounter = dhtml.filter(".pager");
            if (pagecounter.length > 0 && $(".scrollable a").length == 0) {

                $(".scrollable").html(pagecounter.html());
                var anchors = $("div.page-scroll div.scrollable a");
                if (anchors.length < 7) {
                    var width = 0;
                    anchors.each(function (i, e) { width += scrollSize; }).parent().parent().width(width);
                }
            }

            var newpages = dhtml.find(".page");

            log(newpages);

            if (newpages.length == 0) {
                log("no pages found");
                return;
            }

            log(newpages.length, " pages found - adding to view");
            newpages.each(function (i, e) {
                log(i);
                var page = $(e);
                var pagenumber = page.attr("class").substring(page.attr("class").indexOf("_") + 1);

                if ($(".allpages .page").length == 0) {
                    $(".pages .allpages").append(page);
                }
                else {
                    findPageClosestPage(pagenumber, page);
                }
            });



            window.currentString = querystring;

            $(".allpages").width($(".allpages .page").length * $(".allpages .page").width());

            //reset scrollpost to what it was before getting new ajax
            $('div.pages').scrollLeft(820 * $(".allpages .page_" + getCurrentPage()).prevAll().length);


            if (callback) setTimeout(callback, 100);


        } catch (e) {
            alert(e);
        } finally {
            $("#loader").fadeOut();
        }
    });

};

function findPage(number) {
    return $(".allpages .page_" + number);
}

function findPageClosestPage(number, newpage) {
    number = parseInt(number);
    log("findPageClosestPage ", number);
    var match = number;
    var stopnumber = number + 5;
    var start = number - 5;
    start = start >= 0 ? start : 1;
    number = start;
    var page = undefined;
    var closest = 1000;
    var foundMatch = number;
    log("starting at ", start, "stopping at " + stopnumber);
    while (number < stopnumber) {

        var foundpage = findPage(number);
        //   log("searching number ", number, " stop is " + stopnumber, "match is", match, foundpage);
        if (foundpage.length) {
            var newclosest = 0;
            if (number > match)
                newclosest = number - match;
            else newclosest = match - number;

            if (newclosest < closest) {
                closest = newclosest;
                page = foundpage;
                foundMatch = number;
            }
        }

        number++;
    }
    log("found " + foundMatch);
    if (page) {
        if (foundMatch == match) {
            //allready exists
            log("allready exists");
        } else {
            if (foundMatch > match) {
                page.before(newpage);
            } else {
                page.after(newpage);
            }
        }
    }

    log("closest page", page);
    return page;
}




window.hasConsole = !(typeof (console) === 'undefined');
function log() {
 
	if (window.hasConsole) {
	//	console.log(arguments);
	}
}

function setPagersCss(pageNumber) {
    log("setting page number " + pageNumber);
    var pagerlinks = $(".page-scroll .scrollable a");
    pagerlinks.removeClass("selected").filter(":nth-child(" + pageNumber + ")").addClass("selected");

}

function getProductPages(pages, c) {



    $.get("/ajax/productpage.aspx?pages=" + pages + "&c=" + c, function (html) {
        var el = $(html);
        log(el);
        $(".allpages").children().first().prepend(el);
    });




};

function openWishlistbox(pid) {
    $(".dropShoppingLists").val() == "" ? $(".newlist").show() : $(".newlist").hide();
    if (pid != null) {
        $("#wishlistbox input[type=hidden]").val(pid);
        showBlocker("wishlistbox");
    }
}

function openRabattkodebox() {
    showBlocker("rabattkodebox");
}

function showLeveringsbetingelser() {
    showBlocker("leveringsbetingelserBox");
    return false;
}

//generell popupfunksjon, som resizer og viser blocker + popup til id
function showBlocker(id) {
	$(".popup").fadeOut();
    var popup = $("#" + id);
    var winheight = $(window).height();
    var blocker = $("#blocker").height(winheight).fadeIn();
    var top = blocker.height() - popup.height();
    popup.css({ top: top / 2 }).fadeIn();
}



(function ($) {
    $.fn.ellipsis = function () {
        var moreInfo = "<a href='javascript:;' class='more' >Mer informasjon</a>";
        return this.each(function () {
            var el = $(this);
            var didIt = false;

            if (el.css("overflow") == "hidden") {
                var text = el.html();
                var backup = text;
                var multiline = el.hasClass('multiline');
                var t = $(this.cloneNode(true))
					.hide()
					.css('position', 'absolute')
					.css('overflow', 'visible')
					.width(multiline ? el.width() : 'auto')
					.height(multiline ? 'auto' : el.height())
					;

                el.after(t);

                function height() { return t.height() > el.height(); };
                function width() { return t.width() > el.width(); };

                var func = multiline ? height : width;

                while (text.length > 0 && func()) {
                    text = text.substr(0, text.length - 1);
                    t.html(text + "...");
                    didIt = true;
                }
                el.html(t.html());
                t.remove();

                if (didIt) {
                    $(moreInfo).insertAfter(el).data("text", backup).click(function () {


                        el.html($(this).data("text"));
                        el.height("auto");
                        $(this).remove();

                    });
                }
            }
        });
    };
})(jQuery);

var showRequest = function (id) {
	$('#hiddenRequestID').val(id);
	showBlocker('requestPopup');
};

var showFriend = function (id) {
	$('#hiddenFriendID').val(id);
	showBlocker('friendPopup');
};

var userMessage = null;
var userMessageText = null;
var showUserMessage = function (text) {
	userMessageText.html(text);
	userMessage.show();
	setTimeout(function () {
		userMessage.fadeOut();
	}, 4000);
};
