$(document).ready( function() {

	/* pngfix */
	$('.ifixpng, .rabattImage, .jewelcaseImage, .jewelcaseImage80, .jewelcaseImage130').ifixpng();

	/* header menu bar */
	$('#header #navigation a:not(:.selected)').mouseover( function() {
		$(this).addClass("selected");
	}).mouseout( function() {
		$(this).removeClass("selected");
	});

	$(".orderBox").click(function(){
		$(this).find(".orderDetailsTable").toggle();
		if ($(this).find(".orderDetailsTable").is(":visible")) {
			$(this).find(".myOrdersButtonPlus").addClass("Minus");
		}else{
			$(this).find(".myOrdersButtonPlus").removeClass("Minus");
		}
	});
	
	$('.blockOverlay').live("click",unblock); 
	$('.simpleContentBoxBlockUi span.closeX').live("click",unblock); 
});

/* basket functions */
function addToBasket(buyCode, artist, title) {
	if (canCookie()) {
		addToShoppingBasketInternal(buyCode);
		updateShoppingBasket();

		// styling
		$("#notificationBox").html(
				"<h1>Warenkorb</h1><span class=\"closeX\">x</span><div class=\"clear\"><!--e--></div>"+
				"<div class=\"blockContent\"><p>"+
					"Der Artikel <b>" + artist + " - " + title + "</b> wurde in den Warenkorb gelegt."+
				"</p></div>");
		
		var button1 = createContinueShoppingButton();
		$("#notificationBox .blockContent").append(button1);
		
		var button2 = createBasketButton();
		$("#notificationBox .blockContent").append(button2);
		
		$("#notificationBox .blockContent").append("<div class=\"clear\"><!--e--></div>");
		
		blockUI($('#notificationBox'));
	}
}

function addTracksToShoppingBasket() {
	if (canCookie()) {
		var i;
		var addedNumber = 0;
		for (i = 0; i < document.tracklist.length; i++) {
			if (document.tracklist.elements[i].checked) {
				addToShoppingBasketInternal(document.tracklist.elements[i].value);
				addedNumber += 1;
			}
		}
		updateShoppingBasket();
		if (addedNumber > 0) {
			// styling
			$("#notificationBox").html(
					"<h1>Warenkorb</h1><span class=\"closeX\">x</span><div class=\"clear\"><!--e--></div>"+
					"<div class=\"blockContent\"><p>"+
						"<b>" + addedNumber + "</b> Artikel wurden in den Warenkorb gelegt." +
					"</p></div>");
			
			var button1 = createContinueShoppingButton();
			$("#notificationBox .blockContent").append(button1);
			
			var button2 = createBasketButton();
			$("#notificationBox .blockContent").append(button2);
			
			$("#notificationBox .blockContent").append("<div class=\"clear\"><!--e--></div>");

			blockUI($('#notificationBox'));
		}
	}
}

function blockUI(message){

	$.blockUI( {
		message : message,
		css : {
		  color: '#ff0000',
      	  cursor: 'default',
      	  background: 'transparent',
      	  border: 'none'
		},
		overlayCSS: { backgroundColor: '#ffffff',
      	  cursor: 'default',
      	  opacity: .8 }
	});
	
}

function showInformation(message) {
	$(document).ready( function() {
		$("#notificationBox").html(
				"<h1>Information</h1><span class=\"closeX\">x</span><div class=\"clear\"><!--e--></div>"+
				"<div class=\"blockContent\"><p>"+
					message +
				"</p></div>");
		
		var button = createContinueButton();
		$("#notificationBox .blockContent").append(button);
		
		$("#notificationBox .blockContent").append("<div class=\"clear\"><!--e--></div>");
	
		blockUI($('#notificationBox'));
	});
}

function unblock() {
	$.unblockUI({ 
        onUnblock: function(){
			$("#tafForm").hide();
		} 
    });
}

function addToShoppingBasketInternal(buyCode) {
	var shoppingBasket = readCookie("shoppingBasket");
	if (shoppingBasket && shoppingBasket.indexOf(buyCode) != -1) {
		return;
	}
	if (shoppingBasket) {
		shoppingBasket = shoppingBasket + "," + buyCode;
	} else {
		shoppingBasket = buyCode;
	}

	var now = new Date();
	var minutes = now.getMinutes();

	// also needs to be set in ShoppingBasketUtils
	minutes += 7200; // ( 24 Hours * 60 Minutes ) * 5 Days = 7200 Minutes
	now.setMinutes(minutes);

	writeCookie("shoppingBasket", shoppingBasket, now, "/", null, null);
}

function updateShoppingBasket() {
	var i = getShoppingBasket();
	if (i == 0) {
		document.getElementById("nbrObContents").innerHTML = "Kein";
	} else {
		document.getElementById("nbrObContents").innerHTML = "" + i;
	}
	displayBasketMask();
}

function getShoppingBasket() {
	var shoppingBasket = readCookie("shoppingBasket");
	var i = 0;
	if (shoppingBasket) {
		i++;
		var idx = shoppingBasket.indexOf(",");
		while (idx != -1) {
			shoppingBasket = shoppingBasket.substring(idx + 1);
			idx = shoppingBasket.indexOf(",");
			i++;
		}
	}
	return i;
}

function writeShoppingBasket() {
	var i = getShoppingBasket();
	if (i == 0) {
		document.write('<span id="nbrObContents">Kein</span>');
	} else {
		document.write('<span id="nbrObContents">' + i + '</span>');
	}
}

//Diese Funktion korrigiert den Datums-Bug von
// Netscape/Mac und liefert den korrekten GMTString:
function fixedGMTString(datum) {
	var damals = new Date(1970, 0, 1, 12);
	if (damals.toGMTString().indexOf("02") > 0) {
		datum.setTime(datum.getTime() - 1000 * 60 * 60 * 24);
	}
	return datum.toGMTString();
}

function displayLoginMask() {
	document.getElementById("box_cutout_head").className = "box_cutout_head_login";
	document.getElementById("basketMask").style.display = "none";
	document.getElementById("loginMask").style.display = "block";
}

function displayBasketMask() {
	document.getElementById("box_cutout_head").className = "box_cutout_head_basket";
	document.getElementById("loginMask").style.display = "none";
	document.getElementById("basketMask").style.display = "block";
}

/* cookie functions */

function canCookie() {
	writeCookie("test", "musicbox", null, "/", null, null);
	if (readCookie("test") == "musicbox") {
		removeCookie("test", "/", null)
		cookie_set = true;
		return true;
	} else {
		showInformation('Diese Funktion ist nicht m&ouml;glich!<br><br>Bitte aktivieren Sie Cookies!');
		return false;
	}
}

function readCookie(name) {
	var theCookie = document.cookie;

	// Anfangsposition des Name=Wert-Paars suchen
	var posName = theCookie.indexOf("; " + name + "=");
	if (posName == -1) {
		// vielleicht war's der erste Name in der Liste?
		if (theCookie.indexOf(name + "=") == 0)
			posName = 0;
		// nein? dann abbrechen mit R?ckgabewert null
		else
			return null;
	}

	// Anfangs- und Endposition des Kr?melwerts suchen
	var wertAnfang = theCookie.indexOf("=", posName) + 1;
	var wertEnde = theCookie.indexOf(";", posName + 1);
	if (wertEnde == -1)
		wertEnde = theCookie.length;

	// Kr?melwert auslesen und zur?ckgeben
	var wert = theCookie.substring(wertAnfang, wertEnde);
	return unescape(wert);
}

function writeCookie(name, wert, verfall, path, dom, secure) {
	neuerKeks = name + "=" + escape(wert);
	if (verfall)
		neuerKeks += "; expires=" + fixedGMTString(verfall);
	if (path)
		neuerKeks += "; path=" + path;
	if (dom)
		neuerKeks += "; domain=" + dom;
	if (secure)
		neuerKeks += "; secure";
	document.cookie = neuerKeks;
}

function removeCookie(name, path, dom) {
	document.cookie = name + "=" + ((path) ? ";path=" + path : "")
			+ ((dom) ? ";domain=" + dom : "")
			+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function createBasketButton() {
	return $("#basketButton").clone().show();
}
function createContinueShoppingButton() {
	return $("#continueShoppingButton").clone().show();
}
function createContinueButton() {
	return $("#continueButton").clone().show();
}

function redirectToURL(url) {
	if (url != "") {
		window.location = url;
	}
}


/*Trimming*/

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


/*Tell a Friend*/

function showRecommendForm() {
	$("#tafForm").show();

	blockUI($('#tafForm'));
}
function hideRecommendForm() {	
	unblock();
}

function sendIt(artist) {
	recipient = document.getElementById("recipientName").value;
	name = document.getElementById("senderName").value;
	text = document.getElementById("text").value;

	url = 'tellAFriend.do?recipientMail=' + recipient + '&senderName=' + name
			+ '&text=' + text + '&uniqueName=' + artist + '&url=' + escape(window.location);
	encodeURI(url);
	sendDataTAF(url);
}

function responseUpdate(result) {

	if (result == 'OK') {
		hideRecommendForm()
		showInformation('E Mail wurde erfolgreich verschickt');
	}
	if (result == '-1000') {
		hideRecommendForm()
		showInformation('Fehlerhafter EMailHost');
	}
	if (result == '-1001') {
		hideRecommendForm()
		showInformation('Fehlerhafte EMailAdresse');
	}
	if (result == '-1002') {
		hideRecommendForm()
		showInformation('Empf&auml;nger und Name m&uuml;ssen ausgef&uuml;llt werden!');
	}
	if (result == '-1010') {
		hideRecommendForm()
		showInformation('Sie m&uuml;ssen angemeldet sein, um eine Empfehlung zu versenden!');
	}

}

function PreisCheck(preis) {
	var CPreis = preis;
	var XPreis = preis.replace(/,/g, ".");
	CPreis = XPreis.replace(/\./g, "");
	p1 = XPreis.length;
	p2 = XPreis.search(/\./g);
	p3 = parseInt(p1) - parseInt(p2);
	if (p3 == 3) {
		if (p2 < '0')
			CPreis = CPreis + '00';
	}
	if (p3 == '0')
		CPreis = CPreis + '00';
	if (p3 == '1')
		CPreis = CPreis + '00';
	if (p3 == '2')
		CPreis = CPreis + '0';
	return (CPreis);
}

function getKomma(zahl) {
	var zahl0 = new String(zahl);

	if (zahl0 == 0) {
		return '0,00';
	}
	teil1 = zahl0.length - 2;
	zahl1 = zahl0.substr(0, teil1);
	if (zahl1 == "") {
		zahl1 = 0;
	}
	zahl2 = zahl0.substr(teil1, 2);
	zahlk = zahl1 + ',' + zahl2;
	return (zahlk);
}

/*Call and Pay*/
var cap1send = false;
var cap2send = false;

function sendCAPRequest() {
	if(cap1send==false){
		cap1send=true;
		document.getElementById('buyButton').style.display = "none"; 
		document.getElementById('waitButton').style.display = "block"; 
		url = 'order.do?isCallAndPay=true';
		encodeURI(url);
		sendDataCAP(url);
	}
}

function sendCAPRequest2() {
	if(cap2send==false){
		cap2send=true;
		url = 'order.do?checkCallAndPay=true';
		encodeURI(url);
		sendDataCAP2(url);
	}
}

function CAPUpdate(response) {
	if(response=="error"){
		showInformation('Leider trat ein Fehler auf');	
	}else{
		document.getElementById('waitButton').style.display = "none"; 
		document.getElementById('capBox').style.display = "block"; 
		document.getElementById('capNumber').innerHTML = response;
	}
}

function CAPUpdate2(response) {
	cap2send=false;
	if (response!="OK") {
		if (response == "18") {
			showInformation("Bitte t&auml;tigen Sie zun&auml;chst den Festnetzanruf.");	
		} else if (response == "19") {
			showInformation("Bitte f&uuml;hren Sie zun&auml;chst den Bezahlvorgang vollst&auml;ngig durch.");	
		} else {
			showInformation('Leider trat ein Fehler auf');	
		}
	} else {
		location.href = "order.do";
	}
}

function open_urlwindow( url, width ) {
	windowHeight = 640;
	if (width>0){
		windowWidth = width;
	}else{
		windowWidth = 450;
	}
	var maxHeight = screen.availHeight - 50;
	
	if (document.all && !window.opera) {
		windowWidth = windowWidth + 18; // add space for ie scrollbar
	}
	
	if ((windowHeight > maxHeight) && !document.all) {
		windowHeight = maxHeight;
		windowWidth = windowWidth + 16; // add space for scrollbar
	}
	
	urlWindow=window.open( url, '',
		'toolbar=0,location=0,directories=0,status=1,menubar=0,' +
		'scrollbars=1,resizable=yes,' +
		'width=' + windowWidth + 
		',height=' + windowHeight);
	return true;
}

function open_urlwindow( url, width, height ) {
	if (width>0){
		windowWidth = width;
	}else{
		windowWidth = 450;
	}
	if (height>0){
		windowHeight = height;
	}else{
		windowHeight = 640;
	}
	
	var maxHeight = screen.availHeight - 50;
	
	if (document.all && !window.opera) {
		windowWidth = windowWidth + 18; // add space for ie scrollbar
	}
	
	if ((windowHeight > maxHeight) && !document.all) {
		windowHeight = maxHeight;
		windowWidth = windowWidth + 16; // add space for scrollbar
	}
	
	urlWindow=window.open( url, '',
		'toolbar=0,location=0,directories=0,status=1,menubar=0,' +
		'scrollbars=1,resizable=yes,' +
		'width=' + windowWidth + 
		',height=' + windowHeight);
	return true;
}

/* ajax part */
function getXMLRequester( )
{
  var xmlHttp = null;
  
  // Mozilla, Opera, Safari sowie Internet Explorer 7
  if (typeof XMLHttpRequest != 'undefined') {
      xmlHttp = new XMLHttpRequest();
  }
  if (!xmlHttp) {
      // Internet Explorer 6 und �lter
      try {
          xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
          try {
              xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {
              xmlHttp  = null;
          }
      }
  }
  return xmlHttp;
}

function sendData(data, file) {
  	theData = data;
  	xmlHttp = getXMLRequester();
    xmlHttp.open('GET', file, true);
    xmlHttp.setRequestHeader("Pragma", "no-cache");
	xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
	xmlHttp.setRequestHeader("If-Modified-Since", document.lastModified);
    xmlHttp.onreadystatechange = handleGetResponse;
    xmlHttp.send(null);
    
  return false;
}

function sendDataWithoutResponse(file) {

  	xmlHttp = getXMLRequester();
    xmlHttp.open('GET', file, true);
    xmlHttp.setRequestHeader("Pragma", "no-cache");
	xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
	xmlHttp.setRequestHeader("If-Modified-Since", document.lastModified);
    xmlHttp.send(null);
    
  return false;
}

function handleGetResponse() {
  // Checke, ob der Zugriff erfolgreich war
  if (xmlHttp.readyState == 4) {
    var response = xmlHttp.responseText;
    return true;
  } else {
    // Ignore
  }
  return false;
}

// Tell A Friend

function sendDataTAF(file) {
	
  	xmlHttp = getXMLRequester();
    xmlHttp.open('GET', file, true);
    xmlHttp.setRequestHeader("Pragma", "no-cache");
	xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
	xmlHttp.setRequestHeader("If-Modified-Since", document.lastModified);
    xmlHttp.onreadystatechange = handleGetResponseTAF;
    xmlHttp.send(null);
    
  return false;
}

function handleGetResponseTAF() {
  // Checke, ob der Zugriff erfolgreich war
  if (xmlHttp.readyState == 4) {
    var response = xmlHttp.responseText;
    responseUpdate(response);
    return true;
  } else {
    // Ignore
  }
  responseUpdate('Fehler');
  return false;
}


//Call and Pay

function sendDataCAP(file) {
	
	xmlHttp = getXMLRequester();
	xmlHttp.open('GET', file, true);
	xmlHttp.setRequestHeader("Pragma", "no-cache");
	xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
	xmlHttp.setRequestHeader("If-Modified-Since", document.lastModified);
	xmlHttp.onreadystatechange = handleGetResponseCAP;
	xmlHttp.send(null);
	return false;
}

function sendDataCAP2(file) {
	
	xmlHttp = getXMLRequester();
	xmlHttp.open('GET', file, true);
	xmlHttp.setRequestHeader("Pragma", "no-cache");
	xmlHttp.setRequestHeader("Cache-Control", "must-revalidate");
	xmlHttp.setRequestHeader("If-Modified-Since", document.lastModified);
	xmlHttp.onreadystatechange = handleGetResponseCAP2;
	xmlHttp.send(null);
	return false;
}

function handleGetResponseCAP() {
//Checke, ob der Zugriff erfolgreich war
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var response = xmlHttp.responseText;
			CAPUpdate(response);
			return true; //response;
		}else{
			// Ignore
		}
	} else {
	 // Ignore
	}
	return false;
}

function handleGetResponseCAP2() {
//Checke, ob der Zugriff erfolgreich war
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var response = xmlHttp.responseText;
			CAPUpdate2(response);
			return true; //response;
		}else{
			// Ignore
		}
	} else {
	 // Ignore
	}
	return false;
}