/* decryp addresses*/

var customDebugEnabled = false;

function dcmadr(nnnn){
    var a = "";
    for(i=0,m=nnnn.length;i < m;i++){
        if(i%3==0){
            a += String.fromCharCode(nnnn.substr(i, 3));
        }
    }
    location.href=(a);
}
var customDirPath = "";
function setCustomDirPath(bwp){
    customDirPath = bwp;
}



/* select form field element radio/checkbox */
function selectFormFieldElement(group, index) {
    var c = document.contactForm[group];
    if(c.length>0){
        c = c[index];
    }
    if(c.type == "radio"){
        c.checked = true;
    }else{
        c.checked = !c.checked;
    }
}


/* search box */
function removeDefault(formField, value){
    if(formField.value == value){
        formField.value = "";
    }
    formField.style.color = "#000";
}
function resetDefault(formField, value){
    if(formField.value == ""){
        formField.value = value;
        formField.style.color = "#888";
    }
}
function checkSearchBox(ff,st,eft){
    var t = ff.search.value;
    if(t == ''||t==st){
        alert(eft);
        ff.search.focus();
        ff.search.select();
        return false;
    }
}


/* shop basis */
var currentLanguage = "de";
function setCurrentLanguage(l){
    currentLanguage = l;
}
var basePath  = "/";
function setBasePath(p){
    basePath = p;
    shop_basketScriptPath = basePath+"custom/shop/baskethandling.jsp";
}
var shop_basketScriptPath = basePath+"custom/shop/baskethandling.jsp";
var basketHandle = "";
function setBasketHandle(h){
    basketHandle = h;
}


/* shop in product view */
var shop_grandtotal = 0;
var shop_nettotal = 0;
var shop_currencyString = "CHF";
var shop_itemsString = "Items";
var shop_minStockForOrdering = 4;
var shop_minOrderAmount = 40.00;
var shop_shippingFree = 100;
var shop_infoOnLowStock = "Item currenty unavailable";
var shop_alertMinimalAmount = "";
var shop_shippingCost = 9.90;


var basketGlueStrings=new Array("Warenkorb","Artikel wurde in den Warenkorb gelegt.","Artikel im Warenkorb","Totalbetrag","[x] entfernen", "Keine Artikel im Warenkorb","&raquo; Zur Bestellung");
function setBasketGlueStrings(){
     for (var i = 0; i < arguments.length;  i++) {
         basketGlueStrings[i] = arguments[i];
    }
}


function shop_formatPrice(v){
    v = String(v);
    var amo = v;
    var dec = "00";
    if(v.indexOf(".")!=-1){
        dec = v.substring(v.indexOf(".")+1);
        amo = v.substring(0,v.indexOf("."));
        if(dec.length<2){dec += "0";}
        if(dec.length>2){dec = Math.round(dec/10)+"";}
        if(dec.endsWith("5") || dec.endsWith("0")){
        }else{
            dec = String(Math.round(dec/10)*10);
        }
        if(dec.length>2){dec = dec.substr(0,2);}
    }
    while(amo.indexOf("0")==0){
        amo = dec.substring(1);
    }
    if(amo.length>3){
        amo = amo.substring(0,amo.length-3)+"'"+amo.substring(amo.length-3);
    }
    return amo+"."+dec;
}

function addOrderItemToBasket(tid){
    var $f = $("#product_qty_"+tid);
    var amount = $f.val();
    tid = tid.substring(5);
    $.get(shop_basketScriptPath+"?cmd=ab&itemid="+tid+"&amount="+amount+"&ck="+new Date().getTime(),function(data){
        $.jGrowl(basketGlueStrings[1]+"<br/><a href='"+basketHandle+"ck="+new Date().getTime()+"'>"+basketGlueStrings[6]+"</a>", {header: basketGlueStrings[0]});        
        var myObject = eval('(' + data + ')');
        /* reset shop form */
        $f.val(1);
        displayShoppingBag(myObject);
    });
    return false;
}


function displayTopShoppingBag(){
    $.get(shop_basketScriptPath+"?cmd=gt&ck="+new Date().getTime(),function(data){
        var myObject = eval('(' + data + ')');
        displayShoppingBag(myObject);
    });
}
function displayShoppingBag(myObject){
    var $sbd = $("#shop-basket");
    var $sbdd = $("#shop-basket-details");
    var ci = myObject['countitems'];
    var tp = myObject['totalprice'];
    var displayString = " ("+ci+")";
    if(ci>0 && tp){
        $sbd.show();
        $sbdd.html(displayString);
        $("#grandtotal").text(shop_currencyString+" "+tp);
        shop_grandtotal = tp;
//        checkShippingCostDisplay();
    }
}


/* shopping bag in content */
function shop_removeFromBasket(itemid){
    $.get(shop_basketScriptPath+"?cmd=rm&itemid="+itemid+"&ck="+new Date().getTime(),function(data){
        var myObject = eval('(' + data + ')');
        if(myObject['success']=='true'){
            document.location.reload();
        }
    });


}
function shop_updateBagViewAmount(uuid,am){
    var f = $("#q_"+uuid);
    var v = secureDoubleDigitInputValue(f);
    if(v>0){
        f.val(v);
        //    document.title = v ;
        $("#total_"+uuid).text(shop_currencyString+" "+shop_formatPrice(v*am));
        $.get(shop_basketScriptPath+"?cmd=ua&itemid="+uuid+"&amount="+v+"&ck="+new Date().getTime(),function(data){
            var myObject = eval('(' + data + ')');
            displayTopShoppingBag();
        });
    }
}
function shop_checkForBagRemove(uuid){
    var f = $("#q_"+uuid);
    var v = secureDoubleDigitInputValue(f);
    if(v==0||v==""){
        shop_removeFromBasket(uuid);
    }
}
function shop_emptyShoppingBag(reload){
    $.get(shop_basketScriptPath+"?cmd=eb&ck="+new Date().getTime(),function(data){
        if(reload){
            document.location.reload();
        }else{
            displayTopShoppingBag();
        }
    });

}

/* shop orderform */
var text_mandatoryempty ="";
var text_mandatoryagb ="";
var text_invalidemail = "";
var hasDLAdress = false;
var acceptedAGB = false;
function set_text_mandatoryagb(val){text_mandatoryagb = val;}
function set_text_mandatoryempty(val){text_mandatoryempty = val;}
function set_text_invalidemail(val){text_invalidemail = val;}


function persistOrderInfoToSession(field){
    var value = encodeURIComponent(field.value);
    persistOrderInfoWithValueToSession(field.name,value);
}
function persistOrderInfoWithValueToSession(fieldname,value){
    $.get(shop_basketScriptPath+"?cmd=sf&field="+fieldname+"&value="+value+"&ck="+new Date().getTime());
}

function checkMandatoryFieldValue(f, tn){
    var c = true;
    var tf = f[tn];
    if(tf){
        if(tf.value==""){
            $("input[name='"+tn+"']").addClass("emptymandatory");
            c = false;
        }else{
            $("input[name='"+tn+"']").removeClass("emptymandatory");
        }
    }
    return c;
}
function checkEmailFormValue(f, tn){
    var c = true;
    var tf = f[tn];
    if(tf){
        if(!hasCorrectFormat(tf.value)){
            $("input[name='"+tn+"']").addClass("emptymandatory");
            c = false;
        }else{
            $("input[name='"+tn+"']").removeClass("emptymandatory");
        }
    }
    return c;
}





/* shop helper methods */
function secureDoubleDigitInputValue(f){
    var v = f.val();
    if(isNaN(v)){
        v = v.replace(/[^0-9]/g, '');
    }
    if(v>99){v=String(v).substring(0,2)}
    return v;

}
function secureCorrectInput(f){
    var $f = $("#"+f);
    var v = $f.val();
    v = v.replace(/[^0-9]/g, '');
    if(v>1000){v=1000;}
    $f.val(v);
}



$(document).ready(function(){
    // FANCYBOX
    $("a.fancyBox").fancybox({
            'showCloseButton': true,
            'overlayColor': "#000",
            'overlayOpacity': 0.7,
            'titlePosition': 'inside'
        });
    /* add date to links for omiting cache */
    $(".ckLink").each(function(){
        $(this).attr("href", $(this).attr("href")+"?ck="+new Date().getTime());
    });

    // form elements auto focus
    $("input[type=text]").mouseenter(function(){
        $(this).focus();
        $(this).select();
    });
    // form reveal hidden fields
    $(".showhidden").change(function(){
        if($(this).attr("checked")){
            $(".hiddenFormElement").fadeIn();
        }else{
            $(".hiddenFormElement").fadeOut();

        }
    });
    // save form input to session
    $("input[type=text]").change(function(){
        persistOrderInfoToSession(this)
    });


    jQuery('#l1Nav ul').superfish({
        delay:       500,                            // one second delay on mouseout
        animation:   {height:'show'},  // fade-in and slide-down animation
        speed:       'fast',                          // faster animation speed
        autoArrows:  false                           // disable generation of arrow mark-up
    });
    

    // FANCYBOX
    function formatTitle(title, currentArray, currentIndex, currentOpts) {
        return '<div id="resize-title"><div class="left-title">' + (title && title.length ? '<b>' + title + '</b></div> ' : '' ) + '<div class="right-title"><strong>' + (currentIndex + 1) + '</strong> of <strong>' + currentArray.length + '</strong></div></div> <div class="resize-close"><a href="javascript:;" onclick="$.fancybox.close();"><img src="'+customDirPath+'images/system/resize-close.gif" /></a></span>';
    }
//	$(".item a").fancybox({
    $(".item a:not(.product-gallery .item a)").fancybox({
        'showCloseButton': false,
        'overlayColor': "#000",
        'overlayOpacity': 0.7,
        'titlePosition': 'inside',
        'titleFormat': formatTitle
    });

    // PRODUCT DETAIL IMAGES
    $(".productImageThumb").mouseenter(function(){
        var s = $(this).attr("src");
        $(".productImage").attr("src", s);
        $(".productImageThumb").fadeTo(1,0.5);

        $(this).fadeTo(1,1);
    }).fadeTo(1,0.5);
    $(".productImageThumb.act").fadeTo(1,1);

    /* fullsize bg */
    $("#background_image").fullBg();
    $("#home_background").fadeTo(0,0.8);

    /* fade header img */
    $("#header_background").fadeTo(0,0.8);

});


/* helper methods */

Array.prototype.shuffle = function( b ) {
 var i = this.length, j, t;
 while( i ) {
  j = Math.floor( ( i-- ) * Math.random() );
  t = b && typeof this[i].shuffle!=='undefined' ? this[i].shuffle() : this[i];
  this[i] = this[j];
  this[j] = t;
 }
 return this;
};

String.prototype.endsWith = function (s) { return this.length >= s.length && this.substr(this.length - s.length) == s; }

function get_radio_value(formhandle){
    var r = "";
    for (var i=0; i < formhandle.length; i++){
        if (formhandle[i].checked){
            r = formhandle[i].value;
        }
    }
    return r;
}


(function($) {
  $.fn.fullBg = function(){
    var bgImg = $(this);

    function resizeImg() {
      var imgwidth = bgImg.width();
      var imgheight = bgImg.height();

      var winwidth = $(window).width();
      var winheight = $(window).height();

      var widthratio = winwidth / imgwidth;
      var heightratio = winheight / imgheight;

      var widthdiff = heightratio * imgwidth;
      var heightdiff = widthratio * imgheight;

      if(heightdiff>winheight) {
        bgImg.css({
          width: winwidth+'px',
          height: heightdiff+'px'
        });
      } else {
        bgImg.css({
          width: widthdiff+'px',
          height: winheight+'px'
        });
      }
    }
    resizeImg();
    $(window).resize(function() {
      resizeImg();
    });
  };
})(jQuery)
