/*
 * @author: Oliver Kreft / Klaus Baake
 */



// search slider
function initSlider() {
    
   
    
    $('#search_product_price_from').val(0);
    $('#search_product_price_to').val(300);
    $("#advanced-search-slider").slider({
       range: true,
       max: 1200,
       min: 0,
       values: [0, 300],
       step: 10,
       slide: function( event, ui ) {
               $('#search_product_price_from').val(ui.values[0]);
               $('#search_product_price_to').val(ui.values[1]);
        }
    });
    
}




/* Handling for Modal Dialogs */

function messageModal( message ) {
    $.modal( message , { overlayId: 'modal-loading-transparent' , opacity: 0, overlayClose: true }) ;
}

function showModal(res) {
    var modalDialog = $.modal( res , {  overlayId: 'modal-loading-transparent', containerId: 'container-hide', opacity: 0, overlayClose: true }) ;
    return modalDialog ;
    // close: false,
}



function openModal() {
    var modalDialog = $.modal( "" , { overlayId: 'modal-loading-transparent', containerId: 'container-hide', opacity: 0, overlayClose: true }) ;
    return modalDialog ;
}

function setModal( id ) {
    $( id ).modal({ overlayId: 'modal-layer-transparent' ,  containerId: 'container-hide', opacity: 0, overlayClose: true }) ;
}

function closeModal() {
    $.modal.close() ;
    document.body.style.cursor="default" ;
}

function close_dialog_tmwis(){
    closeModal() ;
    $('#dialog-tmwis').addClass('hide');
}


function close_dialog_tellafriend(){
    closeModal() ;
    $('#dialog-tellafriend').addClass('hide');
}

function close_dialog_error(){

    closeModal() ;
    $('#show-error').addClass('hide');

}

function close_dialog_sizeguide(){

    closeModal() ;
    $('#dialog-sizeguide').addClass('hide');

}

function close_dialog_zoom(){

    closeModal() ;
    $('#dialog-zoom-wrapper').addClass('hide');

}


/**
 * Setzt den Korrekten Preis zu der ausgewählten Variante
 */
function setPrice(){
		
	 var cId = $('#color-variants ol li[class="selected"]').attr('id');
	 
	 if(cId == undefined){
		 //cId = $('#color-variants ol li[class="out out-selected"]').attr('id');
		 cId = $('#color-variants ol li[class="out selected"]').attr('id');
		 if(cId == undefined){
			 return;
		 }
	 }
	 cId = cId.replace(/colorId-/, '');

	 var sId = $('#size-variants ol li[class="selected"]').attr('id');
	 if(sId == undefined){
		 sId = $('#size-variants ol li[class="out out-selected"]').attr('id');
		 if(sId == undefined){
			 //Preis ändern bevor eine Größe ausgewählt wird, resultiert in einer versteckten auswhal irgend einer Größe
			 sId = $('#size-variants ol li').attr('id');
			 if(sId == undefined){
				 return;
			 }
			 
			 exp = new RegExp("[^\.]*\."+cId+"\.(.*)");
			 for(var i in availableVariants)
			 {if(exp.exec(i)){
				 if(availableVariants[i].price && availableVariants[i].originalPrice){
					//Sale - Preis gefunden, ersetzt Std preis
					 sId = RegExp.$1;
					 break;
				 }
			  }
			 }
			 
		 }	 
	 }
	 sId = sId.replace(/sizeId-/, '');
	 
	 $('#skudetails-price').parent().removeClass('old-price');
	 $('#sale-price').remove();
	 
	 pId = $(".add-to-cart").attr('id');
	 pId = pId.replace(/product-/, '');

	 var price = availableVariants[pId + '.' + cId + '.' + sId].price;
	 var originalPrice = availableVariants[pId + '.' + cId + '.' + sId].originalPrice;
	 
	 if(originalPrice != undefined){
		 $('#skudetails-price').parent().addClass('old-price');
		 $('#skudetails-price').parent().after("<span id='sale-price'>"+currency+" "+price+"</span>");
		 price = originalPrice;
	 }
	 
	 if(price != undefined){
		 $('#skudetails-price').html(price);
	 }	 
}

/**
 * 
 * Ändert die Vorschaubilder (Farbbilder der Varianten)
 */
function setPics(cId){
	var src = $('#main-ads-img').attr('src');

	firstIndex = src.indexOf("product", 0);
	seconIndex = src.indexOf("_", 0);
	
	var url = src.slice(0, firstIndex+14) + cId + src.slice(seconIndex, src.length);
	
	$('#main-ads-img').attr('src', url);
	
	$('#skudetails-product-views img').each(function(){
		var src = this.src;
		
		firstIndex = src.indexOf("product", 0);
		seconIndex = src.indexOf("_", 0);
		
		var url = src.slice(0, firstIndex+15) + cId + src.slice(seconIndex, src.length);
		this.src = url;
	});
} 

/*
 * Updates the prices from onestepcheckout
 */
function updatePrices(){

	var price = $('#subtotal-price').html();
	price = price.replace('.', ''); 
	price=parseFloat(price.replace(',', '.'));
	
	var sprice = $('#shipping-price').html();
	sprice = sprice.replace('.', '');	
	sprice=parseFloat(sprice.replace(',', '.'));
	
	var pprice = $('#payment-price').html();
	pprice = pprice.replace('.', '');	
	pprice=parseFloat(pprice.replace(',', '.'));
			
	var couponvalue = $('#cart-coupons-total').html();
	
	$('#total-price').html(formatNumber(price+sprice+pprice-couponvalue));
	$('#total-tax').html(formatNumber( ( price+sprice+pprice-couponvalue ) / ( 100 + tax_value ) * tax_value ));
	
}

function formatNumber(num)
{    
    var n = num.toString();
    var nums = n.split('.');
    var newNum = "";
    if (nums.length > 1)
    {
        var dec = nums[1].substring(0,2);
        if(dec.length == 1){
        	dec = dec+'0';
        }
        
        newNum = nums[0] + "," + dec;
    }
    else
    {
    newNum = num + ",00";
    }
    return newNum;
}


function zoomview( img_id ) {
            var zv = new ZoomoViewer();
            zv.clientID = 93636;
            zv.width = 420;
            zv.height = 560;
            zv.addPlugIn("gui_default");
            zv.addImage(img_id);
            zv.start('#zoomo');
        }


/*
 * Non Stop Page Tracking
 */
function getURLParam(paramName){
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?"));
        var ParamArray = strQueryString.split("&");
        for (var i = 0; i < ParamArray.length; i++) {
            if (ParamArray[i].indexOf("nsctrid=") > -1) {
                var ParamValueArray = ParamArray[i].split("=");
                strReturn = ParamValueArray[1];
                break;
            }
        }
    }
    return strReturn;
}

function doNonStopURLParamTracking(paramName, locale, pageWePointerTo){
    
	var nonStopURLParam = getURLParam(paramName);
	
    if (nonStopURLParam.length > 0) {
        // Parameter available. Write it to the users cookie
        var today = new Date();
        // let it expire in 45 day
        expiryDate = new Date(today.getTime() + 1000 * 60 * 60 * 24 * 45);
        document.cookie = "nsctrid=" + nonStopURLParam + "; expires=" + expiryDate.toGMTString() + ";path=/";
        // now write the cookie to the users session in CMS
        $(document).ready(function(){
            // fire the post
            $.post(pageWePointerTo, {
                locale: locale,
                nonStopURLParam: nonStopURLParam
            });
        });
    }
	
    else {
        // We've to check if the cookie was set in the past 45 days
        var myCookies = document.cookie;
        var myNonStopCookieValue = "";
		
        if (myCookies.indexOf(";") > -1) {
            var myCookiesArray = myCookies.split(";");
            for (var i = 0; i < myCookiesArray.length; i++) {
                if (myCookiesArray[i].indexOf("nsctrid") > -1) {
                    var myNonStopCookie = myCookiesArray[i].split("=");
                    var myNonStopCookieValue = myNonStopCookie[1];
                }
            }
        }
		
        if (myNonStopCookieValue.length > 0) {
            // we had no parameter BUT a valid cookie. So let's write it into the users session
            $(document).ready(function(){
                // fire the post
                $.post(pageWePointerTo, {
                    locale: locale,
                    nonStopURLParam: myNonStopCookieValue
                });
            });
        }
    }
}

function initTrustedShop(){
	$("#trustedshop").unbind('click').click(function(){
		handleTrustedShop(this.value);
	});
}

  
