jQuery.preloadImages = function() { for(var i = 0; i<arguments.length; i++) { jQuery("<img>").attr("src", arguments[i]); } }

function pageReload () { var sURL = unescape(window.location.pathname); window.location.href = sURL; }

function purchase (i,oldValue) {
    if ($("#tr_prdc_"+i+" input[id^=qty]").val() == 0) { alert (terms[6]); return; }
    serializedData = $("#tr_prdc_"+i+" input[id^=qty], #tr_prdc_"+i+" input[name^=nh]").serialize();
    $.ajax ({
        type: "POST",
        url: dynamicUrlAjax + '/basket/basketadd?time=' + new Date().getTime(),
        data: serializedData,
        success: function (result) {
            var l = result.length; if (l > 0) { if (l > 5) { alert (result); $("[id^=qty"+i+"_]").val(oldValue); } return; }
            newValue = $("#tr_prdc_"+i+" input[id^=qty]").val();
            addedText= $("#added___"+i).text();
            $("#added___"+i).prepend(newValue + " ").removeClass('visib').animate({opacity:1},1000,function() { 
                $(this).fadeTo('slow', 0, function() { $(this).addClass('visib').text(addedText); }); 
            });
            $("#tr_prdc_"+i+" [id^=stockbasket_]").html('<a href="'+sslBaseUrl+'/checkout"><img src="'+ sslBaseUrl +'/gfx/basket2.gif" alt="" /></a>');
        },
        complete: function () { basketLoad (); }
    });
}

function alreadyInBasket (prdc,i) {
    $.ajax ({
        type: "POST",
        url: dynamicUrlAjax + '/basket/alreadyinbasket?time=' + new Date().getTime(),
        data: "prdc="+prdc,
        success: function (oldValue) {
            serializedData = $("#tr_prdc_"+i+" input[id^=qty], #tr_prdc_"+i+" input[name^=nh]").serialize();
            newValue = $("#tr_prdc_"+i+" input[id^=qty]").val();
            if (oldValue.length == 0) { purchase(i,0); }
            else {
                if (oldValue == newValue) { text = terms[10].replace('XXX', oldValue); alert (text); return false; }
                else { purchase(i,oldValue); text = terms[9].replace('XXX', oldValue); text = text.replace('YYY', newValue); alert (text); return true; }
            }
        }
    });
    return false;
}

function basketLoad () {
    if ($("#items_content").length > 0) {
        $("#items_content").load(dynamicUrlAjax + '/basket/basketload?time=' + new Date().getTime(), function () {
            basketCountRows (); basketClicks (); basketDeleteHover (); basketHover (); basketUpdateSum ();
        });
    }
    else {
        $("#basket_content").load(dynamicUrlAjax + '/basket/basketload2?time=' + new Date().getTime(), function () {
            basketCountRows (); basketClicks (); basketDeleteHover (); basketHover (); basketUpdateSum ();
        });
    }
}

function mAlert (type, message, btn1, btn2, dotrue, dofalse) {
    var bigBackground = $('<div/>');
    $(bigBackground).attr('id', 'bigBackground');
    $('body').append(bigBackground);

    var newalert = $('<div/>');
    var bodywidth = $(document).width();
    $(newalert).attr('id', 'newAlert').css({'opacity':'1','left' : bodywidth/2 -200 +"px", 'backgroundColor':'white', 'position':'fixed','textAlign':'left', 'fontSize':'14px', 'fontWeight':'normal', 'padding':'0px', 'height':'130px', 'lineHeight':'1.25em'});

    html = '<table class="noborder nopad">';
    html+= '<tr><td><img src="'+dynamicUrl+'/gfx/mattonlogo.jpg" alt="" /></td><td style="padding-left:10px;padding-top:30px;">'+message+'</td></tr>';
    html+= '<tr><td></td><td style="padding:5px 0 0 10px;line-height:1.6em;">';
    if (exklinkl == "exkl") { dotrue2 = dotrue; } else { dotrue2 = ""; }
    html+= '<b>&gt; <a href="javascript:void(0)" onclick="mAlertFadeOut();'+dotrue2+'">'+btn1+'</a></b>';
    if (type=='confirm') {
        html+= '<br />';
        if (exklinkl == "inkl") { dofalse2 = dofalse; } else { dofalse2 = ""; }
        html+= '<b>&gt; <a href="javascript:void(0)" onclick="mAlertFadeOut();'+dofalse2+'">'+btn2+'</a></b>';
    }
    html+= '</td></tr></table>';
    $(newalert).html(html);

    var background = $('<div/>');
    $(background).css({"opacity":"0","filter":"alpha(opacity=0)","-moz-opacity":"0"});
    $(background).attr('id', 'overlayBackground').css({'width':$(document).width(),'height':$(document).height()}).animate({'opacity':'.8'},1000,function() {
        $("#bigBackground").append(newalert);
    });

    $("#bigBackground").append(background);
}

function mAlertFadeOut () {
    $("#bigBackround,#newAlert,#overlayBackground").animate({'opacity':'0'},1000,function() { $("#bigBackround,#newAlert,#overlayBackground").remove(); });
}

function setInclVat () {
    document.cookie = "exklinkl=inkl; path=/"; pageReload();
}

function setExclVat () {
    document.cookie = "exklinkl=exkl; path=/"; pageReload();
}

function deleteProduct (prdc, i) {
    if (prdc != null && i != null) {
        $.ajax ({
            type: "POST",
            url: dynamicUrlAjax + '/basket/basketdelete?time=' + new Date().getTime(),
            data: "prdc="+prdc,
            success: function () {
                $("#basketline"+i).animate({opacity: 'hide'}, 'slow', function() {
                    $(this).remove();
                    if ($("input[value="+prdc+"]").length > 0) {
                        nh_prdc = $("input[value="+prdc+"]").attr("name").replace(/^nh_/, '');
                        j = $("input[name="+nh_prdc+"]").attr("id").split('_'); j = j[1].match(/(\d)+/); j = j[1];
                        $("#tr_prdc_"+j+" [id^=stockbasket]").html('');
                        $("#tr_prdc_"+j+" input[id^=qty]").val(1);
                    }
                    basketLoad ();
                });
            }
        });
    }
    else {
        if (confirm (terms[8])) {
            $.ajax ({
                type: "POST",
                url: dynamicUrlAjax + '/basket/basketdelete?time=' + new Date().getTime(),
                data: "purge=1",
                success: function () {
                    $("[id^=stockbasket]").html(''); $("input[id^=qty]").val(1); basketLoad ();
                }
            });
        }
        else return false;
    }
}

function basketCountRows () {
    $(".basketcountitems").text($("[id^=basketline]").size());
}

function basketUpdateSum () {
    basketsum = 0;
    $("[id^=basketqty]").each(function() {
        basketsum = basketsum - (-$(this).val());
    });
    $("#baskettotalqty").val(basketsum);
    var basketexcl = 0; var basketincl = 0;
    $("[id^=basketnotax]").each(function () {
        basketexcl = basketexcl - (-delCommas($(this).text()));
        var nr = $(this).attr("id").match(/\d+$/); var moms = $("#basketmoms"+nr).text()*1;
        basketincl = basketincl - (-delCommas($(this).text())*(moms/100 + 1));
    });
    $("#basketexcl").text(addCommas((basketexcl).toFixed(2)));
    if (basketexcl == 0) { $("#basketincl").text('0.00'); $("#shippingexklmoms").text('0.00'); }
    else { $("#basketincl").text(addCommas((basketincl - (-$("#shippinginklmoms").text())).toFixed(2))); $("#shippingexklmoms").text($("#shippingexklmoms2").text()); }
    basketHover ();
}

function basketClicks () {
    $(".basketplusminus").click (function (event) {
        event.preventDefault(); basketnr = $(this).attr("id").match(/\d+$/);
    });
    $("[id^=basketplus]").click (function () {
        $("#basketqty"+basketnr).val($("#basketqty"+basketnr).val()-(-1));
        $("#baskettotalprice"+basketnr+", #basketnotax"+basketnr).text(TP(delCommas($("#basketqty"+basketnr).val())*1, 'b'+basketnr));
        basketUpdateSum (); a = $("#basketprdc"+basketnr).text(); b = $("#basketqty"+basketnr).val(); waiting ("basketUpdateQty(a, b, basketnr)", 1000);
    });
    $("[id^=basketminus]").click (function () {
        if ($("#basketqty"+basketnr).val()>0) {
            $("#basketqty"+basketnr).val($("#basketqty"+basketnr).val()-1);
            $("#baskettotalprice"+basketnr+", #basketnotax"+basketnr).text(TP(delCommas($("#basketqty"+basketnr).val())*1, 'b'+basketnr));
            basketUpdateSum (); a = $("#basketprdc"+basketnr).text(); b = $("#basketqty"+basketnr).val(); waiting ("basketUpdateQty(a, b, basketnr)", 1000);
        }
    });
    $("[id^=basketqty]").keydown (function (event) {
        basketnr = $(this).attr("id").match(/\d+$/);
        if (event.keyCode == 13) {
            event.preventDefault();
            $("#baskettotalprice"+basketnr+", #basketnotax"+basketnr).text(TP(delCommas($("#basketqty"+basketnr).val())*1, 'b'+basketnr));
            basketUpdateSum (); a = $("#basketprdc"+basketnr).text(); b = $("#basketqty"+basketnr).val(); waiting ("basketUpdateQty(a, b, basketnr)", 10);
        }
    });
}

function basketDeleteHover () {
    $(".deletefrombasket").hover(
        function () { tr = $(this).parent().parent().attr("id"); color = $("#" + tr + " td:first a").css("color"); $("#" + tr + " td:first a").css("color", "red"); },
        function () { tr = $(this).parent().parent().attr("id"); $("#" + tr + " td:first a").css("color", color); }
    );
}

function waiting (fn, msec) {
    t = null; clearTimeout (t); t = setTimeout (fn, msec);
}

var prev;
var prevprdc;
function basketUpdateQty (prdc, qty, basketnr) {
    var curr = qty;
    if (prev == curr && prevprdc == prdc) { return; }
    prev = curr;
    prevprdc = prdc;
    $.ajax ({
        type: "POST",
        url: dynamicUrlAjax + '/basket/basketupdate?time=' + new Date().getTime(),
        data: "prdc="+prdc+"&qty="+qty,
        success: function (msg) {
            if (msg.length > 0) {
                alert(msg);
                $.ajax ({
                    type: "POST",
                    url: dynamicUrlAjax + '/basket/alreadyinbasket?time=' + new Date().getTime(),
                    data: "prdc="+prdc,
                    success: function(origqty) {
                        $("#basketqty"+basketnr).val(origqty); $("#baskettotalprice"+basketnr+", #basketnotax"+basketnr).text(TP(delCommas($("#basketqty"+basketnr).val())*1, 'b'+basketnr)); basketUpdateSum ();
                    }
                });
                return false;
            }
        }
    });
    if ($("input[value="+prdc+"]").length > 0) {
        prdc_html = $("input[value="+prdc+"]").attr("name").replace(/^nh_/,''); $("input[name="+prdc_html+"]").val(qty);
    }
}

function basketHover () {
    $(".showbasketlayer, #items_content").hover(
        function () { if ($("[id^=basketline]").size() > 0) { $("#items_content").show();} },
        function () { $("#items_content").hide(); }
    );
}

function TP (summa, nr) {
         if ($("#priced"+nr).length>0 && summa>=$("#dbqtyd"+nr).text()) multiplier = $("#priced"+nr).text();
    else if ($("#pricec"+nr).length>0 && summa>=$("#dbqtyc"+nr).text()) multiplier = $("#pricec"+nr).text();
    else if ($("#priceb"+nr).length>0 && summa>=$("#dbqtyb"+nr).text()) multiplier = $("#priceb"+nr).text();
    else multiplier = delCommas($("#pricea"+nr).text());
    $("[name=actualprice_"+nr+"]").val(multiplier);
    price = (Math.round(multiplier * summa * 100)/100).toFixed(2);
    return addCommas(price);
}
function Moms (nr) {
    mom = $("#itemmoms"+nr).text() / 100 + 1;
    $("#totalpriceinklmoms"+nr).attr("title",terms[0]+' ('+terms[2]+'): ' + addCommas(Math.round(delCommas($("#totalprice"+nr).text()) * mom * 100/100).toFixed(2)) + ' kr');
}
function OnlyOne (nr) {
    if ($("#totalqty"+nr).val() < 1) { $("#totalpriceinklmoms"+nr).addClass('visib'); }
    else { $("#totalpriceinklmoms"+nr).removeClass('visib'); }
}
function addCommas(nStr){
    nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); }
    return x1 + x2;
}

function delCommas(nStr) {
    return nStr.replace(/,/g,'');
}

function multiMoms (base, moms) {
    return (Math.round(base * moms * 100) / 100).toFixed(2);
}
function divideMoms (base, moms) {
    return (Math.round(base / moms * 100) / 100).toFixed(2);
}

function removeFilters() {
    $.ajax({
        type: "POST",
        url: dynamicUrlAjax + '/index/removefilters?time=' + new Date().getTime(),
        success: function () { pageReload(); }
    });
}

function setColourFilter(code) {
    $.ajax({
        type: "POST",
        url: dynamicUrlAjax + '/index/setcolourfilter?time=' + new Date().getTime(),
        data: 'hex='+code,
        success: function () { pageReload(); }
    });
}

function longdescr (descr) {
    $("#submenu_descr").html(descr);
}

function removelongdescr () {
    $("#submenu_descr").html('');
}

var temp_height;
function show_video (video) {
    if ($("#productdiv_video").html() == "") {
        $("#zoomout_reset, #productdiv2").css("display","none");
        temp_height = $("#producttd").height();
        $("#productdiv, #producttr").animate({ height: '328px' }, 'slow', function () {
            $("#producttd").height('328px');
            $("#productdiv_video").html('<embed src="'+dynamicUrl+'/gfx/gddflvplayer.swf" flashvars="&autoplay=true&sound=100&desc=&mylogo=&tracker=&buffer=2&vdo='+video+'" width="468" height="328" allowFullScreen="true" quality="best" wmode="transparent" allowScriptAccess="always"  pluginspage="//www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>');
        });
    }
}

function show_image () {
    if ($("#productdiv2").css("display") == "none") {
        $("#productdiv_video").html('');
        if (typeof (temp_height) === 'undefined') temp_height = '250px';
        $("#productdiv, #producttr").animate({ height: temp_height }, 'slow', function () {
            $("#producttd").height(temp_height); $("#zoomout_reset, #productdiv2").css("display","block");
        });
    }
}

function show_another_image (filename, x, y) {
    $("#productdiv_video").html('');
    if (filename.match("/")) { var fname = "/gfx/pages/"+filename; }
    else { var fname = "/productimages/med/"+filename; }
    if (x == 0 || y == 0) {
        $.ajax({
            url: dynamicUrlAjax + '/index/ajax/mode/imagesize',
            type: "POST",
            data: { img: fname },
            dataType: 'json',
            success: function (resp) { show_another_image_next (fname, resp.w, resp.h); }
        });
    }
    else {
        show_another_image_next (fname, x, y);
    }
}

function show_another_image_next (fname, x, y) {
    if (y < 250) { new_y = 250; $("#zoomout").hide(); $("#reset").hide(); }
    else { new_y = y; $("#zoomout").hide(); $("#reset").show(); }
    $("#productdiv, #producttr").animate({ height: new_y }, 'slow', function () {
        $("#producttd").height(new_y); $("#product, #productbig").attr("src", fullUrl+fname); $("#productdiv2").attr("style",previewMargins(x,y)); $("#zoomout_reset, #productdiv2").css("display","block");
    });
}

function previewMargins (new_w, new_h) {
    ml = (890 - new_w) / 2; if (new_h > 250) { mt = 0; } else { mt = (250 - new_h) / 2; }
    return "margin-top: "+mt+"px";
}

function changeListName() {
    oldListName = $("#changeListName_oldName").text();
    newHtml = '<input type="text" name="newName" value="'+oldListName+'" /> <input type="submit" value="Spara" /> ';
    $("#changeListName_span").html(newHtml);
}

function saveListName() {
    newName = $("input[name=newName]").val();
    list_id = $("input[name=list_id]").val();
    $.ajax ({
        url: dynamicUrlAjax + '/myaccount/ajax/favourites/savelistname',
        type: "GET",
        data: "list_title="+newName+"&list_id="+list_id,
        success: function () { pageReload(); }
    });
}

function addToFavourites(prdc,j,title) {
    $.ajax({
        url: dynamicUrlAjax+'/index/addtofavourites/',
        type: "GET",
        data: "prdc="+prdc,
        success: function () {
            $("#favs_inactive_"+j).addClass("none"); $("#favs_active_"+j).removeClass("none"); alert(title + ' lades till på din favoritlista');
        }
    });
}

function removeFromFavourites(prdc,msg,j) {
    if (confirm(msg)) {
        $.ajax({
            url: dynamicUrlAjax+'/index/removefromfavourites/',
            type: "GET",
            data: "prdc="+prdc,
            success: function () {
                $("#favs_active_"+j).addClass("none"); $("#favs_inactive_"+j).removeClass("none");
            }
        });
    }
    else {
        return false;
    }
}

function removeSelectedFromFavourites() {
    selected = $("input[name=selected[]]:checked, select[name=selectlist]").serialize();
    $.ajax({
        url: dynamicUrlAjax+'/index/removefromfavourites/',
        type: "GET",
        data: selected,
        success: function () { pageReload(); }
    });
}

function moveProducts() {
    selected = $("input[name=selected[]]:checked, select[name=movetolist]").serialize();
    $.ajax({
        url: dynamicUrlAjax+'/myaccount/ajax/movetolist/true/',
        type: "GET",
        data: selected,
        success: function () { pageReload(); }
    });
}

function checkNewFavouriteList(msg) {
    if ($("input[name=newlist]").val()=="") alert(msg); return false;
}

function campaign (code) {
    // check if code is available
    $.ajax({
        url: dynamicUrlAjax+'/checkout/ajax/checkcode/true',
        type: "POST",
        data: 'code='+code,
        dataType: 'json',
        success: function (resp) {
            // if yes, make changes to basket
            if (resp.msg == '' && resp.status == 1) {
                // change prices
                // proceed text
                newmsg = 'ok';
            }
            // if not
            else {
                // not valid
                newmsg = resp.msg + ' Please, verify your code. <a href="javascript:;" onclick="campaign_back();">Back</a>';
            }
            $("#campaigncode_div, #campaigncode_div > *").fadeOut(500,function(){
                $("#campaigncode_div2").html(newmsg).fadeIn(500,function(){ });
            });
        }
    });
}

function campaign_back () {
    $("#campaigncode_div2").fadeOut(500,function(){
        $("#campaigncode_div, #campaigncode_div > *").fadeIn(500,function(){ });
    });
}

function tipper(cat_id) {
    $("div[id^=sub_cat_ext]").hide().removeShadow();
    $("a[id^=sub_cat_other]").removeClass("firstred");
    $div = $("div#sub_cat_ext_"+cat_id);
    $link = $("a#sub_cat_other_"+cat_id);
    $.ajax({
        url: dynamicUrlAjax + '/index/subcategories/parent/' + cat_id,
        type: "get",
        dataType: 'html',
        success: function (data) {
            if (data.match(/[a-z]+/)) {
                $link.addClass("firstred"); $div.html(data); $div.show().dropShadow({left:0, top:3}); afterSuccess();
            }
        }
    });
    $div.click(function(){
        $link.removeClass("firstred"); $(this).hide().removeShadow(); afterSuccess();
    });
}

function afterSuccess() {
    $("#closex img").mouseover(function () { $(this).css("cursor","pointer"); });
    $("#closex img").click(function () {
        $(".popupmenu").animate({ opacity: 'hide', height: 'hide'}, function() { $(".popupmenu").removeShadow().attr("id",null); });
        allOn(); on = 0; number = 0; $(".dropShadow").css("display","none");
    });
    $(document).bind('click', function(e) {
        var $clicked=$(e.target);
        if( ! ( $clicked.is('.popupmenu') || $clicked.parents().is('.popupmenu') || $clicked.is('#menu') || $clicked.parents().is('#menu')) ) {
            $(".popupmenu").animate({ opacity: 'hide', height: 'hide'}, function() { $(".popupmenu").removeShadow().attr("id",null); });
            allOn(); on = 0; number = 0; $(".dropShadow").css("display","none");
        }
    });
}

function imghover () {
    $("[id^=imgmenu]").hover(
        function() { if (on == 1) { if ($(this).attr("id").match(/\d$/)*1 != number) { $(this).attr("src",$(this).attr("src").replace(/off(\d).gif/,'on$1.gif')); } } },
        function() { if (on == 1) { if ($(this).attr("id").match(/\d$/)*1 != number) { $(this).attr("src",$(this).attr("src").replace(/on(\d).gif/,'off$1.gif')); } } }
    );
}
function allOn () {
    $("[id^=imgmenu]").each(function() { $(this).attr("src",$(this).attr("src").replace(/off(\d).gif/,'on$1.gif')); });
}
function allOff (except) {
    $("[id^=imgmenu]").each(function(i) { if (i != except) { $(this).attr("src",$(this).attr("src").replace(/on(\d).gif/,'off$1.gif')); } });
}

function hideMiniBanners() {
    var today = new Date(); cookie_expire_date = new Date(today.getTime() + (3 * 86400000)); document.cookie = "mb_hidebanners=1; expires="+cookie_expire_date+"; path=/";
    $("#hideMiniBanners, #small_banners").animate({opacity:"hide"},500).addClass("none"); $("li.quicklink, #showMiniBanners").animate({opacity:"show"},500).removeClass("none");
}

function showMiniBanners() {
    var today = new Date(); cookie_expire_date = new Date(today.getTime() - (3 * 86400000)); document.cookie = "mb_hidebanners=0; expires="+cookie_expire_date+"; path=/";
    $("#hideMiniBanners, #small_banners").animate({opacity:"show"},500).removeClass("none"); $("li.quicklink, #showMiniBanners").animate({opacity:"hide"},500).addClass("none");
}

$(document).ready(function () {
    if (fvcookie==0) { mAlert('confirm',terms[11],terms[12],terms[13],'setInclVat()','setExclVat()'); }

    $.nyroModalSettings({
        cssOpt: { content: { textAlign: "center" } }, minHeight: 200, 
        showContent: function (elts, settings, callback) {
            elts.contentWrapper.css({ // Reset the CSS at the start position
                marginTop: (-100/2 + settings.marginScrollTop)+'px', marginLeft: (-100/2 + settings.marginScrollLeft)+'px', height: '100px', width: '100px', opacity: 0
            }).show().animate({ // Set the width
                width: settings.width+'px', marginLeft: (settings.marginLeft)+'px', opacity: 0.5
            }, {duration: 100}).animate({ // Set the height
                height: settings.height+'px', marginTop: (settings.marginTop)+'px', opacity: 1
            }, {complete: callback, duration: 100});
            var innerh = $("#nyroModalContentInner").height();
            $("#nyroModalContentInner").css({
                marginTop: elts.content.height()/2 - innerh/2+"px"
            });
        }
    });

    $.preloadImages(dynamicUrl+"/gfx/menu/off1.gif",dynamicUrl+"/gfx/menu/off2.gif",dynamicUrl+"/gfx/menu/off3.gif",dynamicUrl+"/gfx/menu/off4.gif",dynamicUrl+"/gfx/menu/off5.gif",dynamicUrl+"/gfx/sok.gif");

    if (jsProductPage==1) {
        producttn_height = parseInt ($("#producttn").height());
        pr_descr_height  = parseInt ($("#product_descr_1").height());
        if (pr_descr_height < producttn_height - 30) { $("#product_descr_1").height(producttn_height-30 +"px"); }
    }

    $("#popularproducts_head").click(function(){
        $lis = $("li.quicklink"); $img = $("#popularproducts_head img");
        if($lis.hasClass("none")) { $lis.animate({opacity:"show"},500).removeClass("none"); $img.attr("src",$img.attr("src").replace('arrow.','arrowb.')); }
        else { $lis.animate({opacity:"hide"},500).addClass("none"); $img.attr("src",$img.attr("src").replace('arrowb.','arrow.')); }
    });

    $("div.small_banners").click(function(e){
        var $clicked=$(e.target); if (!$clicked.is("input")) { window.location.href = $(this).attr("rel"); }
    });
	
	var sbth=0; // adjust banner titles to be equal height
	$("div.small_banners_title").each(function(k,v){
		if ($(this).height() > sbth) { sbth=$(this).height(); }
	}).each(function() {
		$(this).height(sbth);
	});

    /***** CHANGE INKL/EXKL MOMS *****/
    $("input[name=moms]").click(function () {
        id = $(this).attr("id");
        if (id == "inklmoms") { setInclVat(); }
        if (id == "exklmoms") { setExclVat(); }
    });
    /***** CHANGE INKL/EXKL MOMS *****/

    /***** SEARCH BUTTON *****/
    $(".mainsearchbutton").hover(
        function () { $(this).attr("src", $(this).attr("src").replace('sok-dark.gif','sok.gif')); },
        function () { $(this).attr("src", $(this).attr("src").replace('sok.gif','sok-dark.gif')); }
    );
    /***** SEARCH BUTTON *****/

    /***** SUBMENU *****/
    on = 0;
    $("[id^=menutitle], [id^=crumbname]").click(function () {
        pmenunumber = $(".popupmenu").attr("id").match(/\d$/); number = $(this).attr("id").match(/\d$/);
        if (on == 0) {
            $(".popupmenu").bgiframe().attr("id","pmenu"+number).animate({ opacity: 'show', height: 'show' }, function() { $(this).dropShadow({left:0, top:3}); });
            allOff(number); on = 1; imghover();
        }
        else {
            $(".popupmenu").bgiframe().attr("id","pmenu"+number).show();
            allOff(number); on = 1; imghover();
        }
        if (number+'' != pmenunumber+'') {
            $("#popupsub1").html('<div id="subloading"><img src="'+dynamicUrl+'/gfx/ajax-loader.gif" alt="loading" /></div>');
            $.ajax({
                type: "GET",
                url: dynamicUrlAjax + '/index/submenu/menu/' + number,
                datatype: 'html',
                success: function (data) {
                    $("#popupsub1").html(data); afterSuccess ();
                }
            });
        }
        else {
            $(".popupmenu").animate({ opacity: 'hide', height: 'hide'}, function() { $(".popupmenu").removeShadow().attr("id",null); });
            allOn(); on = 0; number = 0; $(".dropShadow").css("display","none");
        }
    });
    $("#menu li, #zoomout_reset").mouseover(function () { $(this).css("cursor","pointer"); });
    /***** SUBMENU *****/

    /***** SHOW CONTENTS OF THE BASKET *****/
    basketHover (); basketClicks (); basketDeleteHover ();
    /***** SHOW CONTENTS OF THE BASKET *****/

    /***** PRODUCTS *****/
    function bindMagnifyCursor () {
        $("#product, #productbig").mouseover(function () { if (state != 2) { $(this).css("cursor", "url("+dynamicUrl+"/gfx/cursor-magnify.png), -moz-zoom-in"); } });
    }
    bindMagnifyCursor (); move = 0; state = 1;
    $("#producttn").click(function () { window.location.href = "#productimage"; zoomout (); });
    $("#zoomout, #product").click(function () { zoomout (); });
    $("#reset, #productbig").click(function () { reset (); });

    function zoomout () {
        if (state == 1) {
            origHeight = $("#product").height(); origWidth  = $("#product").width(); newHeight  = origHeight*3/4; newWidth   = origWidth*3/4;
            $("#productdiv2").animate({ marginTop:"0px" }, 'slow');
            $("#productdiv, #producttr").animate({ height: origHeight }, 'slow', function () {
                $("#product").addClass("none").addClass("print_not_show"); $("#productbig").removeClass("none"); $("#zoomout").css("display","none"); $("#reset").show(); $("#producttd").css("height", origHeight); state = 0;
            });
        }
        if (state == 2) {
            $("#product").animate({ height: origHeight, width: origWidth, left: "0px", top: "0px", marginLeft: -(origWidth-newWidth)/2 +"px", marginTop: -(origHeight-newHeight)/2 +"px" }, 'slow', function () {
                $("#zoomout").show(); $("#reset").css("display","none"); state = 1;
            });
        }
        move = 0; bindMagnifyCursor ();
    }

    function reset () {
        origHeight = $("#productbig").height(); origWidth = $("#productbig").width(); newHeight = origHeight*4/3; newWidth = origWidth*4/3;
        $("#productdiv2").animate({ marginTop:-(origHeight-250)/2 +"px" }, 'slow');
        $("#productdiv, #producttr").animate({ height: '250px' }, 'slow', function () {
            move = 0; state = 1; $("#product").removeClass("none"); $("#productbig").addClass("none").addClass("print_not_show"); $("#zoomout").show(); $("#reset").css("display","none"); $("#producttd").css("height", "250px"); bindMagnifyCursor ();
        });
    }

    $("[class^=kop_]").hover (
        function () { i=$(this).attr("class").match(/(\d)+$/); i=i[0]; $("#tr_prdc_"+i+" span[class=gray]").removeClass("gray").addClass("red2"); },
        function () { i=$(this).attr("class").match(/(\d)+$/); i=i[0]; $("#tr_prdc_"+i+" span[class=red2]").removeClass("red2").addClass("gray"); }
    );

    $(".plusminus").click (function (event) {
        event.preventDefault(); nr = $(this).attr("id").match(/\d+_\d+a?$/); nr2 = ''+nr; nr2 = nr2.split('_');
    });
    $("[id^=plus]").click (function () {
        $("#qty"+nr).val($("#qty"+nr).val()-(-1));
        sum = 0;
        $("[id^=qty"+nr2[0]+"_]").each(function () {
            sum = sum - (-$(this).val());
        });
        $("#totalqty"+nr2[0]).val(sum); $("#totalprice"+nr2[0]).text(TP(sum, nr2[0]));
        Moms(nr2[0]); OnlyOne(nr2[0]);
    });
    $("[id^=minus]").click (function () {
        if ($("#qty"+nr).val()>0) {
            $("#qty"+nr).val($("#qty"+nr).val()-1);
            sum = 0;
            $("[id^=qty"+nr2[0]+"_]").each(function () {
                sum = sum - (-$(this).val());
            });
            $("#totalqty"+nr2[0]).val(sum); $("#totalprice"+nr2[0]).text(TP(sum, nr2[0]));
            Moms(nr2[0]); OnlyOne(nr2[0]);
        }
    });
    $("[id^=totalqty]").keyup (function (e) {
        if(e.which==13) return false;
        c = $(this).val().replace( /[^\d]/g ,''); $(this).val(c);
        n = $(this).attr("id").match(/\d+$/);
        sum = $(this).val()-(-1)-1;
        $("#totalprice"+n).text(TP(sum,n)); Moms(n); OnlyOne(n);
    });

    $("[class=star_inactive]").mouseover(function() {
        $(this).addClass('star_active'); $(this).find('img').attr("src",$(this).find('img').attr("src").replace('inactive','active'));
    });
    $("[class=star_inactive]").mouseout(function() {
        $(this).removeClass('star_active'); $(this).find('img').attr("src",$(this).find('img').attr("src").replace('active','inactive'));
    });
    
    var temp_height;
    $("[class^=product_text_more]").click(function(event) {
        event.preventDefault();
        id = $(this).attr("class").match(/\d+/);
        $(".product_text_"+id).toggle(); $(".product_text_more_"+id).toggle();
        if ($("#product_descr_"+id).attr("style") != "") { temp_height = $("#product_descr_"+id).attr("style"); $("#product_descr_"+id).attr("style",""); }
        else { $("#product_descr_"+id).attr("style",temp_height); }
    });

    $("#product_hide_description").click(function(event) {
        event.preventDefault();
        $(".description").slideToggle("slow", function () {
            if ($(this).css("display")=="block") { $("#product_hide_description").text($text1); }
            else { $text1 = $("#product_hide_description").text(); $("#product_hide_description").text(terms[5]); }
        });
    });

    $("[name=prdc_images]").mouseover(function() { $(this).css("cursor","pointer"); });

    $("[name=prdc_images]").click(function(event) {
        img = $(this).attr("id").replace("tui-", "mui-"); img = $(this).attr("id").replace("cui-", "mui-"); img = img.replace(/^tn(2)?_/,"");
        $("#product, #productbig").attr("src", img); window.location.href = '#productimage'; zoomout();
    });

    $("td.backstock").mouseover(function(){
        $id = $(this).parent().attr("id").match(/\d+$/); $("#tr_prdc_"+$id+"_first").find(".descr").css("color","#aa1313");
    });

    $("td.backstock").mouseout(function(){
        $id = $(this).parent().attr("id").match(/\d+$/); $("#tr_prdc_"+$id+"_first").find(".descr").css("color","");
    });
    /***** PRODUCTS *****/


    /***** BROWSE *****/
    $(".browse_description_toggle").click(function (event) {
        event.preventDefault(); $(".browse_description").toggle(); $(".browse_description_toggle").toggle();
    });
    /***** BROWSE *****/

    /***** SEARCH *****/
    $("a[id^=moreinfo], a[id^=variations]").click(function (event) {
        event.preventDefault();
        infonumber = $(this).attr("id").match(/\d+$/);
        $("#resultmore"+infonumber).slideToggle("slow", function () {
            if ($("#resultmore"+infonumber).css("display")=="block") {
                $text1 = $("#variations"+infonumber).text(); $("#variations"+infonumber).text('- '+terms[3]); $("#view"+infonumber).show();
            }
            else {
                $("#variations"+infonumber).text($text1); $("#view"+infonumber).css("display","none");
            }
        });
    });

    function findValueCallback(event, data, formatted) {
        $("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
    }
    function formatItem(row) {
        return row[0] + " (<strong>id: " + row[0] + "</strong>)";
    }
    function format(n) {
        return n.name;
    }
    $("#sok").bgiframe().autocomplete(dynamicUrlAjax + '/index/autosuggest', {
        width: 395,
        parse: function(data) {
            return $.map(eval(data), function(row) {
                return { data: row, value: row.name, result: row.val }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    });
    /***** SEARCH *****/
	
    $("#feedback_close").click(function(){ $("#feedback_link").trigger("click"); });
    $("#feedback_link, #feedback_link2").click(function(){
        var fb_div = $("#f_div");
        if (fb_div.is(":visible")) { fb_div.addClass("none"); }
        else { fb_div.removeClass("none"); }
    });
    $("#feedback_send").click(function(){
        var fields=new Array('s_fname','s_femail','s_fsubject','s_message');
        var hasempty=0; var inp; var pdata="";
        for (var i=0;i<fields.length;i++) {
            inp=$("#"+fields[i]); if(!inp) { return; } pdata+='&'+fields[i]+'='+(inp.val());
            if (i<4 && !inp.val().length) { hasempty=1; }
        }
        if (hasempty) { $.nyroModalManual({ content: "<img src='"+dynamicUrl+"/gfx/warning.png'/><br/>"+terms[15] }); }
        else { 
            $.ajax({
                url: dynamicUrlAjax + '/index/ajax/mode/feedback',
                type: "GET",
                data: pdata,
                success: function (resp) {
                    $.nyroModalManual({ content: "<img src='"+dynamicUrl+"/gfx/checkmark.png'/><br/>"+terms[14] });
                    $("#f_div").addClass("none");
                    $("#s_fname, #s_femail, #s_message").val(""); $("#s_fsubject option:selected").removeAttr("selected");
                }
            });
        }
    });
});

function quickedit(j,field,type,prdc,gno,dbact,topcat) {
    var jfield = field; var sfield = $("#saved_"+field);
    if (j!=0){ var jfield = field.replace(j+'_',""); }
    var qfield = $("#"+field);
    prdc_field = jfield.replace(/^qe_/,"");
    var content = $('#content_'+field).val();
    $.ajax({
        url: dynamicUrlAjax + '/index/quickedit/',
        type: "POST",
        data: {prdc:prdc,gno:gno,field:prdc_field,dbact:dbact,content:content,topcat:topcat},
        dataType: "json",
        success: function (resp) {
            if(dbact=='select') {
                var heads=new Array();
                if(prdc_field=='bulleted_description'){
                    headsa=resp.heads;
                    $.each(headsa,function(k,v){ heads+=this + ":<br/>"; });
                }
                if(type=='text') {
                    qfield.html('<input type="text" id="content_'+field+'" name="'+field+'" size="52" value="'+resp.content+'" />');
                }
                else if(type=='textarea') {
                    var text = resp.content; var rows=0; rows = text.length/30;
                    if (rows>20) { rows=20; }
                    else if (rows<5) { rows=5; }
                    areaclass="qetext";
                    if(prdc_field=="bulleted_description"){ areaclass = "qetextbulleted"; }
                    var textarea='<textarea class="'+areaclass+'" rows="'+rows+'" id="content_'+field+'" name="'+field+'">'+resp.content+'</textarea>';
                    var span='<span>'+heads+'</span>';
                    if (topcat==1) { qfield.html('<table class="noborder nopad"><tr><td valign="top" style="padding-top: 5px;" class="orange">'+heads+'</td><td>'+textarea+'</td></tr></table>'); }
                    else { qfield.html('<span>'+textarea+'</span><br />'); }
                }
                document.getElementById("link_select_"+field).onclick=new Function("quickedit('"+j+"','"+field+"','"+type+"','"+prdc+"','"+gno+"','update','"+topcat+"')");
                $("#link_select_"+field).text("Save");
                document.getElementById("link_cancel_"+field).onclick=new Function("quickedit('"+j+"','"+field+"','"+type+"','"+prdc+"','"+gno+"','cancel','"+topcat+"')");
                $("#link_cancel_"+field).text("Cancel");
                sfield.html('');
            }
            else if(dbact=='update') {
                qfield.html(resp.content);
                document.getElementById("link_select_"+field).onclick=new Function("quickedit('"+j+"','"+field+"','"+type+"','"+prdc+"','"+gno+"','select','"+topcat+"')");
                $("#link_select_"+field).text("Edit");
                $("#link_cancel_"+field).text("").removeAttr("onClick");
                sfield.html('-- saved');
                waiting(function(){
                    sfield.animate({opacity:0},1000,function(){ sfield.html('').css({opacity:1}); });
                },1000);
            }
            else if(dbact=='cancel') {
                qfield.html(resp.content);
                document.getElementById("link_select_"+field).onclick=new Function("quickedit('"+j+"','"+field+"','"+type+"','"+prdc+"','"+gno+"','select','"+topcat+"')");
                $("#link_select_"+field).text("Edit");
                $("#link_cancel_"+field).text("").removeAttr("onClick");
                sfield.html('');
            }
        }
    });
} 

