/* GALLERY */

Event.observe(window, 'load', init_js);

Event.observe(window, 'load', toggle_back_link);

function toggle_back_link()
{
	backlink = getCookie('BACK_LINK');
	
	if(backlink.match(/search/))
	{
		backlink = unserialize(backlink);
		$$('.back')[0].select('a')[0].writeAttribute('href', backlink);
	}
}


function init_js() {
	var preview_imgs = $$('.preview');
	var target = $('big_image');
	var style_TT = $('style_tipp_target');

	/* Setting the initial state of Gallery Images */
	preview_imgs.each(function(s, index) {
		if (index == 0) {
			new Effect.Opacity(s, { from: 1.0, to: 1, duration: 0.01 });
		} else {
			new Effect.Opacity(s, { from: 1.0, to: 0.5, duration: 0.01 });
		}
	});
	if (style_TT != null)
	{
		style_TT.onmousemove = function(e) {
			if (e == null){
				mouseX1 = mouseX(window.event);
				mouseY1 = mouseY(window.event);
			} else {
				mouseX1 = Event.pointerX(e);
				mouseY1 = Event.pointerY(e);
			}

			$('tooltip2').show().setStyle( {
				left : (mouseX1 + 15) + 'px',
				top : (mouseY1 + 15) + 'px'
			});
			$('tooltip2');
			return true;
		};

		style_TT.onmouseout = function(e) {
			$('tooltip2').hide();
		};
	}

	if( $('bigImageDummy') != null)
	{
		Event.observe('bigImageDummy','click',function(){
			$('bigImageDummy').hide();
		});
	}
}

/* ZOOMBOX */

var zoom_box_height = 0;
var zoom_open = false;
var zoom_akt = 'a';
var last_element = null;
function zoom(img, el) {
	if (last_element == null)
		last_element = document.getElementById("link_ad_a");
	if (last_element != el) {
		new Effect.Opacity(last_element.id, {
			duration : 0.5,
			from : 1,
			to : 0.5
		});
		new Effect.Opacity(el.id, {
			duration : 0.5,
			from : 0.5,
			to : 1
		});

		new Effect.Morph(last_element.up(), {
			style: 'inactive',
			duration: 0.5
		});

		new Effect.Morph(el, {
			style: 'active',
			duration: 0.5
		});

		last_element = el;
	}
	if (img == 'close') {
		$('box_general').setStyle( {
			minHeight : zoom_box_height + 'px',
			height : zoom_box_height + 'px'
		});
		Element.removeClassName($('content_inner'), 'zoom');
		zoom_open = false;
		img = zoom_akt;
	} else if (img == 'open') {
		zoom_open = true;
		if (!zoom_box_height) {
			zoom_box_height = $('box_general').getHeight();
		}
		Element.addClassName($('content_inner'), 'zoom');

		img = zoom_akt;
	}
	zoom_akt = img;
	$$('.zoom_detail').each(function(el) {
		Element.removeClassName(el, 'active');
	});

	mojo_zoom_image = $('big_img_zoom').down('img.mojozoom_img');
	mojo_zoom_image.src = zoom_huge_images[img];

	Element.addClassName($('link_' + img + 'a'), 'active');

	if (zoom_small_images[img]) {
		var newImg = new Image();
		newImg.src = zoom_small_images[img];

		newImg.onLoad = new function() {
			new Effect.Fade('big_img', {
				duration : 0.3,
				from : 1,
				to : 0.1
			});

			setTimeout(function() {

				$('big_img').src = newImg.src;
				new Effect.Fade('big_img', {
					duration : 0.4,
					from : 0.5,
					to : 1
				});
				document.body.style.cursor = 'default';

			}, 320);

		};
	}
}

function size_active(el, currency, price, size, price_orig, maxAmount) {
	// hande made toggle for a checkbox
	var Amount = new Array();
	for (var i = 1; i <= maxAmount; i++)
	{
		Amount[i-1] = i;
	}
	if ($(el.htmlFor).checked) {
		$(el.htmlFor).checked = false;
		el.removeClassName('labelactive');
		size = '';
	} else {
		// unchecks all checked boxes (better: radiobutton)
		$$(".sizeCheckbox").each(function(element) {
			element.checked = false;
			$$('.labelactive').each(function(el) {
				el.removeClassName('labelactive');
			});
		});
		// end
		$(el.htmlFor).checked = true;
		el.addClassName('labelactive');
		if (price == price_orig) {
			$('prod_price').innerHTML = "" + price + " " + currency;
		} else {
			$('prod_price').innerHTML = "<span id='prod_oldPrice'>" + price_orig + "</span> " + currency + " &nbsp; <span id='prod_newPrice'>" + price + " " + currency + "</span>";
		}
	}
	$('add_to_bag_size').value = size;
	if ($('size_error_message')) {$('size_error_message').style.visibility = "hidden";}
	initDropDownList('bag_amount',Amount,'add_to_bag_amount');
}

var bag_height;
var bag_is_static = false;

function add_to_bag_epoq(style, color, pAmount, pSize, pShow, epoqUrl) {
	//alert(epoqUrl);
	add_to_bag(style, color, pAmount, pSize, pShow, true);

	new Ajax.Request(epoqUrl, {
		  onSuccess: function(transport) {
		  }
	});
}

function add_to_bag_epoq_test(style, color, pAmount, pSize, pShow) {
	//alert(epoqUrl);
	top.win.close();
	add_to_bag(style, color, pAmount, pSize, pShow, true);

}

function add_to_bag_epoq_info(style, color, pAmount, pSize, pShow) {
	//alert(epoqUrl);
	top.win.close();
	add_to_bag(style, color, pAmount, pSize, pShow, true);

}

function add_to_bag(style, color, pAmount, pSize, pShow) {
	var amount = pAmount;

        //Hier war (siehe svn) eine nicht erklärliche / Ersetzung bei sizes
	//Die dazu führte, dass Größen nicht gefunden wurden und man diese
	//Artikel nicht zum Warenkorb hinzufügen konnte.

	size = encodeURIComponent(pSize);
	if (!style || !color)
		return false;

	var sizes= new Array(size);
	if (sizes == '') {
		$('size_error_message').style.visibility = "visible";
		return false;
	}

	if(arguments.length > 5)
	{
		site_reload = true;
	}
	else
	{
		site_reload = false;
	}


	new Ajax.Request("/?site=product_to_bag&style_id=" + style + "&colorcode="
			+ color + '&sizes=' + sizes + "&amount=" + amount + "&action=process", {
		method : 'post',
		parameters : '1=1',
		onSuccess : function(rtn, json) {
			try{
				cartProduct(trackingProduct.id,
						trackingProduct.sid,
						trackingProduct.channel,
						amount,
						trackingProduct.price
				);
			}
			catch(e){};
			if (pShow)
			{
				$('top').scrollTo();
				showBasketBox(true);
				isBasketBagOpen = true;
	        	answer = eval('('+rtn.responseText+')');
	        	$('bdBasketBoxCount').innerHTML		= answer.articles;
                if (parseInt(answer.articles) == 1) {
                    $('bdBasketBoxCountSingular').show();
                    $('bdBasketBoxCountPlural').hide();
                } else {
                    $('bdBasketBoxCountSingular').hide();
                    $('bdBasketBoxCountPlural').show();
                }
	        	$('bdBasketBoxSummary').innerHTML = answer.amount;
	        	$('bdBasketBoxText').innerHTML		= answer.content;
	        	setTimeout( "close_add_to_bag(site_reload)", 6000);
	        	$('basket_amount').innerHTML		= answer.amount;
	        	$('basket_count').innerHTML = answer.articles;
	        	//$('basket').removeClassName('empty');
	        	//$('basket_a_checkout').setStyle({'color': '#E9E9E9'});
	        	//$('WarenkorbCount').setStyle({'color': '#E9E9E9'});
	        	//$('WarenkorbCount_a_checkout').setStyle({'color': '#E9E9E9'});
	        	//$('basket_count').setStyle({'color': '#E9E9E9'});
	        	//$('WarenkorbPrice').setStyle({'color': '#E9E9E9'});
	        	//$('WarenkorbPrice_a_checkout').setStyle({'color': '#E9E9E9'});
	        	//$('basket_amount').setStyle({'color': '#E9E9E9'});

	        	$('basket_arrow').writeAttribute({'src': '/images/layout/RightArrow.png'});
	        	// EPOQ ausschalten
	        	 callEpoq(answer.warenKorb);
           }
		}
	});
	return false;
}


function add_to_bag_multi(pAmounts,pSize,pIds,pColors,pAllPrice) {
	amount = pAmounts.join("_");
	style = pIds.join("_");
	size = pSize.join("_");
	color = pColors.join("_");
	new Ajax.Request("/?site=product_to_bag&style_ids=" + style + "&colors="
			+ color + '&sizes=' + size + "&amounts=" + amount +"&price="+pAllPrice.toFixed(2)+"&action=process&op=multi&noseo=1", {
		method : 'post',
		parameters : '1=1',
		onSuccess : function(rtn, json) {
				$('top').scrollTo();
				showBasketBox(true);
				isBasketBagOpen = true;
	        	answer = eval('('+rtn.responseText+')');
	        	$('bdBasketBoxCount').innerHTML		= answer.articles;
                if (parseInt(answer.articles) == 1) {
                    $('bdBasketBoxCountSingular').show();
                    $('bdBasketBoxCountPlural').hide();
                } else {
                    $('bdBasketBoxCountSingular').hide();
                    $('bdBasketBoxCountPlural').show();
                }
	        	$('bdBasketBoxSummary').innerHTML = answer.amount;
	        	$('bdBasketBoxText').innerHTML		= answer.content;
	        	setTimeout( "close_add_to_bag()", 6000);
	        	$('basket_amount').innerHTML		= answer.amount;
	        	$('basket_count').innerHTML = answer.articles;

	        	$('basket_a_checkout').setStyle({'color': '#E9E9E9'});
	        	$('WarenkorbCount').setStyle({'color': '#E9E9E9'});
	        	$('WarenkorbCount_a_checkout').setStyle({'color': '#E9E9E9'});
	        	$('basket_count').setStyle({'color': '#E9E9E9'});
	        	$('WarenkorbPrice').setStyle({'color': '#E9E9E9'});
	        	$('WarenkorbPrice_a_checkout').setStyle({'color': '#E9E9E9'});
	        	$('basket_amount').setStyle({'color': '#E9E9E9'});

	        	$('basket_arrow').writeAttribute({'src': '/images/layout/RightArrow.png'});
		}
	});
	return false;
}

function showBasketBox(show)
{
	if(show)
	{
		$('bdBasketBox').style.top = ($('basket').offsetTop+40) +"px";
		$('bdBasketBox').style.left = ($('basket').offsetLeft-149) +"px";
		new Effect.BlindDown('bdBasketBox',{duration: 0.7});
	}
	else
	{
        var queue = Effect.Queues.get('bdBasketBox');
        queue.each(function(effect) { effect.cancel(); });

		$('bdBasketBox').fade();
	}
	return false;
}
function close_add_to_bag(reload)
{
        if($('bdBasketBox').visible())
        {
            Effect.SlideUp('bdBasketBox', {duration: .5});
            if(reload==true)
            {
                window.location.reload();
            }
        }
}

function reset_add_to_bag() {
	var wel = $('warenkorb_outer');
	if (typeof document.body.style.maxHeight == "undefined") {
		wel.removeClassName('ie6fix');
	}
	wel.setStyle( {
		left : '',
		top : '0px',
		height : bag_height + 'px',
		position : '',
		display : ''
	});
}

function showStyleTip() {
	$('styleTip_Box').appear( {
		duration : 0.2
	});
	Event.observe($('closebtn'), 'click', function(e) {
		$('styleTip_Box').fade( {
			duration : 0.2
		});
	});

}

function calculateMiniBasket(pCurrency)
{
	$all_price = 0;
	$forms = document.forms;
	for (var i = 0; i <= $forms.length-1; i++)
	{
		$formName = $forms[i].name;
		$substr = $formName.substring(0,15);
		add = false;
		if($substr == 'formInputValues')
		{
			text = $formName+'Add';
			add = $(text).checked;
			$els = $($formName).childNodes;
			price = 0;
			amount = 0;

			for (var j = 0; j <= $els.length -1; j++)
			{
				if (($els[j].localName == 'input') || ($els[j].nodeName == 'INPUT'))
				{

					switch ($els[j].name) {
						case "price":
							price = $els[j].value;
							break;
						case "amount":
							amount = $els[j].value;
							break;
						case "choise":
							add = $els[j].checked;
							break;
					}
				}
			}
			if (add) $all_price = $all_price +(price*amount);
		}
	}
	$('miniBasketSum').innerHTML = $all_price.toFixed(2) +" "+pCurrency;
	//alert($all_price.toFixed(2));
}

function addMiniBasket2Bag()
{	var amounts = [];
	var sizes = [];
	var ids = [];
	var colors = [];
	$all_price = 0;
	$forms = document.forms;
	for (var i = 0; i <= $forms.length-1; i++)
	{
		$formName = $forms[i].name;
		$substr = $formName.substring(0,15);
		add = false;
		if($substr == 'formInputValues')
		{
			text = $formName+'Add';
			add = $(text).checked;
			$els = $($formName).childNodes;
			amount = 0;
			size = '';
			id = 0;
			color = '';
			for (var j = 0; j <= $els.length -1; j++)
			{

				if (($els[j].localName == 'input') || ($els[j].nodeName == 'INPUT'))
				{
					switch ($els[j].name) {
						case "price":
							price = $els[j].value;
							break;
						case "amount":
							amount = $els[j].value;
							break;
						case "size":
							size = $els[j].value;
							break;
						case "style_id":
							id = $els[j].value;
							break;
						case "colorcode":
							color = $els[j].value;
							break;
						case "choise":
							add = $els[j].checked;
							break;
					}
				}
			}
			if (add)
			{
				$all_price = $all_price +(price*amount);
				amounts.push(amount);
				sizes.push(size);
				ids.push(id);
				colors.push(color);
			}
		}
	}
	if (amounts.length > 0)
	{
		add_to_bag_multi(amounts,sizes,ids,colors,$all_price);
	} else {
		alert('Bitte ein Produkt auswählen!');
	}
}

function switchBigImage(pFormsCount)
{
	$('bigImageDummy').src = $('bigImage'+pFormsCount).src;

	Event.observe('bigImageDummy','load',function(){
		$('bigImageDummy').show();
	});

}

function resizeStyleTipDiv()
{
	normalS = 280;
	normalH = 296;
	normalA = 383;
	flow_box = $('flow_box').scrollHeight;
	height = $('flow_box').offsetHeight;
	if (height != normalH){
		$('flow_box').style.height = normalH+"px";
		$('styleTip_Box').style.height = normalA+"px";
		flow_box = $('flow_box').scrollHeight;
		height = $('flow_box').offsetHeight;
	}
	if (normalS == flow_box) $('flow_box').style.height = normalH+"px";
	else {
		$('flow_box').style.height = (normalH + (flow_box-normalS))+"px";
		$('styleTip_Box').style.height = $('styleTip_Box').offsetHeight + (flow_box-normalS)+"px";
	}
}

epoqGlobal = {
	epoqLoop: 0
}

function callEpoq(pWarenKorb)
{
	/*
	 * wenn die epoq_productIds noch nicht initialisiert sind, wurde das
	 * Host-skript von epoq auch noch nicht geladen, das hier nachholen
	 */
	if( typeof(epoq_productIds) == 'undefined' || typeof(epoq_productIds) == '' ) {
	    var script = document.createElement("script");
	    script.type = 'text/javascript';
	    script.src = 'http://rs.epoq.de/web-api/epoq.js';
	    document.appendChild(script);
	}

    if(typeof(epoq_processCart) != 'undefined') {
            epoq_tenantId       =    tenantId;
        	epoq_sessionId      =   sessionId;
        	epoq_localhistory	=	true;
        	var webtrekkProduct = '';
        	var webtrekkCost	= '';
        	var webtrekkQuantity= '';

        	for (i=0; i < pWarenKorb.length; i++) {
        		item = pWarenKorb[i];
        		epoq_quantities[i]	= item.amount;
        		epoq_unitPrices[i]	= item.price;
        		epoq_sizes[i]		= item.size;
        		epoq_productIds[i]	= item.artData.th_style_id + '-' +   item.artData.colorcode;
        		epoq_variantOf[i]	= item.artData.th_style_id;
        		webtrekkProduct 	= webtrekkProduct + item.artData.th_style_id + ';';
        		webtrekkCost		= webtrekkCost + item.price + ';';
        		webtrekkQuantity	= webtrekkQuantity + item.amount + ';';
        	};
        	//// Webtrekk: In den Warenkorb gelegte Produkte
        	webtrekk.product			= webtrekkProduct.substr( 0, webtrekkProduct.length-1) ; // products
        	webtrekk.productQuantity 	= webtrekkQuantity.substr( 0, webtrekkQuantity.length-1) ; // optional: quantity
        	webtrekk.productCost 		= webtrekkCost.substr( 0, webtrekkCost.length-1) ; // optional: costs
        	webtrekk.productStatus 		= "add"; // optional: status: (add|conf|view)

        	//webtrekk.orderValue = "{$orderTotalBrutto}"; // total order value
        	//webtrekk.orderId = "{$webID}"; // optional: order id
        	//webtrekk.productCategory = new Array();
        	//webtrekk.productCategory[1] = ""; // optional: category
        	//webtrekk.productCategory[2] = ""; // optional: brand

           epoq_updateCart();

    } else {
        window.setTimeout('callEpoq()',1000);
    }

}

function size_guide(action){
	switch (action) {
		case "men_long":
			/* Shoes */
			$('size_guide_shoes_table').hide();
			$('men_casual_shoes').hide();
			/* Normal */
			$('size_guide_table').hide();
			$('men_casual_normal').hide();

			break;
		case "men_shoes":
			/* Shoes an */
			$('size_guide_shoes_table').show();
			$('men_casual_shoes').show();
			/* Normal */
			$('size_guide_table').hide();
			$('men_casual_normal').hide();

			break;
		default:
			/* Normal an */
			$('size_guide_table').show();
			$('men_casual_normal').show();
			/* Shoes */
			$('size_guide_shoes_table').hide();
			$('men_casual_shoes').hide();
	}
}


function size_guide_women(action)
{
	switch (action)
	{
		case "women_shoes":
			/* Shoes */
			$('women_casual_shoes').show();
			$('size_guide_shoes_table').show();

			/* Size*/
			$('size_guide_table').hide();
			$('women_casual_size').hide();

			/* Jewelry */
			$('size_guide_jewelry_table').hide();
			$('women_casual_jewelry').hide();
		break;
		case "women_jewelry":
			/* Jewelry */
			$('size_guide_jewelry_table').show();
			$('women_casual_jewelry').show();

			/* Size*/
			$('size_guide_table').hide();
			$('women_casual_size').hide();

			/* Shoes */
			$('women_casual_shoes').hide();
			$('size_guide_shoes_table').hide();

		break;
		default:
			/* Size*/
			$('size_guide_table').show();
			$('women_casual_size').show();

			/* Shoes */
			$('women_casual_shoes').hide();
			$('size_guide_shoes_table').hide();

			/* Jewelry */
			$('size_guide_jewelry_table').hide();
			$('women_casual_jewelry').hide();
	}
}

function show_overlays(target, quick){

	$$('.info_overlays').each(Element.hide);

	if(quick){
		$(target).show();
	}
	else
	{
	  Effect.Appear(target, {
	    duration: .2,
	    afterFinish: function() {

    	  if (target == 'sizeguide' && $('size_guide_men_slider_content') != null) {

      	  var slsg = new Control.Slider('sliderSlideSg', 'sliderTrackSg', {
        	  axis:'vertical',
        	  	sliderValue: 0,
        	  	maximum: 50,
        	  	range: $R(0, ($('size_guide_men_slider_content').getHeight() - 300)),
        		disabled: false,
        		onChange: function(value) {
					$('size_guide_men_slider_content').style.top = '-' + value + 'px';
        		},
        		onSlide: function(value) {
					$('size_guide_men_slider_content').style.top = '-' + parseInt(value) + 'px';
        		}
        	});

        	Event.observe('sliderUpSg','click',function(event){
      			slsg.setValue(slsg.value - 50);
      		});

      		Event.observe('sliderDownSg','click',function(event){
      			slsg.setValue(slsg.value + 50);
      		});
        }
      }
	  });
	}
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

