trim = function(txt) {
	for(var str='',tmp=[],y=-1,x=0;x<txt.length;x++) {
		if(txt.charAt(x)!=" ") {
			(tmp[((y==-1)?0:y)]==undefined)?tmp[((y==-1)?0:y)]=txt.charAt(x):tmp[((y==-1)?0:y)]+=txt.charAt(x);
		}
		else {
			(tmp[((y==-1)?0:y)]!=undefined)?y++:"";
		}
	}
	for(var x=0;x<tmp.length;x++) {
		(x<tmp.length-1)?str+=tmp[x]+" ":str+=tmp[x];
	}

	return str;
};

//Sesson-Cookie OHNE DATUM eingeben (null), NICHT -1
//setCookie("CookieName" , "Wert", null);
function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "")
	document.cookie = curCookie
}

function getCookie(cookieName) {
	var lf = "\n";
	var cookieString = document.cookie;
	var cookieSet = cookieString.split(';');
	var SetSize = cookieSet.length;
	var cookiePieces;
	var returnValue = "";
	var x = 0;
	for (x = 0; ((x < SetSize) && (returnValue == "")); x++) {
		cookiePieces = cookieSet[x].split('=');
		if (cookiePieces[0].substring (0,1) == ' ') {
			cookiePieces[0] = cookiePieces[0].substring (1, cookiePieces[0].length);
		}
		if (cookiePieces[0] == cookieName) {
			returnValue = cookiePieces[1];
		}
	 }
	return unescape(returnValue);
}

function hasCookie(name) {
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0,name.length))) return false;
	if (start == -1) return false;

	return true;
}

function getCookieValue(name) {
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;

	if( !start && (name != document.cookie.substring(0,name.length)) ) return '';
	if( start == -1 ) return '';

	var end = document.cookie.indexOf(";",len);
	if( end == -1 ) end = document.cookie.length;
	return unescape(document.cookie.substring(len,end));
}


function isSSLOff() {
	return (document.location.protocol.indexOf("https")==-1);
}


function determineBasketCounterCookie() {
	if( hasCookie('BasketCounter') ) {
		counterValue 	= getCookieValue('BasketCounter');

		if(counterValue == null || counterValue == '') {
			counterValue = '0';
		}
		return counterValue;
	}
	else {
		return '0';
	}
}


function clearItem(item, value) {
	if( item.value==value ) {
		item.value = '';
	}
}

function fillItem(item, value) {
	if( item.value=='' ) {
		item.value = value;
	}
}


function determineLoginStatusByCookie() {
	if (hasCookie('LoginCounter')) {
		loginValue = getCookieValue('LoginCounter');

		if (loginValue == null || loginValue == '')
			loginValue = 0;
			return loginValue;
		}
		else {
		return 0;
	}
}

function openBBSInfo() {
	window.open('/webroot/html/product/bbs.html','BCLUB_BBS', 'width=532,height=576,scrollbars=yes');
}

function openBBSDVDInfo() {
	window.open('/webroot/html/product/bbsdvd.html','BCLUB_BBS', 'width=532,height=576,scrollbars=yes');
}

function openBBSPartnerInfo() {
	window.open('/webroot/html/product/bbspartner.html','BCLUB_BBS', 'width=532,height=576,scrollbars=yes');
}

function openvBook(sku,width,height) {
	openWindow(ecsURL+'DEEmpfehlungen-VirtualBook?ProductSKU='+sku+'&redirect=/webroot/download/vbook/'+sku+'/index.html', 'VirtualBook'+sku,width,height,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,noresize');
}

function openFilInfo() {
	window.open('/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEPopup-Var?t=filiale_versandkosten','BCLUB_FIL', 'width=522,height=576');
}

function openWindow(src,name,width,height,features){
	if(features){
		return window.open(src, name, "width="+width+",height="+height+","+features);
	} else {
		return window.open(src, name, "width="+width+",height="+height+",scrollbars=yes");
	}
}

function add2Basket(url) {
	new Ajax.Request(url, 
	{
		evalJS:false,
		onCreate: add2basketcreate,
		onException: add2basketexception,
		onSuccess: showAdd2basketResponse
	});
}

function showAdd2basketResponse(response) {
	var respjson = response.responseJSON;

	if(respjson.from == 'add2basket_silent') {
		$('warenkorb_layer_loading').hide();
		$('warenkorb_layer_content_add2basket_package').hide(); //package
		$('warenkorb_layer_content_add2basket_silent').show(); //normal
	} else if (respjson.from == 'add2basket_treueadd') {
		$('warenkorb_layer_loading').hide();
		$('warenkorb_layer_content_add2basket_treueadd2').hide();
		$('warenkorb_layer_content_add2basket_package').hide(); //package
		$('warenkorb_layer_content_add2basket_treueadd').show();
		$('warenkorb_layer_content_add2basket').show(); //treueadd
	} else if (respjson.from == 'add2basket_treueadd2') {
		$('warenkorb_layer_loading').hide();
		$('warenkorb_layer_content_add2basket_treueadd').hide();
		$('warenkorb_layer_content_add2basket_package').hide(); //package
		$('warenkorb_layer_content_add2basket_treueadd2').show();
		$('warenkorb_layer_content_add2basket').show(); //treueadd2
	} else if (respjson.from == 'add2basket_package') {
	    if (respjson.fromProperty == 'add2basket_priemierenpackage'){
			$('warenkorb_layer_loading').hide();
			$('warenkorb_layer_content_add2basket_treueadd').hide();
			$('warenkorb_layer_content_add2basket_treueadd2').hide();
			$('warenkorb_layer_content_add2basket_package').show(); //package
			$('warenkorb_layer_content_add2basket').show();
		}
		
	}
	
	if (respjson && respjson.status) {
		if (respjson.from != 'add2basket_package'){
			if (respjson.status=='error') {
				$('warenkorb_layer_content_headline').update(respjson.headline);
				$('warenkorb_layer_content_message').update(respjson.message);
			} else {
				$('warenkorb_layer_content_message').update(respjson.message);
			}
		}
	}
	refresh();
	
	Tracking.track({
				pageName:respjson.pageName,
				ch :respjson.channel,
				events  :respjson.events,
				products:respjson.products,
				h1   :respjson.h1
			});
}

function add2basketcreate()
{
	$('warenkorb_layer_content_add2basket').hide();
	$('warenkorb_layer_content_add2basket_silent').hide();
	$('warenkorb_layer_content_add2basket_package').hide(); 
	ModalDialog.show('warenkorb_layer', {height:'217', width:'400', use_fade:'true',use_resize:'true'});
	$('warenkorb_layer_loading').show();
}

function add2basketexception()
{
	$('warenkorb_layer_loading').hide();
	$('warenkorb_layer_content_buttons').hide();
	$('warenkorb_layer_content_add2basket_silent').show();
	$('warenkorb_layer_content_message').update('Ihre Anfrage konnte leider nicht verarbeitet werden. Bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt erneut.');
}

//SiteCatalyst Tracking
	var Tracking = {
		myhash : new Hash(),
		
		'track':function(obj){
	
			if(s && obj) {
				h = $H(obj);
	
				['events'].each(function(name){
					if (!h.get(name)) {
						s[name] = '';
					}
				});
	
				h.each(function(pair) {
					s[pair.key] = pair.value;
				});
	
				s.tl();
			}
			
		},
		
		'setProperty':function(property,value){
			this.myhash.set(property,value);
			
		},
		
		'addEvent':function(event) {
			previousEvents = this.myhash.get('events');
			if (typeof(previousEvents) == 'undefined'
				|| previousEvents == null 
				|| previousEvents.blank()) {
				
				this.myhash.set('events', event);
			} else {
				previousEvents = this.myhash.unset('events');
				this.myhash.set('events', previousEvents + ',' + event);
			}
		},
		
		'update':function(obj){	
			
			this.myhash.each(function(pair) {
				s[pair.key] = pair.value;
			});
		}
	};
	


function add2Merkzettel(url) {
	add2Basket(url);
}


/*** Erweiterte Suche ***/
function checkProSearch() {
	if (productSearch.queryAuthor.value == ''
		&& productSearch.queryTitle.value == ''
		&& productSearch.queryNumber.value == ''
		&& productSearch.queryActor.value == ''
		&& productSearch.queryText.value == '')
	{
		alert("Bitte füllen Sie mindestens eines der Suchfelder aus.")
		return false;
	}

	var queryText, queryActor;

	queryText 	= trim(productSearch.queryText.value);
	queryActor 	= trim(productSearch.queryActor.value);

	if(queryActor != '') {
		if(queryText != '') {
			productSearch.queryText.value = queryText +' '+ queryActor;
		}
		else {
			productSearch.queryText.value = queryActor;
		}
	}

	return true;
}

//---  Download Foto-Bestellsoftware---
function openTeaserClient() {
	browserTitle = escape("Fotoservice");
	path = "http://app.photoprintit.de/hclient/frame_index.jsp?keyacc_id=2280&currency=EUR&LOCALE_LANGUAGE=de&LOCALE_COUNTRY=de&browser_title=" + browserTitle;
	htmlClientWindow = open( path, "OPS_HTML_Client", "width=540,height=436,screenX=0,screenY=0" );
}

function startTrueTalk(servletURL, thema, optional) {
  var arg = "http://"+servletURL+"/";
  arg += "providers/NOVOMIND";
  arg += "/mandates/CLUB";
  arg += "/Main.html?requestType=CLIENT&mandant_name=CLUB";
  arg += "&hot_button_name=" + escape(thema);
  arg += "&provider_name=NOVOMIND";
  if (optional != null) {
    arg += optional;
  }
  var win = "width=325,height=410,";
  win += "toolbar=no,location=no,directories=no,status=no,"
  win += "menubar=no,scrollbars=no,copyhistory=no,resizable=no,";
  win += "left=0,top=40,screenX=0,screenY=40";

  var fensterName = "TrueTalkWindow"+Math.round(Math.random()*1000);

  window.open(arg, fensterName, win);
}


/* Suchfeld im Header */
function volltextFocus() {
	clearItem(document.search.volltext, 'Suchbegriff oder Bestellnummer eingeben');

	document.search.volltext.className = "searchkeywordactive";
}

function volltextBlur() {
	fillItem(document.search.volltext, 'Suchbegriff oder Bestellnummer eingeben');

	if( document.search.volltext.value == 'Suchbegriff oder Bestellnummer eingeben' ) {
		document.search.volltext.className = "searchkeyword";
	}
	else {
		document.search.volltext.className = "searchkeywordactive";
	}
}

function showFilialDetailHome()
{
    var plz = document.forms.filialen.plz.value;
    var ortsname ="";
    if (plz != null && plz != 'undefined') {
	ortsname=Number(plz);
	if(isNaN(ortsname)) {
      		return filialSucheExternWithOrt(plz);
	}
    }

    if (plz != null && plz != 'undefined' && plz.length == 5)
      return filialSucheExternWithValue(plz);
    return false;
}

function showFilialDetailExtern()
{
    var plz = document.forms.filialen.plz.value;
    if (plz != null && plz != 'undefined' && plz.length == 5)
      return filialSucheExternWithValue(plz);

    var ort = "", plz="", value;
    for(i=0;i<document.filialen.filialnr.length;++i)
    if(document.filialen.filialnr.options[i].selected == true)
    value = document.filialen.filialnr.options[i].value;

    if (value != null && value != 'undefined' && value != '')
    {
			var values = value.split(" ");
			ort = values[0];
			plz = values[1];
			if (top.frames['BCLUB_TOP'])
			{
      	top.frames['BCLUB_TOP'].window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?Hauptort="+ort+"&PLZ="+plz;
			}
			else
			{
      	window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?Hauptort="+ort+"&PLZ="+plz;
			}
    }

    return false;
}

function filialSucheExternWithValue(plz)
{
	  if (top.frames['BCLUB_TOP'])
	  {
    	top.frames['BCLUB_TOP'].window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?PLZ="+plz;
    }
    else
    {
    	window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?PLZ="+plz;
    }
    return false;
}

function filialSucheExternWithOrt(plz)
{
	  if (top.frames['BCLUB_TOP'])
	  {
    	top.frames['BCLUB_TOP'].window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?Hauptort="+plz;
    }
    else
    {
    	window.location.href = "/is-bin/INTERSHOP.enfinity/eCS/Store/de/-/EUR/DEService-GetBranchForUndefinedRegion?Hauptort="+plz;
    }
    return false;
}

/*
 * caller: Node, in dem diese Funktion aufgerufen wird (normalerweise this).
 * msg: Anzuzeigende Nachricht
 * x, y: Koordination, wo die Quickinfo angezeigt werden soll (relativ zum caller)
 * width: Breite des Quickinfo-Divs.
 *
 * x, y, width sind optional.
 *
 * Beispiel: derclub/account/login.isml
 */
function show_quickinfo(caller, msg, x, y, width) {
	if (!x) x = "0";
	if (!y) y = "-300";
	if (!width) width = "300";
	qi_node = make_quickinfo(msg, x, y, width);
	// Opera Workaround:
	qi_parent = document.getElementById("quickinfo_parent");
	if (qi_parent) qi_parent.parentNode.removeChild(qi_parent);
	// wegen position:absolute müssen wir sicherstellen, dass
	// das Elternelement des Quickinfos nicht static positioniert ist.
	// Also basteln wir uns einfach selbst eins ohne weitere Eigenschaften.
	qi_parent = document.createElement("div");
	qi_parent.id = "quickinfo_parent";
	qi_parent.appendChild(make_quickinfo(msg, x, y, width));
	caller.appendChild(qi_parent);
}

function make_quickinfo(msg, x, y, width) {
	qi_node = document.createElement("div");
	qi_node.innerHTML = msg;
	qi_node.id = "quickinfo";
	qi_node.style.left = x;
	qi_node.style.top = y;
	qi_node.style.width = width;
	return qi_node;
}

function hide_quickinfo() {
	qi_node = document.getElementById("quickinfo_parent");
	qi_node.style.display = "none";
	// das qi an dieser Stelle aus dem DOM zu kicken verwirrt Opera...
	//if (qi_node) qi_node.parentNode.removeChild(qi_node); else alert("DSD");
}

function OpenHelpMain() {
	OpenHelpPar('hilfe','');
}

function showPWField() {
	if( document.getElementById("pwfield1") ) {
		document.getElementById("pwfield1").style.display = 'none';
	}

	if( document.getElementById("pwfield2") ) {
		document.getElementById("pwfield2").style.display = '';
		
		if(document.LoginFormNavLeft.LoginForm_Password ) {
			document.LoginFormNavLeft.LoginForm_Password.focus();
		}
	}
}

function hidePWField() {
	if(document.LoginFormNavLeft.LoginForm_Password.value == '') {
		document.getElementById("pwfield1").style.display = '';
		document.getElementById("pwfield2").style.display = 'none';
	}
}

function sendChosenPartners(url) {
	
	var partnerCoRegForm = $('partnerCoRegForm');
	var partnerCoRegAgreement = $('partnerCoRegAgreement');
	
	$('partnerCoRegSuccess', 'partnerCoRegFailure', 'partnerCoRegAgreementMissing').invoke('hide');
	if (partnerCoRegAgreement.checked) {
		//check to see if at least one checkbox is selected
		if (partnerCoRegForm.getInputs('checkbox').without(partnerCoRegAgreement).pluck('checked').any()) {
		
			new Ajax.Request(url,
			{
				parameters:Form.serialize($('partnerCoRegForm')	),
				evalJS:false,
				onException: showCoRegFailure,
				onSuccess: showCoRegConfirmation
			});
		}
	} else {
		$('partnerCoRegAgreementMissing').show();
	}
}

function showCoRegConfirmation() {
	$('partnerCoReg').hide();
	$('partnerCoRegSuccess').show();
}

function showCoRegFailure() {
	$('partnerCoReg').hide();	
	$('partnerCoRegFailure').show();
}

function suggest(url) {
	searchForm = $('searchForm');
	searchQuery = searchForm.getInputs('text').first().value;
	
	if (searchQuery.length > 0) {
	  	if (searchQuery.length % 2 == 0) {
			new Ajax.Request(url, 
			{
				parameters: 'volltext=' + searchQuery,
				evalJS:false,
				onException: handleSuggestException,
				onSuccess: suggestSearchQuery
			});
		}
	}
}
	
// JUBILÄUMS GEWINNSPIEL CHECK JS
function checkJubiRaffle() {
	var error = false;
	
	$('answers1').getElementsByClassName('textfield')[0].maxLength = 3;
	$('answers2').getElementsByClassName('textfield')[0].maxLength = 4;
	$('answers3').getElementsByClassName('textfield')[0].maxLength = 2;
	$('answers4').getElementsByClassName('textfield')[0].maxLength = 3;

	if($('error_docking_id') != null) {
		$('answers1').style.top = '723px';
		$('answers2').style.top = '723px';
		$('answers3').style.top = '723px';
		$('answers4').style.top = '723px';
	};
	
	if($('question1').className == 'question colorerror') {
		$('answers1').getElementsByClassName('textfield')[0].style.backgroundColor = 'red';
		error = true;
	}
	if($('question2').className == 'question colorerror') {
		$('answers2').getElementsByClassName('textfield')[0].style.backgroundColor = 'red';	
		error = true;
	}
	if($('question3').className == 'question colorerror') {
		$('answers3').getElementsByClassName('textfield')[0].style.backgroundColor = 'red';
		error = true;
	}
	if($('question4').className == 'question colorerror') {
		$('answers4').getElementsByClassName('textfield')[0].style.backgroundColor = 'red';
		error = true;
	}
	
	if(error) {
		return false;
	} else {
		return true;
	}
}