
// ++++++++++ the actual toggle of the orders ++++++++++++++
if (window.location.href.indexOf('/Suche/')) {
	$(window).bind('hashchange', function(){
		if (!ajax_suche_hat_das_event_ausgelöst) {
			//reload page suche
			var h='';
			if (window.location.hash=='') {
				h=window.location.search.substr(1);
			} else {
				h=window.location.hash.substr(1);
			}
			ajaxReloadSuche( h, h, true );
			//console.log(h);
		} else {
			ajax_suche_hat_das_event_ausgelöst=false;
		}
	});
}

/*
Function: $get
	This function provides access to the "get" variable scope + the element anchor

Version: 1.3

Arguments:
	key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor)
	url - url; optional; the url to check for "key" in, location.href is default

Example:
	>$get("foo","http://example.com/?foo=bar"); //returns "bar"
	>$get("foo"); //returns the value of the "foo" variable if it's present in the current url(location.href)
	>$get("#","http://example.com/#moo"); //returns "moo"
	>$get("#"); //returns the element anchor if any, but from the current url (location.href)
	>$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:'bar',bar:'foo'}
	>$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:'bar',bar:'foo',hash:'moo'}
	>$get(); //returns same as above, but from the current url (location.href)
	>$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href)

Returns:
	Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
	Returns "" if the variable is not present in the given query string

Credits:
		Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url]
		Function by Jens Anders Bakke, webfreak.no
*/

function $get(key,url){
	if(arguments.length < 2) url =location.href;
	if(arguments.length > 0 && key != ""){
		if(key == "#"){
			var regex = new RegExp("[#]([^$]*)");
		} else if(key == "?"){
			var regex = new RegExp("[?]([^#$]*)");
		} else {
			var regex = new RegExp("[?&]"+key+"=([^&#]*)");
		}
		var results = regex.exec(url);
		return (results == null )? "" : results[1];
	} else {
		url = url.split("?");
		var results = {};
			if(url.length > 1){
				url = url[1].split("#");
				if(url.length > 1) results["hash"] = url[1];
				url[0].split("&").each(function(item,index){
					item = item.split("=");
					results[item[0]] = item[1];
				});
			}
		return results;
	}
}


function createCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 ;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function checkboxFormat ( checkbox ) {
	if (checkbox.attr('checked')) {
		checkbox.parent('li').addClass('checked kfselected');
		checkbox.parent('li').removeClass('unchecked');
	} else {
		checkbox.parent('li').addClass('unchecked');
		checkbox.parent('li').removeClass('checked');
		checkbox.parent('li').removeClass('kfselected');
	}
	checkbox.css('left', '-9999px');
}

function checkboxGroupFromat ( checkboxGroup ) {

	sel_all=true;
	id_head='';

	checkboxGroup.find("input[type=checkbox]").each( function() {
		var id=$(this).attr('id');
		var t=id.split('_');
		id_head='#'+id.substr(0,id.length-t[t.length-1].length)+'all';

		if ($(id_head).attr('checked')=='checked' && id.substr(id.length-4,4)!='_all') { //
			$(this).removeAttr('checked');
			//console.log('re'+$(this).attr('id'));
		}

		if ($(this).attr('checked')=='checked')  sel_all=false;
		checkboxFormat ( $(this) );

		//console.log($(this).attr('id')+' '+$(this).attr('checked'));

	});

	if (sel_all){
		$(id_head).attr('checked','checked');
		checkboxFormat ( $(id_head) );
	}

}

function inititiliseSuche () {


	$('#kat_filter').addClass('jsison');

	var inp = $('#kat_filter');

	$('#kat_filter .jsGroup').each(function (){
		checkboxGroupFromat( $(this) );
	})

	//#for (i=0; i<inp.length;i++) {
//#
		//#inp.find("input[type=checkbox]").each(
			//#function() {
				//#checkboxFormat ( $(this) );
			//#}
		//#);
	//#}

	var namenssuche=inp.find("#textInputProduktsuche");
	namenssuche.addClass('text_ProduktsucheJS');

	namenssuche.keyup(function(e){
		if(e.which == 13){
			ajaxReloadSuche({'ProduktSuche':$('#textInputProduktsuche').val()});
			e.preventDefault();
		}
		if (namenssuche.val().length>=2) {
			ajaxReloadSuche({'ProduktSuche':$('#textInputProduktsuche').val()});
		}
		//console.log($('#textInputProduktsuche').val());
	});


	inp.find("#bottonInputProduktsuche").click( function(e){
		ajaxReloadSuche({'ProduktSuche':$('#textInputProduktsuche').val()});
		e.preventDefault();
	});



	inp.find("#bottonInputProduktsuche").each(
		function() {
			$(this).addClass('button_ProduktsucheJS');
		}
	);



	$('#kat_filter li').delegate("li", "click", function(e) {

		$('#formSendSeite').val('');

		var box=$(this).find('input[type=checkbox]');
		if (box != undefined ) {
			var id=box.attr('id');
			//console.log(id);
			if (id == undefined) return false;
			if (id.substr(id.length-4,4)!='_all') {
				var id=box.attr('id');
				var t=id.split('_');
				var id_head='#'+id.substr(0,id.length-t[t.length-1].length)+'all';
				$(id_head).removeAttr('checked');
				//console.log('h '+id_head);
			}


			if (box.attr('checked')=='checked') box.removeAttr('checked');  else box.attr('checked','checked');
			checkboxGroupFromat ( box.parents('.jsGroup') );
			//console.log(box.parents('.jsGroup'));

			ajaxReloadSuche ();
		}
		//console.log(box.attr('checked'));
		e.preventDefault();

	});



	$("#kat_filter #slider_stil").slider({
		range: true,
		min: 0,
		max: 10,
		step: 0.1,
		values: [ 0, 10 ],
		change: function(e,ui) {
			$('#kf09_stil_min').val(Math.round(ui.values[ 0 ]));
			$('#kf09_stil_max').val(Math.round(ui.values[ 1 ]));
			//console.log($('#kf09_glas_min').val() + ' ' + $('#kf09_glas_max').val());
			ajaxReloadSuche ();
		}
	});

	$("#kat_filter #slider_preis").slider({
		range: true,
		min: 30,
		max: 130,
		step: 1,
		values: [ 30, 130 ],
		change: function(e,ui) {
			$('#kf09_preis_min').val(Math.round(ui.values[ 0 ]));
			$('#kf09_preis_max').val(Math.round(ui.values[ 1 ]));
			//console.log($('#kf09_glas_min').val() + ' ' + $('#kf09_glas_max').val());
			ajaxReloadSuche ();
		}
	});

	$("#kat_filter #slider_size").slider({
		range: true,
		min: 0,
		max: 10,
		step: 0.1,
		values: [ 0, 10 ],
		change: function(e,ui) {
			$('#kf09_size_min').val(Math.round(ui.values[ 0 ]));
			$('#kf09_size_max').val(Math.round(ui.values[ 1 ]));
			//console.log($('#kf09_glas_min').val() + ' ' + $('#kf09_glas_max').val());
			ajaxReloadSuche ();
		}
	});

	$("#kat_filter #slider_form").slider({
		range: true,
		min: 0,
		max: 10,
		step: 0.1,
		values: [ 0, 10 ],
		change: function(e,ui) {
			$('#kf09_glas_min').val(Math.round(ui.values[ 0 ]));
			$('#kf09_glas_max').val(Math.round(ui.values[ 1 ]));
			//console.log($('#kf09_glas_min').val() + ' ' + $('#kf09_glas_max').val());
			ajaxReloadSuche ();
		}
	});



}


function ajaxReloadSuche (customdata,alternativlink,reloadIfHashChanged) {

	//$('#topPanel').html('test');

	// da von produktdetailseite nicht per ajax zur suche gewechselt werden kann (anderes css layout)
	if ($('#productDetailPage').length) {
		//console.log('sollte gehn');
		var form=$('#kat_filter');
		form.submit();
		return "";
	}


	if(customdata==undefined) {
		var send={'formJs':'jup'};
		$('#kat_filter').find('input').each(function (intIndex ) {
			if ($( this ).attr('type')=='checkbox')
				send[$( this ).attr('name')]=($( this ).attr('checked')) ? 'on' : '';
			else
				send[$( this ).attr('name')]=$( this ).val();
		});
		send['formSendWithJS']='jup';
	} else {
		send=customdata;
		//send['formSendWithJS']='jup';
		//send['formJs']='jup';
	}


	$.ajax({
		  type: "GET",
		  async: true,
		  url: '/index_reload_search.php',
		  data: send,
		  success: function(data){

			//console.log(data);
			$('#topPanel').replaceWith( data );
			//$( elementId ).show();
			//registerDetailListeners();

			//console.log($('#getVariable').val());
			if ($('#getVariable').val()!=undefined && $('#getVariable').val().length>0)
				window.location.href="#"+$('#getVariable').val();

			inititiliseListenerSeitenzahlen();

			if (reloadIfHashChanged!=true) {
				ajax_suche_hat_das_event_ausgelöst=true;
			}

		  },
		  error: function( data ){
				// alert ("fehler!!! \n\n"+data.responseText);
				if (alternativlink==undefined) {
					//alterLink='';
					//$.each(send, function (key,value){
					//	alterLink +=key+'='+value+'&';
					//});
					//console.log(alterLink);
					//$('#kat_filter').append('<input type="hidden" name="dontLoad" value="myvalue" />');
					$('#kat_filter').submit();
					//$('#productSearch').html( '<div class="ajaxFehler" style="padding:40px 20px 40px 20px;font-size:15px;">Bitte laden Sie die Seite neu zb. indem Sie F5 auf Ihrer Tastatur drücken. Falls das Problem weiter auftritt, würden wir uns über eine kurze Nachricht von Ihnen freuen, um es beheben zu können.</div>' );
				} else {
					window.location.href=alternativlink;
				}
		  }
	});


}

//#$(document).ajaxError(function(e, xhr, opts, err){
	//#var status = (xhr || {}).status;
	//#xhr = null;
	//#setTimeout(function(){
		//#throw(e.type +' | '+ status +' | '+ opts.url);
	//#}, 0);
//#});

function googleTrackingCode() {

	//console.log('googleTrackingcode');
	_gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-938579-1']);
	_gaq.push(['_trackPageview']);

	setTimeout(function(){
		_gaq.push(['_trackEvent', 'NoBounce', 'Over 10 seconds']);
	},10000);

}





function inititliseRollupWarenkorb() {

	wkHasFokus=false;
	wkIsVisible=false;
	var c=readCookie('bk_miniWk_hider_already_used');

	if (c!="jup") {
		$('.hideIfNoJs_miniWk').removeClass('hideIfNoJs_miniWk').addClass('showthis');
		wkIsVisible=true;
		setTimeout(
			function(){
				if (!wkHasFokus && wkIsVisible)
					$('#wkZumEinklappen').hide("slide", { direction: "up" },1000);
					wkHasFokus=false;
					wkIsVisible=false;
			},
		2000);
		createCookie('bk_miniWk_hider_already_used','jup',1,'/',document.domain );
	} else {
		$('.hideIfNoJs_miniWk').removeClass('hideIfNoJs_miniWk').css('display','none').addClass('showthis');
	}


	$('#miniBasket-10').bind('mouseenter mouseleave', function(e){
		//console.log(wkHasFokus);
		if (e.type=='mouseenter') {
			if (!wkIsVisible && !wkHasFokus) {
				$('#wkZumEinklappen').show("slide", { direction: "up" },1000);
			}
			wkIsVisible=true;
			wkHasFokus=true;
		}
		if (e.type=='mouseleave') {
			if (wkIsVisible) {
				$('#wkZumEinklappen').hide("slide", { direction: "up" },1000);
			}
			wkIsVisible=false;
			wkHasFokus=false;
		}
	});

}

function inititiliseListenerSeitenzahlen() {

	$('#productSearch .pagination a').each( function(){
		$(this).click(function(e){
				//console.log('click '+$get('seite',elem.get('href'))+'  _  '+elem.get('href'));
				var link=$(this).attr('href');
				var seite=$get('seite',link);
				$('#formSendSeite').val(seite);
				//console.log($get('seite',$(this).attr('href')));
				if ($get('ProduktSuche',link)!='')
					ajaxReloadSuche ('ProduktSuche='+$get('ProduktSuche',link)+'&seite='+seite,$(this).attr('href'));
				else
					ajaxReloadSuche (undefined,$(this).attr('href'));
				e.preventDefault();
			}
		);
	});

}

function onReloadChangeHashToGet() {

	var hash=(window.location.hash.length>1) ? window.location.hash.substring(1) : "" ;
	if (hash!="")
		if (window.location.pathname.substring(0,7)=="/Suche/")
			window.location = "/Suche/?"+hash;

}


function tooltip (){
	/* CONFIG */
	xOffsetLeft = 30;
	xOffsetRight = 50;
	tipTitle='';
	timer=null;

	// ie6 & 7 stellen die positionen nicht correct dar, deshalb hab ich den tooltip nochmal modifiziert, aber das cashed die bilder nicht..
	// deshalb 2 verschiedene.. für moderne browser gehts quasi schneller
	if (ie6 || ie7) {
		$("#mainColumn").delegate("a.jsImagePopup", "mouseover mouseout", function(e){

			if (e.type=='mouseover'){
				// Standarttooltip deaktivieren
				tipTitle = $(this).attr('title'); $(this).attr('title','');


				// ob links oder rechts
				var leftOrRight='';
				if ($(window).width()/2 > $(this).offset().left+$(this).width()/2)
					leftOrRight='left: '+($(this).offset().left+$(this).width()+xOffsetLeft)+'px;';
				else
					leftOrRight='right: '+($(window).width()-$(this).offset().left+xOffsetRight)+'px;';

				$('body').append('<div class="tooltipImage" style=" '+leftOrRight+';top:'+$(this).offset().top+'px; position: absolute;z-index: 9999;display:none;  ">'+ $(this).attr('rel') +'</div>');

				$('body').find('.tooltipImage').fadeIn('fast');
			}

			if (e.type=='mouseout') {
				// standarttooltip wieder einstellen
				$(this).attr('title',tipTitle);
				$('body').find('.tooltipImage').fadeOut('fast').remove();
			}
		});
	} else {

		$("#mainColumn").delegate("a.jsImagePopup", "mouseover mouseout", function(e){

			if (e.type=='mouseover'){
				// Standarttooltip deaktivieren
				tipTitle = $(this).attr('title'); $(this).attr('title','');

				if (!$(this).parent().find('.tooltip').length) {

					// ob links oder rechts
					var leftOrRight='';
					if ($(window).width()/2 > $(this).offset().left+$(this).width()/2)
						leftOrRight='left: '+($(this).width()+xOffsetLeft)+'px;';
					else
						leftOrRight='right: '+($(this).width()+xOffsetRight)+'px;';

					$(this).parent().append('<div class="tooltip" style=" '+leftOrRight+'; position: absolute;top: 0;z-index: 9999;display:none;  ">'+ $(this).attr('rel') +'</div>');
				}

				// für die 500millisec delay gebraucht
				var delaytimerElement= $(this).parent().find('.tooltip');
                timer = setTimeout(function() {
                    delaytimerElement.fadeIn('fast');
                    clearTimeout(timer);
					timer = null;
                }, 600)


			}

			if (e.type=='mouseout') {

				// für die 500millsec delay
				if(timer) {
					clearTimeout(timer);
					timer = null;
                }

				// standarttooltip wieder einstellen
				$(this).attr('title',tipTitle);
				$(this).parent().find('.tooltip').fadeOut('fast');
			}
		});

	}


};


function fancybox(){


	$('a.thumbLink').fancybox({
		'hideOnContentClick': true,
		'hideOnOverlayClick': true,
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600,
		'speedOut'		:	200,
		'overlayOpacity':	0,
		'overlayShow'	:	true
	});

	$('a.lightbox').fancybox({
		'hideOnContentClick': false,
		'hideOnOverlayClick': true,
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600,
		'speedOut'		:	200,
		'width'			:	1000,
		'height'		:	'90%',
		'autoDimensions':	false,
		'overlayOpacity':	0,
		'overlayShow'	:	true
	});

	$('a.popupLink').fancybox({
		'hideOnContentClick': false,
		'hideOnOverlayClick': true,
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600,
		'speedOut'		:	200,
		'width'			:	650,
		'height'		:	'90%',
		'autoDimensions':	false,
		'overlayOpacity':	0,
		'overlayShow'	:	true
	});

}

function inititiliseDetailseiteSonnebrillenTabumschalter () {

	/***2010 product detail tab opening***/
	$('#openTabOne-10').click(function(e) {
		$('#prodTabs-10').removeClass('tabTwoisopen-10');
		$('#prodTabs-10').addClass('tabOneisopen-10');
		e.preventDefault();
	});
	$('#openTabTwo-10').click(function(e) {
		$('#prodTabs-10').removeClass('tabOneisopen-10');
		$('#prodTabs-10').addClass('tabTwoisopen-10');
		e.preventDefault();
	});

}


// was beim laden des dokumentes da sein soll...
$(document).ready(function(){


	$('.hideIfJs_09').addClass( 'hidethis');
	$('.hideIfNoJs_09').addClass( 'showthis');

	if ($('#kat_filter').length) inititiliseSuche();

	if ($('#wkZumEinklappen').length) inititliseRollupWarenkorb();

	if ($('.pagination').length) inititiliseListenerSeitenzahlen();

	if (!is_localhost) googleTrackingCode();

	if ($('#productSearch').length) tooltip();

	fancybox();

	if($('#openTabOne-10').length) inititiliseDetailseiteSonnebrillenTabumschalter ();

	$("#bestproductCarusel").carousel( { dispItems: 2, autoSlide: true, autoSlideInterval: 5000, loop: true } );


});





//find the bad browsers
if((navigator.appVersion.indexOf("MSIE 6")>-1)) ie6=true; else ie6=false;
if((navigator.appVersion.indexOf("MSIE 7")>-1)) ie7=true; else ie7=false;


// laden sobald möglich... before domeready, sonst lädt die ganze seite komplett, nur um neu geladen zu werden..
onReloadChangeHashToGet();

is_localhost=((location+'').indexOf('localhost')>=0) ? true : false;
//console.log(is_localhost);


