Number.prototype.formatCurrency = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

/* create instance of myself */
/* ************************* */
var mySC = new shoppingcart();
/* ************************* */

function shoppingcart() {

	// global variables
	var aSteps = new Object();
	var iActiveStep = 0;
	var iMaxAccessStep = 0;
	var iMaxSteps = 5

	// menu- und content-strip ids
	aSteps["menu"] = new Array();
	aSteps["content"] = new Array();	
	/* *********************************************************************** */
	/* ********************** FUNCTIONS ************************************** */
	/* *********************************************************************** */
	/* init function */
	this.init = function(){
		var param = {};
		
		try {
			syncJSSettings('get');
		} catch (err) {
			console.log(err);			
		}
	}

	// synchronisiert status und stepsize mit datenbank
	var syncJSSettings = function(state){
		var param = {};
		param.state = '' + state + '';
		
		if(state == 'set'){
			param.stepnumberaccess = iMaxAccessStep;
		}		
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=syncAjaxInitJSSettings",
			dataType: 'json',
			data: jQuery.param(param),
			type: 'POST',
			async: false,
			success: function(respObj, respStatus, blubb){
				if(respObj.state == 'get' || respObj.state == 'reset'){
					/* nur hier ist es erlaubt und gewollt, das man direkt auf die globale variable zugreift! */
					iMaxAccessStep = respObj.stepnumberaccess;
					iActiveStep = respObj.stepnumberaccess;
				};
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}	
	
	/* dump function */
	this.dump = function(){
		console.log('Variable: aSteps');
		console.log(aSteps);
		console.log('Variable: iActiveStep');
		console.log(iActiveStep);
		console.log('Variable: iMaxAccessStep');
		console.log(iMaxAccessStep);
		console.log('Variable: this');
		console.log(this);
	}
	
	// resettet die Step-Tabs
	this.resetTabBar = function(){
		$(aSteps["menu"]).unbind();
		$(aSteps["menu"]).addClass('greyed');
		$(aSteps["menu"]).removeClass('selected');
	}
	
	// schreibt die html-ids in die arrays
	this.setTabBar = function(menuwrapper,contentwrapper){
		var i = 0;
		var aMenuSteps = $('#'+ menuwrapper + ' > div');
		var aContentSteps = $('#'+ contentwrapper + ' > div');
		
		setIncreaseAccess(iActiveStep);
		setActiveStep(iActiveStep);
		
		if (aMenuSteps.length == aContentSteps.length){
			aSteps["menu"] = aMenuSteps;
			aSteps["content"] = aContentSteps;
		} else {
			throw('The component init does fail. The wrapperconfig is wrong! Arrays have different lengths.');
		}
		
		this.switchToStep(iActiveStep);
	}
	
	// oeffentliche Function fuer das Aufrufen des naechsten Steps
	this.nextStep = function(post){
		this.switchToStep(iActiveStep,post);
		$('html, body').animate({scrollTop:0}, 'fast');
	}
	
	// oeffentliche Function fuer das Aufrufen des vorherigen Steps
	this.prevStep = function(){
		this.switchToStep(iActiveStep-1,false);
		$('html, body').animate({scrollTop:0}, 'fast');
	}
	
	// interne/oeffentliche Function fuer das Aufrufen von bestimmten Steps
	this.switchToStep = function(pStep,post){
		if(pStep > iMaxAccessStep){
			pStep = iMaxAccessStep;
		};
		setActiveStep(pStep);
		
		$(aSteps["menu"]).unbind();
		$(aSteps["menu"]).addClass('greyed');
		$(aSteps["menu"]).removeClass('selected');
		
		$(aSteps["content"]).removeClass('selected');

		for(i=0; i <= iMaxAccessStep;i++){
			var elM = $(aSteps["menu"][i]);
			var elC = $(aSteps["content"][i]);
			
			elM.removeClass('greyed');
			elM.bind('click', {step: i}, function(event){mySC.switchToStep(event.data.step)});
		}
		
		$(aSteps["menu"]).removeClass('selected');
		$(aSteps["content"]).removeClass('selected');
		
		$(aSteps["menu"][pStep]).addClass('selected');
		$(aSteps["content"][pStep]).addClass('selected');

		this.getContentByStep(pStep,post);
	}
	
	// Step: Verteilen | Buchbindung setzen
	this.setCollectionbindings = function(id){
		var param = {};
		param.pkcollectionbindings = id;
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=setAjaxCollectionBindings",
			dataType: 'json',
			type: 'POST',
			data: jQuery.param(param),
			success: function(respObj, respStatus, blubb){
				mySC.setReArrangePrescriptions();
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// Step: Verteilen | Anzahl Buecher setzen
	this.setCollectionCount = function(count){
		var param = {};
		param.collectioncount = count;
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=setAjaxCollectionCount",
			dataType: 'json',
			type: 'POST',
			data: jQuery.param(param),
			success: function(respObj, respStatus, blubb){
				mySC.switchToStep(0,false);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// Step: Verteilen | Menge Buecher setzen
	this.setCollectionAmount = function(collection,amount){
		var param = {};
		param.amount = amount;
		param.collectionnumber = collection;
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=setAjaxCollectionAmount",
			dataType: 'json',
			type: 'POST',
			data: jQuery.param(param),
			success: function(respObj, respStatus, blubb){
				mySC.switchToStep(0,false);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// Step: Verteilen | Automatische Verteilung ausfuehren
	this.setReArrangePrescriptions = function(){
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=setReArrangePrescriptions",
			dataType: 'json',
			type: 'POST',
			async: false,
			success: function(respObj, respStatus, blubb){
				mySC.switchToStep(0,false);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// interne Funktion fuer das Abholen eines Steps
	this.getContentByStep = function(pStep,post){
		var param = {};
		
		if(post != 'undefined' && post == true){
			param.post = true;
			$(':radio:checked, :checkbox:checked, :selected, :text, [type=hidden], :password',aSteps["content"][iActiveStep])
			 .each(function() {
				 param[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
			});
		}
		param.stepid = $(aSteps["content"][pStep]).attr("id");
		
		jQuery.ajax({
				url: "/ajax/shoppingcart/ajaxresponder.cfm?action=getAjaxContentByStep",
				dataType: 'json',
				data: jQuery.param(param),
				type: 'POST',
				success: function(respObj, respStatus, blubb){
					if(respObj.error != 'undefined' && respObj.error == false && post == true){
						setActiveStep(iActiveStep+1);
						setIncreaseAccess(iActiveStep);
					}
					if(respObj.content != 'undefined' && respObj.content.length > 0){
						$(aSteps["content"][pStep]).html(respObj.content);
					};
				},
				error: function(respObj, respStatus, blubb){
					console.log(respStatus);
				}
		})
	}
	
	// oeffentliche Function fuer das Hinzufuegen einer Vorschrift zum Warenkorb
	this.addPrescriptions = function(id){
		var data = {};
		
		if(id == undefined){
			data.prescription = "";
			$.each($('#prescriptionlist :checked'), function(index, value) {
				data.prescription += '' + value.value.toString() + ',';
			});
		} else {
			// add by pkprescriptions
			data.prescription = id;
		}
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=addAjaxPrescriptions",
			cache: false,
			data: data,
			dataType: 'json',
			type: 'POST',
			async: false,
			success: function(respObj, respStatus, blubb){
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
		this.refreshSCTeaser();
		syncJSSettings('reset');
	}
	
	// oeffentliche Funktion fuer das Resetten eines Warenkorbs
	this.resetShoppingcart = function(){
		var param = "";

		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=resetAjaxShoppingcart",
			cache: false,
			data: jQuery.param(param),
			dataType: 'json',
			type: 'POST',
			success: function(respObj, respStatus, blubb){
				mySC.switchToStep(0,false);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
		syncJSSettings('reset');
		this.refreshSCTeaser();
	}
	
	// Step: Verteilen | Loeschen einer Vorschrift aus Warenkorb
	this.delPrescriptions = function(id){
		var param = {};
		param.prescriptionid = id;
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=delAjaxPrescriptions",
			dataType: 'json',
			data: jQuery.param(param),
			type: 'POST',
			success: function(respObj, respStatus, blubb){
				$('#row_' + id).remove();
				mySC.refreshSCTeaser();
				mySC.switchToStep(0, false);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// Step: Verteilen | Aenderungsmailer setzen
	this.toggleChangemailer = function(id){
		var param = {};
		param.prescriptionid = id;
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=toggleAjaxChangemailer",
			dataType: 'json',
			data: jQuery.param(param),
			type: 'POST',
			success: function(respObj, respStatus, blubb){
				$('#mailer_' + id).html(respObj.value);
				$('#mailer_' + id).attr('title',respObj.title);
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// oeffentliche Funktion fuer die Verabeitung des Loginteasers
	this.doLoginTeaser = function(){
		var param = {};
		
		$('#loginboxteaser :text, #loginboxteaser :password')
		 .each(function() {
			 param[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});
		
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=doAjaxLoginTeaser",
			dataType: 'json',
			type: 'POST',
			data: param,
			processData: true,
			success: function(respObj, respStatus, blubb){
				// sollte ein redirect zurueckgegeben werden, so wird dieser anstelle alles anderem ausgefuehrt
				if(typeof(respObj.redirect) != 'undefined' && respObj.redirect.length > 0){
					location.href = respObj.redirect;
				}
				
				if(respObj.content != 'undefined' && respObj.content.length > 0){
					$('#loginboxteaser').html(respObj.content);
					if(iActiveStep == 2){
						mySC.switchToStep(2,false);
					}
				}
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			}
		})
	}
	
	// oeffentliche Function fuer das Erneuern des Warenkorbteasers
	this.refreshSCTeaser = function(){
		jQuery.ajax({
			url: "/ajax/shoppingcart/ajaxresponder.cfm?action=refreshAjaxSCTeaser",
			cache: false,
			dataType: 'json',
			type: 'POST',
			success: function(respObj, respStatus, blubb){
				if(respObj.nprescriptioncount == 0){
					$('#warenkorb').html('<tr><td>keine Produkte im Warenkorb</td></tr>')
				}else{
					$('#warenkorb').html('<tr>'
					+'<td class="warenkorb_eintrag">Anzahl Vorschriften</td>'
					+'<td class="warenkorb_preis" id="scteaser_prescriptioncount">'+respObj.NPRESCRIPTIONCOUNT+'</td>'
					+'</tr>'
					+'<tr>'
					+'<td class="warenkorb_eintrag">Anzahl Seiten</td>'
					+'<td class="warenkorb_preis" id="scteaser_prescriptionpages">'+respObj.NPRESCRIPTIONPAGES+'</td>'
					+'</tr>'
					+'<tr>'
					+'<td class="warenkorb_eintrag" colspan="2"><b>Warenkorb</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/index.cfm?pid='+respObj.PIDSHOPPINGCART+'">Aufrufen</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);" title="Warenkorb leeren" onclick="mySC.resetShoppingcart();">Leeren</a></td>'
					+'</tr>');
				}
				$('#warenkorbteaser #scteaser_prescriptionprice').html(respObj.NPRESCRIPTIONVALUE.formatCurrency(2, ',', '.') + ' &euro;');
			},
			error: function(respObj, respStatus, blubb){
				console.log(respStatus);
			},
			beforeSend: this.toggleLoading('#warenkorbteaser div .inside',true),
			complete: this.toggleLoading('#warenkorbteaser div .inside',false)
		})
	}
	
	// Loading-Kreis bei Warenkorbteaser
	this.toggleLoading = function(selector,state){
		
		if(state == true){
			$(selector).children().addClass('hidden');
			$(selector).prepend('<div class="loading">&nbsp;</div>');
		} else {
			$(selector).children().removeClass('hidden');
			$('.loading',selector).remove();			
		}
	}
	
	// Step: Verteilen | Sortierung von Vorschriften
	this.sortIt = function(element,direction){
		
		var elTableRows = $('.vorschriftenverteilung tr[id^="row_"]');
		var param = {};
		var idxNextToLast = elTableRows.index(elTableRows.filter('tr:last'))-1;
		
		/* settings fuer das verschiebende elemente */
		var elRow = $(element).parent().parent();
		var elCollection = $(':checked', elRow).attr("value");
		var elId = $(':checked', elRow).attr("name").split("_")[1];
		var elIdx = elTableRows.index(elRow);
		
		
		/* settings fuer das zu verschiebende element ermitteln */
		if(direction == 'up'){
			var elExRow = elTableRows.filter(":eq(" + (elIdx-1) + ")");
			var elExCollection = $(':checked', elExRow).attr("value");
			var elExId = $(':checked', elExRow).attr("name").split("_")[1];
			var elExIdx = elTableRows.index(elExRow);
			
		} else if (direction == 'down'){
			var elExRow = elTableRows.filter(":eq(" + (elIdx+1) + ")");
			var elExCollection = $(':checked', elExRow).attr("value");
			var elExId = $(':checked', elExRow).attr("name").split("_")[1];
			var elExIdx = elTableRows.index(elExRow);
		}
		
		if(elCollection == elExCollection){
			param.prescription = elId;
			param.prescriptionexchange = elExId;
			param.collectionnumber = elCollection;
			
			jQuery.ajax({
				url: "/ajax/shoppingcart/ajaxresponder.cfm?action=sortAjaxPrescriptionList",
				cache: false,
				data: jQuery.param(param),
				dataType: 'json',
				type: 'POST',
				success: function(respObj, respStatus, blubb){
					if(respObj.sortorderlist != 'undefined'){
						$('#c' + elCollection + '_sortorder:hidden').attr("value",respObj.sortorderlist);
					}
				},
				error: function(respObj, respStatus, blubb){
					console.log(respStatus);
				}
			})
			
			if(direction == 'up'){
				elExRow
				.before(elRow)
				.toggleClass('bluecolumn');
				
				elRow
				.toggleClass('bluecolumn');				
			}else if (direction == 'down'){
				elExRow
				.after(elRow)
				.toggleClass('bluecolumn');
				
				elRow
				.toggleClass('bluecolumn');				
			}
		}
		
		/* pfeile nach oben und unten bei erstem und letztem element ein/ausblenden */
		$('.vorschriftenverteilung tr[id^="row_"]:first td:first a.up').hide();
		$('.vorschriftenverteilung tr[id^="row_"]:eq(1) td:first a.up').show();
		
		$('.vorschriftenverteilung tr[id^="row_"]:eq('+ idxNextToLast +') td:first a.down').show();
		$('.vorschriftenverteilung tr[id^="row_"]:last td:first a.down').hide();

		/* aktuell verschobene vorschriftenzeile highlighten */
		elTableRows.removeClass('highlight_current');
		elRow.addClass('highlight_current');
	}
	
	// Step: Verteilen | Zuordnung Vorschrift zu Buch setzen
	this.changeCollectionRelation = function(){
		var param = {};
		var aList = Array(1);

		$('.vorschriftenverteilung input[name*="_sortorder"]:hidden').each(function(index){
		    aList = Array(1);
		    $('.vorschriftenverteilung :radio:checked[value="' + (index+1) +'"]').each(function(){
		        aList.push(this.name.split("_")[1]);
		    });
		    $('#c'+(index+1)+'_sortorder').attr("value",aList.join(","));
		})
		
		/* falls dieses hiddenfeld auf true steht, wird zwar das formular gepostet, aber es kommt die gleiche seite nochmals */
		$('#noredirect').attr("value","true");
		mySC.switchToStep(0,true);
	}
	
	// Step: Buchtitel festlegen | Aktive Page setzen
	this.toggleCollections = function(activecollection,collectioncount){
		var i;
		
		if(activecollection <= 0){activecollection = 1;};
		if(activecollection >= collectioncount){activecollection = collectioncount;};
		
		for(i=0; i <= collectioncount;i++){
			$('#collectioncontent' + i + '').removeClass('selected');
		}
		$('#collectioncontent' + activecollection + '').addClass('selected');
	}
	
	// interne Funktion fuer das Erhoehen des Zugriffssteps
	var setIncreaseAccess = function(pStep){
		if(pStep > iMaxAccessStep){
			iMaxAccessStep = pStep;
			syncJSSettings('set');
		}
		/* sollte ueber die maximale anzahl an steps hinausgezaehlt werden, resetten */
		if(pStep > iMaxSteps){
			syncJSSettings('reset');
		}
	}

	// interne Funktion fuer das Setzen des aktuellen, aktiven Steps
	var setActiveStep = function(pStep){
		iActiveStep = pStep;
	}
}


/* sonstige Funktionen, die auf der Homepage benötigt werden */
/* ********************************************************* */
function checkAllSubEntries(selfhtmlid){
	var el = $('#' + selfhtmlid + '');

	el.parent()
		.parent()
		.children('ul.vorschriftenliste')
		.children('li')
		.children('input:checkbox')
		.attr('checked', el.attr('checked'));
}

function checkParentEntry(parenthtmlid,selfhtmlid){
	
	var nChkBoxes = $('#' + selfhtmlid + '')
					.parent()
					.parent()
					.children('li')
					.children('input:checkbox').length;
	
	var nChkedBoxes = $('#' + selfhtmlid + '')
						.parent()
						.parent()
						.children('li')
						.children('input:checked').length;
	
	if(nChkedBoxes == nChkBoxes){
		$('#' + parenthtmlid + '').attr('checked',true);
	} else {
		$('#' + parenthtmlid + '').attr('checked',false);
	}
}

function checkAllEntries(checkstate){
	$('#prescriptionlist').find('input:checkbox').attr('checked',checkstate);	
}

function togglePayments(paymentid){
	switch(paymentid){
		case "1":
			$('#creditcard').hide();
			$('#elv').show();
			break;
		case "10":
			$('#creditcard').show();
			$('#elv').hide();
			break;
		default:
			$('#creditcard').hide();
			$('#elv').hide();
			break;
	}
}

function testWordLen(element,len){
	var words = element.value.split(" ");
	for (i = 0; i<words.length;i++){
		if (words[i].length>len){
			$('#errortext').html('Maximale Zeilenl&auml;nge von ' + len + ' Zeichen bei einem Wort erreicht.<br/>Bitte brechen Sie an geeigneter Stelle mit einem Leerzeichen um.')
			return true;
			break;
		} else {
			$('#errortext').html('');
		}
	}
	return true;
}

function updatePreview(activecollection,element){
	var itemid = "";
	var aSplitResult = [];
	aSplitResult = element.id.split("_");
	
	switch (aSplitResult[1]) {
		case "titel":
			itemid = "vorschautitel";
			break;
		case "untertitel":
			itemid = "vorschauuntertitel";
			break;
		case "datum":
			itemid = "vorschaudatum";
			break;
		case "firma":
			itemid = "vorschaufirma";
			break;
		case "name":
			itemid = "vorschauname";
			break;
		default:
			itemid = 'none';
			break;
	}

	if(aSplitResult[1] != 'datum' || element.value == ''){
		$('#collectioncontent' + activecollection +  ' .bildvorschau #' + itemid + '').html(element.value);	
	}else{
		$('#collectioncontent' + activecollection +  ' .bildvorschau #' + itemid + '').html('Stand: ' + element.value);
	}
}

function toggleChangemailer(id,that){
	var param = {};
	param.prescriptionid = id;
	param.userid = getCookie('IDLOGGEDIN');

	jQuery.ajax({
		url: "/ajax/shoppingcart/ajaxresponder.cfm?action=toggleAjaxChangemailerOutbox",
		dataType: 'json',
		data: jQuery.param(param),
		type: 'POST',
		success: function(respObj, respStatus, blubb){
			$(that).html(respObj.value);
			$(that).attr('title',respObj.title);
		},
		error: function(respObj, respStatus, blubb){
			console.log(respStatus);
		}
	})
}

function deleteUserPrescriptions(id){
	var param = {};
	param.prescriptionid = id;
	param.userid = getCookie('IDLOGGEDIN');
	
	jQuery.ajax({
		url: "/ajax/shoppingcart/ajaxresponder.cfm?action=deleteAjaxUserPrescriptions",
		dataType: 'json',
		data: jQuery.param(param),
		type: 'POST',
		success: function(respObj, respStatus, blubb){
			$('#prescription' + id).parent().remove();
			$('.kontolist').removeClass('bluecolumn').filter(':even').addClass('bluecolumn');
			$('.konto_selected').click();
		},
		error: function(respObj, respStatus, blubb){
			console.log(respStatus);
		}
	})
}

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
}

/*
 * isdefined v1.0
 * Check if a javascript variable has been defined.
 * Author : Jehiah Czebotar
 * Website: http://www.jehiah.com
 * Usage  : alert(isdefined('myvar'));
*/
function isDefined(variable)
{
	return (typeof(window[variable]) == "undefined")?  false: true;
}
