function hideDiv(divid){
    $(divid).fadeOut("fast");
}
var galleryID = '#gallerydetail';
var galleryBasePath = '';
var simpleModalDialog = '';

function showSingleImageDetail(img,w,h,t){
    w = (w*1)+2;
    h = (h*1)+2;
    var style = 'width: '+w+'px; height: '+h+'px';
    $('#gallerydetail').attr('style', style);
    $('#gallerydetail').removeClass();
    $('#gallerydetail').addClass('singleEntry hiddenEntry');
    $('#gallerydetail').html('<img src="'+img+'" alt="'+t+'" title="'+t+'"/>');
    $("#gallerydetail").modal({close:true, overlayClose:true,overlay:90, overlayCss: {backgroundColor:"#000"},onOpen: function (dialog) {
        simpleModalDialog = dialog;
        dialog.overlay.fadeIn('fast', function () {
            dialog.data.hide();
            dialog.container.fadeIn('fast', function () {
                dialog.data.fadeIn('fast');
            });
        });
    }});
    $(".singleEntry").mousedown(function(){
        $.modal.close();
    });
  }


function fillGalleryDetail(img, txt){
    var borderWidth = 22;
    var imgWidth = img.width;
    var imgHeight = img.height;
    var containerWidth = imgWidth + borderWidth + borderWidth;
    var containerHeight =  imgHeight + borderWidth + borderWidth;
    var detailContent = '<div style="width: '+containerWidth+'px; height: '+containerHeight+'px;" class="image-border image-border-left">';
    detailContent += '<div class="image-border-t-r" style="left: '+(imgWidth-102)+'px; top: -73px"/>';
    detailContent += '<div class="image-border-b-l"/>';
    detailContent += '<div class="gal-close" style="width: '+containerWidth+'px"><a href="javascript:$.modal.close();">fenster schliessen</a></div>';
    if(window.galPrvImgSrc && totalImages > 0){detailContent += '<div class="gal-prv" style="top: '+(containerHeight-90)/2+'px"><a href="javascript:checkModalContent(true)"><img src="'+window.galPrvImgSrc+'" alt="prv"/></a></div>';}
    if(window.galNxtImgSrc && totalImages > 0){detailContent += '<div class="gal-nxt" style="top: '+(containerHeight-90)/2+'px"><a href="javascript:checkModalContent()"><img src="'+window.galNxtImgSrc+'" alt="nxt"/></a></div>';}
    detailContent += '<div class="gal-txt">'+txt+'</div>';
    detailContent += '<div class="image-content" style="height: '+imgHeight+'px;">';
    detailContent += '<a href="javascript:checkModalContent();"><img width="'+imgWidth+'" src="'+img.src+'"/></a>';
    detailContent += '</div>';
    detailContent += '</div>';
    return detailContent;
}
function displayModalContent(me){
    window.currentImageNo = me;
    var tmpimg = new Image();
  $(tmpimg)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default
      $(this).hide();
      $(galleryID).html(fillGalleryDetail(this, bigImageTitles[me]));
      $("#gallerydetail").modal({overlayClose:true,overlay:90, overlayCss: {backgroundColor:"#000"},onOpen: function (dialog) {
          simpleModalDialog = dialog;
            dialog.overlay.fadeIn('fast', function () {
                dialog.data.hide();
                    dialog.container.fadeIn('fast', function () {
                        dialog.data.slideDown('slow');
                    });
                });
            }});
    })
    .attr('src', bigImageHandles[me]);
}



function checkModalContent(back){
    $(galleryID).fadeOut("fast", function () {
        if(back == true){
            currentImageNo--;
            if(currentImageNo<0){currentImageNo = totalImages;}
        }else{
            currentImageNo++;
            if(currentImageNo>totalImages){currentImageNo = 0;}
        }
        resizeModal(currentImageNo);
    });
}


function resizeModal(me){
    var tmpimg = new Image();
    tmpimg.onload = function(){
        var pic_real_width = this.width;
        var pic_real_height = this.height;
        simpleModalDialog.container.width(pic_real_width+44);
        simpleModalDialog.container.height(pic_real_height+44);
        $(galleryID).html(fillGalleryDetail(this, bigImageTitles[me]));
        $(window).trigger('resize.simplemodal');
        $(galleryID).fadeIn("fast");
    }
    tmpimg.src = bigImageHandles[me];
}

function removeDefault(formField, value){
    if(formField.value == value){
        formField.value = "";
    }
}
function resetDefault(formField, value){
    if(formField.value == ""){
        formField.value = value;
    }
}


function showMailForm(){
    //$(".minimailform").slideDown("slow");
    $(".minimailform").slideToggle("slow");
    $(".minimailform").append("<input type='hidden' name='sendminimail' value='true' />");
}
function hideMailForm(){
    $(".minimailform").slideUp("fast");
}
var detailHandles = new Array();
var minigalTitles = new Array();
var minigalActImg = 1;
function setDetailHandles(id,arr){
    detailHandles[id] = new Array();
    detailHandles[id] = arr;
}
function setMinigalTitles(id,arr){
    minigalTitles[id] = new Array();
    minigalTitles[id] = arr;
}
function showMinigal(no, id, ignore){
    if(!ignore){
        var isVisible = $("#"+id).is(':visible');
        if(isVisible && minigalActImg == no*1){return hideMinigal(id);}
    }
    minigalActImg = no*1;
    $("#"+id).slideDown("slow");
    $("#"+id+" .detail_img").css("background-image", "url('"+detailHandles[id][minigalActImg]+"')");
    $("#"+id+" .minigal_img_title").html(minigalTitles[id][minigalActImg]);
}
function showYouTubeMinigal(no, id, ignore){
    if(!ignore){
        var isVisible = $("#"+id).is(':visible');
        if(isVisible && minigalActImg == no*1){return hideMinigal(id);}
    }
    minigalActImg = no*1;
    $("#"+id).slideDown("slow");
    var width = 700;
    var height = 425;
    var c = detailHandles[id][minigalActImg];
    var clip = '<object width="'+width+'" height="'+height+'"><param name="movie" value="http://www.youtube.com/v/'+c+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+c+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'+width+'" height="'+height+'"></embed></object>' 
    $("#"+id+" .moviecontainer").html(clip);
    $("#"+id+" .minigal_img_title").html(minigalTitles[id][minigalActImg]);
}
function showNext(id){
    minigalActImg++;
    if(minigalActImg>=detailHandles[id].length){minigalActImg=1;}
    showMinigal(minigalActImg, id, true);
}
function showPrevious(id){
    minigalActImg--;
    if(minigalActImg<1){minigalActImg=detailHandles[id].length-1;}
    showMinigal(minigalActImg, id, true);
}
function hideMinigal(id){
    $("#"+id).slideUp("fast");
}


function revealContent(){
    $("#contentparagraphs").fadeIn("fast");
}
var contentFadeInTime = 5000;
function setContentFadeInTime(t){
    contentFadeInTime = t;
}

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

/* home */
function hideHomeNavigation(){
//    $("#teasers").fadeTo("slow", 0.001);
//    $("#footerwrap").fadeTo("slow", 0.001);
    $("#teasers").fadeOut("slow");
    $("#footercontainer").fadeOut("slow");
}
function showHomeNavigation(){
//    $("#teasers").fadeTo("fast", 1);
//    $("#footerwrap").fadeTo("fast", 1);
    $("#teasers").fadeIn("slow");
    $("#footercontainer").fadeIn("slow");
}

/* shop */
var currentLanguage = "de";
var basePath  = "/";
var scriptpath = basePath+"/custom/shop/baskethandling.jsp";
var text_countitemstext = "";
var text_totalchftext = "";
var text_emptybaskettext = "";
var text_updatedbasket = "";
var text_basketoverweigt = "";
var text_removedfrombasket = "";
var text_mandatoryempty ="";
var text_mandatoryagb ="";
var hasDLAdress = false;
var acceptedAGB = false;
var SHIPPING_MODE_POST = 0;
var SHIPPING_MODE_KURIER = 1;
var shippingMode = SHIPPING_MODE_POST;
var shippingInformation = new Array("","","","","");

var CHF = "CHF";

function setCurrentLanguage(lang){
    currentLanguage = lang;
}
function putItemInBasket(itemid, isform){
    var amount = document.basket[itemid].value;
    if(isNaN(amount)){
        document.basket[itemid].value = 1;
    }else{
        handleBasketItemsAmount(itemid, amount, true, true);
    }
    if(isform){return false;}
}
function handleBasketItemsAmount(itemid, amount, displaybasket, addtoamount){
    $.get(scriptpath+"?cmd=ub&add="+addtoamount+"&itemid="+itemid+"&amount="+amount+"&lang="+currentLanguage,function(data){
        var myObject = eval('(' + data + ')');
        displayBasketUpdateFeedback(myObject['success']=='true');
        if(displaybasket){updateBasketDisplay(myObject['countitems'], myObject['totalprice'])};
    });
}
function showBasketitemsInDisplay(){
    $.get(scriptpath+"?cmd=gt",function(data){
        var myObject = eval('(' + data + ')');//eval(data);
        updateBasketDisplay(myObject['countitems'], myObject['totalprice']);
    });
}
function updateBasketDisplay(countitems, totalchf){
    var text = text_emptybaskettext;
    if(countitems > 0 && totalchf > 0){
        text = countitems+" "+text_countitemstext+", "+text_totalchftext+" "+totalchf;
    }
    $("#shoping_basket_info").html(text);
}

function updateBasketAmount(itemid, isform){
    var amount = document.basket["buy"+itemid].value;
    var compare = document.basket["amount"+itemid].value;
    if(!isNaN(amount) && amount != compare){
        handleBasketItemsAmount("buy"+itemid, amount, true, false);
    }else{
        document.basket["buy"+itemid].value = document.basket["amount"+itemid].value;
    }
}
function removeFromBasket(itemid){
    $.get(scriptpath+"?cmd=rm&itemid="+itemid+"&lang="+currentLanguage,function(data){
        var myObject = eval('(' + data + ')');
        if(myObject['success']=='true'){
            alert(text_removedfrombasket);
            window.location.reload();
        }
    });
}
function displayBasketUpdateFeedback(success){
    if(success){
        alert(text_updatedbasket);
    }else{
        alert(text_basketoverweigt);
    }
}

function emptyBasket(){
    $.get(scriptpath+"?cmd=eb");
    updateBasketDisplay(0,0);

}

function checkDisplayDeliveryAdress(isbox){
    var box = document.orderform.select_dl;
    var isChecked = box.checked;
    if(!isbox){box.checked = !isChecked; isChecked = !isChecked}
    if(isChecked){
        $("#delivery_address").slideDown("fast");
        hasDLAdress = true;
    }else{
        $("#delivery_address").slideUp("fast");
        hasDLAdress = false;
    }
    persistOrderInfoWithValueToSession("hasDLAddress",isChecked);
    countryCanged();
}
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 selectShipingMode(field){
    document.orderform.shipping[field].checked = true;
    shippingMode = field;
    persistOrderInfoWithValueToSession("shippingMode",shippingMode);
    displayOrderTotal();
}
function set_agb_selection_state(state){
    if(state == true){acceptedAGB = true;}
}
function checkOrderFormCompletion(){
    displayOrderTotal();
    var complete = true;
    var f = document.orderform;
    var fieldNames = new Array("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(hasDLAdress){
            if(!checkMandatoryFieldValue(f, "dl_"+fieldNames[i])){complete = false;}
        }
    }
    if(!complete){alert(text_mandatoryempty);}
    if(!acceptedAGB){
        alert(text_mandatoryagb);
        complete=false;
        $("#agbdiv").addClass("emptymandatory");
    }else{
        $("#agbdiv").removeClass("emptymandatory");
    }
    return complete;
//    /* TODO: remove test return: */
//    return true;
}
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 displayOrderTotal(){
    var cc = document.orderform.rg_country.value;
    if(document.orderform.select_dl.checked){
        cc = document.orderform.dl_country.value; 
    }
    var sh = get_radio_value(document.orderform.shipping);
    $.get(scriptpath+"?cmd=gtincl&cc="+encodeURIComponent(cc)+"&sh="+sh,function(data){
        var myObject = eval('(' + data + ')');
        $("#total_articles").html(myObject['countitems']);
        $("#total_excl").html(CHF+" "+myObject['totalprice']);
        $("#total_shipping").html(CHF+" "+myObject['shippingcost']);
        $("#total_incl").html(CHF+" "+myObject['finalbill']);
    });

}
function countryCanged(field){
    if(field==undefined){
        if(hasDLAdress){
            field = document.orderform.dl_country;
        }else{
            field = document.orderform.rg_country;
        }
    }
    persistOrderInfoToSession(field);
    var cc = field.value;
    var updateSM = true;
    if(field.name == "dl_country"){
        hasDLAdress = true;
    }else{
        //if we have a delivery address no need to update shipping modes
        if(hasDLAdress){updateSM = false;}
    }
    if(updateSM){
        /* 0=post only 1=kurier only 2=post and kurier */
        $.get(scriptpath+"?cmd=gtsm&cc="+encodeURIComponent(cc),function(data){
            var myObject = eval('(' + data + ')');
            var t = myObject['shippingmodes']*1;
            if(t==0){
                $("#shipping_post").show();
                $("#shipping_kurier").hide();
                selectShipingMode(SHIPPING_MODE_POST);
                shippingMode = SHIPPING_MODE_POST;
            }else if(t==1){
                $("#shipping_post").hide();
                $("#shipping_kurier").show();
                selectShipingMode(SHIPPING_MODE_KURIER);
                shippingMode = SHIPPING_MODE_POST;
            }else if(t==2){
                $("#shipping_post").show();
                $("#shipping_kurier").show();
                selectShipingMode(shippingMode);
            }
            //display shippingmode info
            var ci = myObject['countryindex']*1;
            /* 0=ch 1=eu 3=int */
            var pi = shippingInformation[ci];
            var ki = "";
            if(ci>0){ki=shippingInformation[ci+1];}
            $("#shipping_post_info").html(pi);
            $("#shipping_kurier_info").html(ki);
            displayOrderTotal();
        });            
    }
}

function persistOrderInfoWithValueToSession(fieldname,value){
    $.get(scriptpath+"?cmd=sf&field="+fieldname+"&value="+value);
}
function persistOrderInfoToSession(field){
    var value = encodeURIComponent(field.value);
    $.get(scriptpath+"?cmd=sf&field="+field.name+"&value="+value);
}
function showPayment(){
    $.get(scriptpath+"?cmd=gpurl",function(data){
        var myObject = eval('(' + data + ')');
        var t = myObject['paymenturl'];
        window.location.href = t;
        //OpenSaferpayWindowJScript(t);
        //alert("zur Zahlung");
    });
}



function set_basePath(val){basePath = val; scriptpath = basePath+"/custom/shop/baskethandling.jsp";}
function set_text_countitemstext(val){text_countitemstext = val;}
function set_text_totalchftext(val){text_totalchftext = val;}
function set_text_emptybaskettext(val){text_emptybaskettext = val;}
function set_text_updatedbasket(val){text_updatedbasket = val;}
function set_text_basketoverweigt(val){text_basketoverweigt = val;}
function set_text_removedfrombasket(val){text_removedfrombasket = val;}
function set_text_mandatoryagb(val){text_mandatoryagb = val;}
function set_text_mandatoryempty(val){text_mandatoryempty = val;}
function set_text_shipping_information(val){shippingInformation = val};



$(document).ready(function(){
     $(".hideLink").mousedown(function(){
        $("#contentparagraphs").fadeOut("fast");
        setTimeout('revealContent()', contentFadeInTime)
    });

});



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