/* 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;
}

/* sound embeding / metanavigation */
var _isFirst = null;
var _offtxt = null;
var _ontxt = null;
var _soundfile = null;
var _soundplayer = null;
var _isLoop = null;

function handleSound(isFirst, offtxt, ontxt, soundfile, soundplayer, isLoop){
    if(_isFirst==null)_isFirst = isFirst;
    if(_offtxt==null)_offtxt = offtxt;
    if(_ontxt==null)_ontxt = ontxt;
    if(_soundfile==null)_soundfile = soundfile;
    if(_soundplayer==null)_soundplayer = soundplayer;
    if(_isLoop==null)_isLoop = isLoop;
    displaySoundSwitch();
    playSoundIfEnabled();
}
function playSoundIfEnabled(){
    var disableSound = $.cookie('kuhnrikon_sound');
    if(disableSound != 'true'){
        var html='<object width="1" height="1"><param name="flashVars" value="soundPath='+_soundfile+'&soundLoop='+_isLoop+'" /><param name="movie" value="'+_soundplayer+'"><embed src="'+_soundplayer+'" flashVars="soundPath='+_soundfile+'&soundLoop='+_isLoop+'" width="1" height="1"></embed></object>';
        $("#soundBox").html(html);
    }else{
        $("#soundBox").html("");
    }
}
function displaySoundSwitch(){
    var disableSound = $.cookie('kuhnrikon_sound');
    var metaNavElement = " | ";
    if(_isFirst == 'true'){metaNavElement="";}
    if(disableSound == 'true'){
        metaNavElement += '<a href="javascript:toggleSound(\''+false+'\')">'+_ontxt+'</a>';
    }else{
        metaNavElement += '<a href="javascript:toggleSound(\''+true+'\')">'+_offtxt+'</a>';
    }
    $("#soundSwitch").html(metaNavElement);
}
function toggleSound(val){
    $.cookie('kuhnrikon_sound', val, { expires: 365 });
    displaySoundSwitch();
    playSoundIfEnabled();
}



/* select form field element radio/checkbox */
function selectFormFieldElement(group, index) {
    var c = $("input[name="+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;
    }
}

/* inline search */
$.fn.inlineSearch = function(listElement, parentElement, searchElemtns){
    $(this).keyup(function(){
      var searchString = jQuery.trim($(this).val().toLowerCase());
        $(parentElement, $(listElement)).each(function(){
            var c = $(searchElemtns, $(this)).parent().text().toLowerCase();
            if(c.indexOf(searchString)!=-1){
                $(this).show();
            }else{
                $(this).fadeOut();
            }
        });
    });
}



/* product-gallery */
function showProductGalleryDetail(i,g){
    $("#"+g).attr("src", i.src);
}

/* 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";



/* 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 coupon_enterCouponText = "Enter Code";
var coupon_freeShipping = false;


function shop_setBaseInformation(_cur,_item,_min,_info,_sfree,_scost,_minorder,_almin,_coupon){
    shop_currencyString = _cur;
    shop_itemsString = _item;
    if(!isNaN(parseInt(_min))){
        shop_minStockForOrdering = parseInt(_min);
    }
    if(!isNaN(parseInt(_sfree))){
        shop_shippingFree = parseInt(_sfree);
    }
    if(!isNaN(parseFloat(_scost))){
        shop_shippingCost = parseFloat(_scost);
    }
    if(!isNaN(parseFloat(_minorder))){
        shop_minOrderAmount = parseFloat(_minorder);
    }
    shop_infoOnLowStock = _info;
    shop_alertMinimalAmount = _almin;
    coupon_enterCouponText = _coupon;
}
var shop_visibleProducts = new Array();
function shop_addToVisibleProducts(uuid, pid, price, saleprice, salepriceUUID, stock){
    shop_visibleProducts[uuid] = new Array(pid,price,saleprice,salepriceUUID,stock); 
}

function shop_switchProduct(){
    $("#amount").val(1);
    shop_updateShopView();
}
function shop_updateShopView(){
    var pid = $("#product").val();
    /* check if provided id is empty */
    if(pid==""){
        shop_showHideBuying(false);
    }else{
        /* check if provided id is in array */
        if(shop_visibleProducts[pid]){
            shop_showHideBuying(true);
        }
    }
    shop_displayPrice();
}

function shop_showHideBuying(boolShow){
    var $b = $("#amount, #submit, #code");
    if(boolShow){
        $b.fadeTo(0,1);
        $($b).attr('disabled',  false);
    }else{
        $("#price").html("");
        $b.fadeTo(0,0.3);
        $($b).attr('disabled', true);
    }
}

function shop_updateShopViewAmount(){
    var f = $("#amount");
    $("#amount").val(secureDoubleDigitInputValue(f));
    shop_updateShopView();
}

function shop_displayPrice(){
    var pid = $("#product").val();
    var p = "";
    var op = "";
    var ep = "";
    if(pid!=""){
        var amount = $("#amount").val();
        var pp = parseFloat(shop_visibleProducts[pid][1]);
        var sp = parseFloat(shop_visibleProducts[pid][2]);
        var st = parseInt(shop_visibleProducts[pid][4]);
        if(!isNaN(sp) && sp!=pp && sp>0){
            op = "<span class='oldprice'>"+shop_currencyString+" "+shop_formatPrice(pp)+"</span><br /><span class='sale-price'>";
            pp = sp;
            ep = "</span>"
        }
        p = parseFloat(amount)*(pp);
        if(isNaN(p)){
            p="";
        }else{
            p = shop_formatPrice(p);
            p = shop_currencyString+" "+p;
        }
        if(st<parseInt(shop_minStockForOrdering)){
            shop_showHideBuying(false);
            p = shop_infoOnLowStock;
            op="";
        }
    }
    $("#price").html(op+p+ep);
}

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.length>1){
        amo = dec.substring(1);
    }
    if(amo.length>3){
        amo = amo.substring(0,amo.length-3)+"'"+amo.substring(amo.length-3);
    }
    return amo+"."+dec;
}

function shop_addToBasket(){
    var itemid = $("#product").val();
    var pageid = $("#productPageId").val();
    var amount = $("#amount").val();
    var saleid = shop_visibleProducts[itemid][3];
    var coupon = $("#code").val();
    if(coupon==""){coupon='remove';}
    var h = shop_basketScriptPath+"?cmd=ub&itemid="+itemid+"&amount="+amount+"&productPageId="+pageid+"&salePriceId="+saleid+"&lang="+currentLanguage+"&ck="+new Date().getTime();
    if(coupon!=coupon_enterCouponText){h+="&coupon="+coupon}
    $.get(h,function(data){
        /* reset shop dropdown */
        $("#product").attr('selectedIndex', 0);
        $("#amount").val(1);
        shop_updateShopView();
        displayTopShoppingBag();
    });
}

function displayTopShoppingBag(){
    var $sbd = $("#shop-basket-display");
    var $sbdd = $("#shop-basket-display-details");
    var h = shop_basketScriptPath+"?cmd=gt&ck="+new Date().getTime();
    $.get(h,function(data){
        var myObject = eval('(' + data + ')');
        var ci = myObject['countitems'];
        var tp = myObject['totalprice'];
        var tpno = myObject['totalprice_noship'];
        var displayString = ci+" "+shop_itemsString+" / "+shop_currencyString+" "+tp;
        var coupon = myObject['coupon'];
        if(coupon && coupon!=undefined&&coupon!=""){
            $("#code").val(coupon);
            coupon_freeShipping = myObject['free_shipping'];
        }
        if(ci>0 && tp){
            $sbd.show();
            $sbdd.html(displayString);
            $("#grandtotal").text(shop_currencyString+" "+tp);
            shop_grandtotal = tp;
            shop_nettotal = tpno;
            checkShippingCostDisplay();
            $("#inline-shop-basket").html($("#shop-basket").html());
        }
    });
}
var alertmodal_title="";
var alertmodal_ok_text="";
var alertmodal_cancel_text="";
function set_alertmodal_title(t){alertmodal_title=t;}
function set_alertmodal_ok_text(t){alertmodal_ok_text=t;}
function set_alertmodal_cancel_text(t){alertmodal_cancel_text=t;}
var alertmodal_ok_callback = alertModal_ignoreCouponWarning;
var alertmodal_cancel_callback = alertModal_remove;
var alertmodal_content = '<div class="modal" id="alertmodal"><h3>Title</h3><p>Text</p><form><input id="alertmodal_ok" type="submit" value="Ok" class="button close"> <input id="alertmodal_cancel" type="submit" value="Cancel" class="button close"></form><br /></div> ';
function shop_checkCoupon(){
    var t = $(".coupon_error").text();
    if(t!=""){
        if ($("#alertmodal").length == 0){
            $('#content').append($(alertmodal_content));
        }
        $("#alertmodal form").submit(function(e) { return e.preventDefault();});
        $("#alertmodal h3").html(alertmodal_title);
        $("#alertmodal_ok").attr("value", alertmodal_ok_text);
        $("#alertmodal_cancel").attr("value", alertmodal_cancel_text);
        $("#alertmodal p").html(t);
        $("#alertmodal_ok").click(function(){alertmodal_ok_callback()});
        $("#alertmodal_cancel").click(function(){alertmodal_cancel_callback()});
        $("#alertmodal").overlay({
            mask: {
                color: '#000',
                loadSpeed: 100,
                opacity: 0.7
            },
            closeOnClick: false,
            load: true
        });
        return false;
    }else{
        return shop_checkMinimal();
    }
}


function displayCustomAlert(msg){
    var content = '<div class="modal" id="alertmodal"><p>'+msg+'</p><form><input id="alertmodal_ok" type="submit" value="Ok" class="button close"></form><br /></div> ';
    $("#alertmodal").remove();
    $('#content').append($(content));
    $("#alertmodal form").submit(function(e) { return e.preventDefault();});
    $("#alertmodal").overlay({
        mask: {
            color: '#000',
            loadSpeed: 100,
            opacity: 0.7
        },
        closeOnClick: false,
        load: true
    });

}

function alertModal_ignoreCouponWarning(){
    $(".coupon_error").text("");
    document.checkout.submit();
}
function alertModal_remove(){
    $("#alertmodal").remove();
//    document.location.reload();
}
function shop_checkMinimal(){
    if(shop_grandtotal < shop_minOrderAmount){
        alert(shop_alertMinimalAmount);
        return false;
    }
    return true;
}
function checkShippingCostDisplay(){
    if(shop_nettotal<shop_shippingFree && !coupon_freeShipping){
        $("#shipment").removeClass("deleted_text");
    }else{
        $("#shipment").addClass("deleted_text");
    }
}


/* 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 + ')');
//            refreshMainShoppingBagDisplay();
//            displayTopShoppingBag();
//        });
//    }
}
function shop_basketOutputBindKeyUp(){
    $("#basketdisplay .quantity").bind('keyup', function(e) {
        var f = $(this);
        var v = secureDoubleDigitInputValue(f);
        if(v>0){f.val(v);}
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) { //Enter keycode
            shop_updateBagAmountForProduct(f);
        }
    }).blur(function(){
        var f = $(this);
        var v = secureDoubleDigitInputValue(f);
        if(v>0){f.val(v);}
        shop_updateBagAmountForProduct(f);

    });
    $("#basketdisplay #code").bind('keyup', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) { //Enter keycode
            coupon_verifyCouponEntry();
        }
    }).blur(function(){
        coupon_verifyCouponEntry();
    });
}
function shop_updateBagAmountForProduct(f){
    var uuid = f.attr("id").substring(2);
    var v = secureDoubleDigitInputValue(f);
    if(v>0){f.val(v);
        //write new amount to session and refresh display
        $.get(shop_basketScriptPath+"?cmd=ua&itemid="+uuid+"&amount="+v+"&ck="+new Date().getTime(),function(data){
            refreshMainShoppingBagDisplay();
        });
    }else{
        shop_checkForBagRemove(uuid);
    }
}

function refreshMainShoppingBagDisplay(){
    var url = document.location.href;
    if(url.indexOf("?")==-1){url = url+"?ck="+new Date().getTime();}else{url = url+"&ck="+new Date().getTime();}
    $('#basketdisplaywrapper').load(url+' #basketdisplay',function(){
        quantityFieldFocusHandling();
        checkShippingCostDisplay();
        displayTopShoppingBag();
        shop_basketOutputBindKeyUp();
        addCacheKillerToLinks();
        hijackBasketUpdateLink();


    });
//    alert(document.location.href);
}

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();
        }
    });

}

/* coupon handling */
var coupon_unknownCouponText = "UngŸltiger Coupon Code";
function setUnknownCouponText(t){
    coupon_unknownCouponText = t;
}
function coupon_removeCoupon(){
    $.get(shop_basketScriptPath+"?cmd=rmcp&ck="+new Date().getTime(),function(data){
        refreshMainShoppingBagDisplay();
    });
}
function coupon_verifyCouponEntry(){
    var v = $("#code").val();
    if(v==""||v==coupon_enterCouponText){
        coupon_removeCoupon();
    }else{
        $.get(shop_basketScriptPath+"?cmd=vfcp&coupon="+v+"&ck="+new Date().getTime(),function(data){
            if(data){
                var myObject = eval('(' + data + ')');
                if(myObject['recalculate']=='true'){
                    refreshMainShoppingBagDisplay();
                }else if(myObject['invalidcoupon']=='true'){
                    $("#code").val("");
                    displayCustomAlert(coupon_unknownCouponText);
                    refreshMainShoppingBagDisplay();
                }
            }
        });
    }
}


/* shop orderform */
var text_mandatoryempty ="";
var text_mandatoryagb ="";
var text_invalidemail = "";
var text_invalidzip = "";
var hasDLAddress = false;
var acceptedAGB = false;
function set_hasDLAddress(val){hasDLAddress=val;}
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 set_text_invalidzip(val){text_invalidzip = val;}


function checkDisplayDeliveryAdress(isbox){
    var box = document.orderform.select_dl;
    var isChecked = box.checked;
    if(!isbox){box.checked = !isChecked; isChecked = !isChecked}
    setDeliveryAddressState(isChecked);
    persistOrderInfoWithValueToSession("hasDLAddress",isChecked);
}
function setDeliveryAddressState(isChecked){
    if(isChecked){
        $("#delivery_address").slideDown("fast");
        hasDLAddress = true;
        $("#rg_country").html($("#countries_list_int").html());
    }else{
        $("#delivery_address").slideUp("fast");
        hasDLAddress = false;
        $("#rg_country").html($("#countries_list_ch").html());
        $("#rg_country").attr('selectedIndex', 0);
    }

}

function selectAGB(isbox){
    var box = document.orderform.select_agb;
    var isChecked = box.checked;
    if(!isbox){box.checked = !isChecked; isChecked = !isChecked}
    if(isChecked){
        acceptedAGB = true;
    }else{
        acceptedAGB = false;
    }
    persistOrderInfoWithValueToSession("acceptedAGB",isChecked);
}
function selectNewsletter(isbox){
    var box = document.orderform.select_newsletter;
    var isChecked = box.checked;
    if(!isbox){box.checked = !isChecked; isChecked = !isChecked}
    persistOrderInfoWithValueToSession("subscribeNewsletter",isChecked);
}


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 checkOrderFormCompletion(){
    var complete = true;
    var correctEmail = true;
    var f = document.orderform;
    var fieldNames = new Array("salutation","name","firstname","street","zip","city","country","email","phone");
    for(var i=0;i<fieldNames.length;i++){
        if(!checkMandatoryFieldValue(f, "rg_"+fieldNames[i])){complete = false;}
        if(hasDLAddress){
            if(!checkMandatoryFieldValue(f, "dl_"+fieldNames[i])){complete = false;}
        }
    }
    if(fieldNames[i]=="email"&&!hasCorrectFormat(fieldNames[i])){correctEmail = false;}
    if(!complete){alert(text_mandatoryempty);}
    correctEmail = checkEmailFormValue(f,"rg_email");

    if(!correctEmail){alert(text_invalidemail);complete=false;}
    if(!acceptedAGB){
        var box = document.orderform.select_agb;
        var isChecked = box.checked;
        if(isChecked){
            acceptedAGB = true;
        }else{
            alert(text_mandatoryagb);
            complete=false;
            $("#agbdiv").addClass("emptymandatory");
        }
    }else{
        $("#agbdiv").removeClass("emptymandatory");
    }
    /* check correct zip format - IE 4 digits */
    var zipFieldToCheck = $("#rg_zip");
    if(hasDLAddress){zipFieldToCheck = $("#dl_zip");}
    var zipFieldContent = zipFieldToCheck.val().replace(/[^0-9]/g, '');
    if(zipFieldContent.length!=4 || zipFieldContent.indexOf("0")==0){
        zipFieldToCheck.addClass("emptymandatory");
        complete = false;
        alert(text_invalidzip);
    }
    /* fill payment fields */
    fillInPaymentFieldsForPF(false);
    return complete;
//    return false;
}


function fillInPaymentFieldsForPF(submitForm){
    $("#CN").val(($("#rg_name").val()+", "+$("#rg_firstname").val()));
    $("#EMAIL").val($("#rg_email").val());
    $("#ownerZIP").val($("#rg_zip").val());
    $("#owneraddress").val($("#rg_street").val());
    $("#ownercty").val($("#rg_country").val());
    $("#ownertown").val($("#rg_city").val());
    $("#ownertelno").val($("#rg_phone").val());
    if(submitForm){
        document.orderform.submit();
    }
}

function checkMandatoryFieldValue(f, tn){
    var c = true;
    var tf = f[tn];
    if(tf){
        if(tf.value==""){
            $("#"+tn).addClass("emptymandatory");
            c = false;
        }else{
            $("#"+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;

}

/* add date to links for omiting cache */
function addCacheKillerToLinks(){
    $(".ckLink").each(function(){
        $(this).attr("href", $(this).attr("href")+"?ck="+new Date().getTime());
    });
}
function hijackBasketUpdateLink(){
    $("#updateBasketDisplay").click(function(evt){
        evt.preventDefault();
        setTimeout('refreshMainShoppingBagDisplay()',500);
    });

}
// form elements auto focus
var lastFocusedField = null;
var lastFocusedFieldValue = null;
function quantityFieldFocusHandling(){
    $("input[type=text].quantity").mouseenter(function(){
        $(this).focus();
        $(this).select();
        //check if last remembered value ist the same otherwise trigger blur on last input
        if(lastFocusedField!=null && lastFocusedFieldValue!=null){
            if(lastFocusedFieldValue!=lastFocusedField.val()){lastFocusedField.blur();}
        }
        lastFocusedFieldValue = $(this).val();
        lastFocusedField = $(this);
    });
}
function fieldFocusHandling(){
    $("input[type=text]:not(.quantity)").mouseenter(function(){
        $(this).focus();
        $(this).select();
    });
}
$(document).ready(function(){
    addCacheKillerToLinks();
    hijackBasketUpdateLink();

    /* slideout for tips&tricks and Q&A */
    $(".slideOutEntry").mousedown(function(){
        var act = !$(".slideOutEntryDetail",this).is(':visible');
        if(act){
            $(".slideOutEntryDetail.openEntry").slideUp();
            $(".slideOutEntryDetail.openEntry").removeClass("openEntry");
            $(".slideOutEntryDetail",this).slideDown();
            $(".slideOutEntryDetail",this).addClass("openEntry")
        }
    });

    fieldFocusHandling();
    quantityFieldFocusHandling();
    // main basket output listener
    shop_basketOutputBindKeyUp();
});

//* teaser and  background overlay *//

var $overlay_wrapper;
var $overlay_panel;
var openPanel;
function prepare_overlay(){
    if ( !$overlay_wrapper ) append_overlay();    
}
function show_overlay() {
    $overlay_wrapper.fadeIn(300);
}
function hide_overlay() {
    openHotSpotArray = new Array();
    $overlay_wrapper.fadeOut(100);
}
function append_overlay() {
    $overlay_wrapper = $('<div id="overlay"></div>').appendTo( $('BODY') );
    $overlay_panel = $('<div id="overlay-panel"></div>').appendTo( $overlay_wrapper );
    attach_overlay_events();
}

function attach_overlay_events() {

    $(window).scroll(function () {
        repositionOpenHotspot();
    });
    $(window).resize(function() {
        repositionOpenHotspot();
    });
    $(".closeTeaser").click(function(){
        hide_overlay();
    });
    $($overlay_wrapper).click( function(ev) {
         if (!$(ev.target).closest(".teaserPopup").length) {
             hide_overlay();
        };
    });
}
function showHotspots(panel,totalPanels){
    if(panel == 1){$("#slider .left").hide();}else{$("#slider .left").show();}
    if(panel == totalPanels){$("#slider .right").hide();}else{$("#slider .right").show();}
    openPanel = $("#panel_"+panel);
    $(".openTeaser", openPanel).fadeIn(200);
}
function hideHotspots(){
    $(".openTeaser").fadeOut(20);    
}
var openHotSpotArray = new Array();
function repositionOpenHotspot(){
    if(openHotSpotArray.length>4){
        displayHotspotPopup(openHotSpotArray[0],openHotSpotArray[1],openHotSpotArray[2],openHotSpotArray[3],openHotSpotArray[4],openHotSpotArray[5],openHotSpotArray[6])
    }
}
function displayHotspotPopup(hst,hsl,orientation,windowMode,popupid,imgtag){
    openHotSpotArray = [hst,hsl,orientation,windowMode,popupid,imgtag];
    prepare_overlay();
    var t = hst+parseInt(openPanel.offset().top);
    var l = hsl+parseInt(openPanel.offset().left);
    var pop = $(".teaserPopup", $("#"+popupid));
    if(orientation=="tl"){
    }else if(orientation=="tr"){
        l = l-parseInt(pop.css("width"));
    }else if(orientation=="bl"){
        t = t-parseInt(pop.css("height"));
    }else if(orientation=="br"){
        l = l-parseInt(pop.css("width"));
        t = t-parseInt(pop.css("height"));
    }
    if($(window).scrollTop()>0){
        t -= $(window).scrollTop();
    }
    if($(window).scrollLeft()>0){
        l -= $(window).scrollLeft();
    }

    $overlay_panel.removeClass();
    $overlay_panel.addClass(orientation);
    $overlay_panel.addClass(windowMode);
    $overlay_panel.html( imgtag+ $("#"+popupid).html() );
    $overlay_panel.css("top", t+"px");
    $overlay_panel.css("left", l+"px");
    show_overlay();
}



/* 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;
}

