$(document).ready( function() {

	/* pngfix */
	$('.ifixpng, .rabattImage, .jewelcaseImage, .jewelcaseImage80, .jewelcaseImage130, .icon_basket a img').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); 
});

function getPremiumBundle(cat_name){
	$.ajax({url:"dispatch.do?def=.premiumBundleDisplay&cat_name="+cat_name, cache:false, success:function(data){
		$("#specialLayoutPremiumBundleFirstItem").html(data);
	}});
}

function addToPremiumBundle(ordercode,cat_name){
	$.ajax({url:"addToPremiumBundle.do?oc="+ordercode+"&cat_name="+cat_name, cache:false, success:function(data){
		$("#specialLayoutPremiumBundleFirstItem").html(data);
	}});
}

function removeFromPremiumBundle(ordercode,cat_name){
	$.ajax({url:"removeFromPremiumBundle.do?oc="+ordercode+"&cat_name="+cat_name, cache:false, success:function(data){
		$("#specialLayoutPremiumBundleFirstItem").html(data);
	}});
}

function addToBasketCall(ordercode, artist, title){
	$.ajax({url:"addBasketEntry.do?oc="+ordercode, cache:false, success:function(data){
		updateShoppingBasket(data);
	}});
}

/* basket functions */
function addToBasket(buyCode, artist, title) {
	addToBasketCall(buyCode);

	var titleText="";
	if(title!=null && title.size>0){
		titleText= " - " + title;
	}
	// styling
	$("#notificationBox").html(
			"<h1>Warenkorb</h1><span class=\"closeX\">x</span><div class=\"clear\"><!--e--></div>"+
			"<div class=\"blockContent\"><p>"+
				"Der Artikel <b>" + artist + titleText + "</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() {
	var i;
	var addedNumber = 0;
	for (i = 0; i < document.tracklist.length; i++) {
		if (document.tracklist.elements[i].checked) {
			addToBasketCall(document.tracklist.elements[i].value);
			addedNumber += 1;
		}
	}
	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 updateShoppingBasket(count) {
	$("#basketCount").html(count);
	displayBasketMask();
}

function displayLoginMask() {
	$("#box_cutout_head").attr("class","box_cutout_head_login");
	$("#basketMask").hide();
	$("#loginMask").show();
}

function displayBasketMask() {
	$("#box_cutout_head").attr("class","box_cutout_head_basket");
	$("#loginMask").hide();
	$("#basketMask").show();
}

/* cookie functions */

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;
}
