//=======================================================================================
// add datepicker to date fields

function addJQDatePickers () {
//	alert("addDatePickers");
	
	jQuery.each($(".date"), function(index, value) {
		alert("value " + value);
		//$("#" + value.id).datepicker({showOn: 'button', buttonImage: pathprefix + '/images/calendar.png', buttonImageOnly: true});
		$("#" + value.id).datepicker($.datepicker.regional['us']);
	 
//		   console.log("index", index, "value", value);
	});
}

//=======================================================================================
// utility method to get the 'cutter-url'

function getCutterURL (theURL, theCutID) {
	var anURL = null;
	if (theURL.indexOf("?") == -1) {
		anURL = theURL + "?client_request_ajaxcutid=" + theCutID;
		
	}
	else {
		anURL = theURL + "&client_request_ajaxcutid=" + theCutID;
		
	}
	return anURL;
}

//=======================================================================================
// utility to close a dialog

function __closeDialog(identity) {
	var $dialog = $("#" + (identity || "dialog")); 
	$dialog.dialog("close");
	$dialog.dialog("destroy");
	$dialog.html("");
}

//=======================================================================================
//method used to open a modal form dialog
var dialogStandardHeight = 400;

function openModalDialog (theDialogLink) {
	try{
		$("#dialog").dialog("destroy");		
		var myURL = getCutterURL(theDialogLink, 'content');
		$("#dialog").dialog("open");
//		alert(myURL);
		$("#dialog").load(myURL, {}, __internal_modaldialogcallback);
	}
	catch (error) {
		alert("Fehler: " + error);
	}
}

function createModalDialog(url, options) {
	options = options || {};
	var identity = options.identity || "dialog";
	var $dialog = $("#" + identity);
	if (!$dialog.length) {
		$dialog = $('<div id="' + identity + '" />').appendTo("body");
	} 
	$dialog.dialog("destroy");
	$dialog.dialog("open");
	$dialog.attr("title", options.title || "");
	$dialog.load(getCutterURL(url, "content"), {}, function() {
		__internal_modaldialogcallback(options.width, options.height, identity, options.beforeClose);
		options.open && options.open();
	});
	return $dialog;
}

function openModalDialogWithTitle (theDialogLink, title, width, height) {
	try{
		$("#dialog").dialog("destroy");	
		var myURL = getCutterURL(theDialogLink, 'content');
		$("#dialog").dialog("open");
		dialogStandardHeight = 500;
		$("#dialog").attr("title", title);
		$("#dialog").load(myURL, {}, function() {
			__internal_modaldialogcallback(width, height);
		});
	
	}
	catch (error) {
		alert("Fehler: " + error);
	}
}


function __internal_modaldialogcallback (width, height, identity, beforeClose) {
	identity = identity || "dialog";
	try {
		replaceTextAreasByWYSIWYGEditorInID(identity);
	} catch (ignore) {}
	//addDatePickers();
	var button_name = 'Schliessen';
	if (typeof jqueryCloseButton != "undefined") {
		button_name = jqueryCloseButton;
	}
	var dialog_buttons = {};
	dialog_buttons[button_name] = function() { 
		__closeDialog(identity);
	};
	width = width || 600;
	try {
		$("#" + identity).dialog(
			{
				bgiframe: true,
				resizable: true,
				minHeight: 250, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
				height: height || dialogStandardHeight,
				width: width,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: dialog_buttons,
				"beforeClose": beforeClose || function() {}
			}
		);
		$('#' + identity).dialog('option', 'dialogClass', 'modalDialog');
	}
	catch (error) {
		alert("callback-error: " + error.number + ", " + error.description);
	}
}

//=======================================================================================
//method used to open a modal form dialog

function openProgressPopup (theDialogLink) {
	try{
		$("#dialog").dialog("destroy");		
		var myURL = getCutterURL(theDialogLink, 'content');
		$("#dialog").dialog("open");
//		alert(myURL);
		$("#dialog").load(myURL, {}, __internal_modaldialogcallbackProgressPopup);
	}
	catch (error) {
		alert("Fehler: " + error);
	}
}


function __internal_modaldialogcallbackProgressPopup (responseText, textStatus, XMLHttpRequest) {
//	alert(responseText);
	replaceTextAreasByWYSIWYGEditorInID('dialog');
	addDatePickers();
	try {
		$("#dialog").dialog(
			{
				bgiframe: true,
				resizable: true,
				minHeight: 250, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
				height: 300,
				width: 600,
				modal: true,
				closable: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				}
			}
		);
	}
	catch (error) {
//		alert("callback-error: " + error.number + ", " + error.description);
	}
}


//=======================================================================================
// method used to open a modal form dialog

function openEditDialog (thePart2Replace, theLink, theDialogLink) {
	try{
		$("#dialog").dialog("destroy");
		$("#callbackURL").attr("val", theLink);
		$("#callbackTarget").attr("val", thePart2Replace);
		var myURL = getCutterURL(theDialogLink, 'content');
		$("#dialog").dialog("open");
//		alert(myURL);
		$("#dialog").load(myURL, {}, __internal_callback_2);
//		__internal_callback_2(null, null, null);
	}
	catch (error) {
//		alert("Fehler, letzter Schritt: " + step + ", error=" + error);
	}
}

function __internal_callback_2 (responseText, textStatus, XMLHttpRequest) {
//	alert(responseText);
	replaceTextAreasByWYSIWYGEditorInID('dialog');
	addDatePickers();
	try {
		$("#dialog").dialog(
			{
				bgiframe: true,
				resizable: true,
				minHeight: 400, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
				height: 600,
				width: 800,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				}
			}
		);
	}
	catch (error) {
//		alert("callback-error: " + error.number + ", " + error.description);
	}
}

//=======================================================================================
// method used to open a docustore menu

function openMenuDialog (event, theHeight, title, theDialogLink) {
	try{
		size = title.length;
		if(size > 23) {
			title = title.substring(0, 15)+"..."+title.substring(size-4, size);
		}
		$("#docuMenu").dialog("destroy");		
		var myURL = getCutterURL(theDialogLink, 'content');
		$("#docuMenu").dialog("open");
		$("#docuMenu").attr("title", title);		
		$("#docuMenu").attr("height", theHeight);	
		$("#docuMenu").attr("position", new Array(new Number(event.clientX-160), new Number(event.clientY-40)));
		$("#docuMenu").load(myURL, {}, __internal_menu);
	  $("#docuMenu").attr("position", new Array(new Number(event.clientX-160), new Number(event.clientY-40)));
		//alert(event.clientX);
	}
	catch (error) {
		alert("Fehler: " + error);
	}
}

function __internal_menu (responseText, textStatus, XMLHttpRequest) {
	//alert(responseText);	
	replaceTextAreasByWYSIWYGEditorInID('docuMenu');
	addDatePickers();
	arr = $("#docuMenu").attr("position").toString().split(",");	
	try {
		$("#docuMenu").dialog(
			{
				position: [new Number(arr[0]), new Number(arr[1])],
				backgroundColor: '#ffffff',					
				padding:0,
				margin:0,				
				bgiframe: true,				
				resizable: false,
				minHeight: 100, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
				height: $("#docuMenu").attr("height"),
				width: 230,				
				modal: false				
			}
		);
	}
	catch (error) {
//		alert("callback-error: " + error.number + ", " + error.description);
	}
}

// =======================================================================================
// cancel a modal form dialog

function cancelFormDialog() {
	__closeDialog();
}

//=======================================================================================
//submit a modal form dialog and refresh part of the underlaying page

function submitFormDialog(formID) {
	//writeBackFCK2textarea(formID);
	var dataString = $("#" + formID).serialize();
//	alert(dataString);
	$.ajax({
		type: "POST",
		url: pathprefix + "/boxalino/client/common/error.html?client_request_ajaxcutid=error",  
		data: dataString,
		success: function(thehtml) {
//			alert(thehtml);
//todo: auswerten des resultates
			$("#infoarea").html(thehtml);			
			var callbackURL = $("#callbackURL").attr("val");			
			var callbackTarget = $("#callbackTarget").attr("val");			
//			alert("callback url = " + callbackURL);
//			alert("callback target = " + callbackTarget);
			if (callbackTarget && callbackURL) {
				ajaxReplace(callbackTarget, callbackURL);
			}
			
			__closeDialog();
		}
	});  										
}

function submitFormDialog2(formID) {
	writeBackFCK2textarea(formID);
	var dataString = $("#" + formID).serialize();
//	alert(dataString);
	$.ajax({
		type: "POST",
		url: pathprefix + "/boxalino/client/common/error.html?client_request_ajaxcutid=error",  
		data: dataString,
		success: function(thehtml) {
			$("#infoarea").html(thehtml);
			if (!thehtml || thehtml.indexOf("errorMarker") < 0) {				
				var callbackURL = $("#callbackURL").attr("val");			
				var callbackTarget = $("#callbackTarget").attr("val");			
	//			alert("callback url = " + callbackURL);
	//			alert("callback target = " + callbackTarget);
				if (callbackTarget && callbackURL) {
					ajaxReplace(callbackTarget, callbackURL);
				}
				
				__closeDialog();
			}
		}
	});  										
}

//urlToCall: (pathprefix + url), this page will create for example an item an set the values

function submitFormDialogAndCallURL(formID, urlToCall) {
	writeBackFCK2textarea(formID);
	var dataString = $("#" + formID).serialize();
	//alert(dataString);
		
	$.ajax({
		type: "POST",
		url: urlToCall + "?client_request_ajaxcutid=error",  
		data: dataString,
		success: function(thehtml) {	
//todo: auswerten des resultates
			$("#infoarea").html(thehtml);	
			var callbackURL = $("#callbackURL").attr("val");
			var callbackTarget = $("#callbackTarget").attr("val");
		// alert("callback url = " + callbackURL);
	 // alert("callback target = " + callbackTarget);
			ajaxReplace(callbackTarget, callbackURL);
			__closeDialog();		
		}
	});  											
}


//=======================================================================================
//submit form without default action

function submitFormExceptDefaultAction (formID, targetID, theURL) {
//	var hiddenField = $("input[name='defaultAction']");
	var hiddenField = document.getElementById(formID + "_defaultAction");
	var origDA = "";
	if (hiddenField != null) {
		origDA = hiddenField.value;
		hiddenField.name="client_request_ajaxcutid";
		hiddenField.value="error";
	}
	writeBackFCK2textarea(formID);
	var dataString = $("#" + formID).serialize();	
	if (hiddenField != null) {
		hiddenField.name = "defaultAction";
		hiddenField.value = origDA;
	}
//	alert(dataString);
	$.ajax({
		type: "POST",
		url: pathprefix + "/boxalino/client/common/error.html",  
		data: dataString,
		success: function(thehtml) {
//			alert(thehtml);
//todo: auswerten des resultates
//			$("#infoarea").html(thehtml);
//			alert("callback url = " + callbackURL);
//			alert("callback target = " + callbackTarget);
//			alert(targetID + "-->" + theURL);
			ajaxReplace(targetID, theURL);
		}
	});  										
}

//=======================================================================================
//submit form without default action

function execAndUpdate (theFormID, theTargetID, theParams) {
//	var hiddenField = $("input[name='defaultAction']");
	var hiddenField = document.getElementById(theFormID + "_defaultAction");
	var origDA = "";
	if (hiddenField != null) {
		origDA = hiddenField.value;
		hiddenField.name="client_request_ajaxcutid";
		hiddenField.value="error";
	}
	writeBackFCK2textarea(theFormID);
	var dataString = $("#" + theFormID).serialize();
	if (hiddenField != null) {
		hiddenField.name = "defaultAction";
		hiddenField.value = origDA;
	}
//	dataString = encodeURIComponent(dataString);
//	alert(dataString);
	$.ajax({
		type: "POST",
		url: pathprefix + "/boxalino/client/common/error.html",  
		data: dataString,
		success: function(thehtml) {
//			alert(thehtml);
//todo: auswerten des resultates
//			$("#infoarea").html(thehtml);
//			alert("callback url = " + callbackURL);
//			alert("callback target = " + callbackTarget);
//			alert(targetID + "-->" + theURL);
			var refresh = $("#" + theTargetID).attr("refresh");
//			alert(refresh);
			refresh = refresh + "&" + theParams;
//			alert(refresh);
			ajaxReplace(theTargetID, refresh);
		}
	});
	return false;
}

//=======================================================================================
//submit form without default action

function confirmExecAndUpdate (theConfirmationDialogURL, theFormID, theTargetID, theParams) {
	$("#dialog").attr("the-form-id", theFormID);
	$("#dialog").attr("the-target-id", theTargetID);
	$("#dialog").attr("the-params", theParams);

	confirmActionWithFunction (theConfirmationDialogURL, _confirmExecAndUpdate);
}

function _confirmExecAndUpdate () {
	var theFormID = $("#dialog").attr("the-form-id");
	var theTargetID = $("#dialog").attr("the-target-id");
	var theParams = $("#dialog").attr("the-params");
//	var hiddenField = $("input[name='defaultAction']");
	var hiddenField = document.getElementById(theFormID + "_defaultAction");
	var origDA = "";
	if (hiddenField != null) {
		origDA = hiddenField.value;
		hiddenField.name="client_request_ajaxcutid";
		hiddenField.value="error";
	}
	writeBackFCK2textarea(theFormID);
	var dataString = $("#" + theFormID).serialize();
	if (hiddenField != null) {
		hiddenField.name = "defaultAction";
		hiddenField.value = origDA;
	}
//	alert(dataString);
	$.ajax({
		type: "POST",
		url: pathprefix + "/boxalino/client/common/error.html",  
		data: dataString,
		success: function(thehtml) {
//			alert(thehtml);
//todo: auswerten des resultates
//			$("#infoarea").html(thehtml);
//			alert("callback url = " + callbackURL);
//			alert("callback target = " + callbackTarget);
//			alert(targetID + "-->" + theURL);
			var refresh = $("#" + theTargetID).attr("refresh");
			refresh = refresh + "&" + theParams;
//			alert(refresh);
			ajaxReplace(theTargetID, refresh);
		}
	});
	return false;
}

//=======================================================================================
// process a modal form dialog and refresh part of the underlaying page

function executeHREFDialog(params) {
	var callbackURL = encodeURI($("#callbackURL").attr("val"));
	var callbackTarget = $("#callbackTarget").attr("val");
	var theurl = null;
	if (callbackURL.indexOf("?") == -1) {
		theurl = callbackURL + "?" + params;
	}
	else {
		theurl = callbackURL + "&" + params;
	}
	ajaxReplace(callbackTarget, theurl);
	__closeDialog();
}

//=======================================================================================
//method used to protect actions in hrefs

function confirmAction (thePart2Replace, theLink, theDialogLink) {
	$("#dialog").dialog("destroy");
	ajaxReplace('dialog', theDialogLink);
//	$("#dialog").dialog('open');
	$("#dialog").dialog(
			{
		bgiframe: true,
		resizable: false,
		height:250,
		minHeight: 250, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
		width:400,
		minWidth: 250,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		close: function () {
			__closeDialog();
		},
		buttons: {
			"Nein": function() {
			__closeDialog();
			},
			"Ja": function() {
//				alert("Lösche " + theLink.href);
//				alert("Lösche " + theLink);
//				alert(thePart2Replace + " --> " + theLink);
				ajaxReplace(thePart2Replace, theLink);
				__closeDialog();
			}
		}
	});
}

//=======================================================================================
//method used to protect actions in hrefs

function confirmActionWithFunction (theConfirmationDialogURL, theFunction) {
	$("#dialog").dialog("destroy");
	ajaxReplace('dialog', pathprefix + theConfirmationDialogURL);
//	$("#dialog").dialog('open');
	$("#dialog").dialog(
			{
		bgiframe: true,
		resizable: false,
		height:250,
		minHeight: 250, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
		width:400,
		minWidth: 250,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		close: function () {
			__closeDialog();
		},
		buttons: {
			"Nein": function() {
				__closeDialog();
			},
			"Ja": function() {
//				alert("Lösche " + theLink.href);
//				alert("Lösche " + theLink);
				theFunction();
				__closeDialog();
			}
		}
	});
}

//=======================================================================================
//method used to protect actions in hrefs

function confirmActionWithFunctionParam (theConfirmationDialogURL, theFunction, theParam) {
	$("#dialog").dialog("destroy");
	ajaxReplace('dialog', pathprefix + theConfirmationDialogURL);
//	$("#dialog").dialog('open');
	$("#dialog").dialog(
			{
		bgiframe: true,
		resizable: false,
		height:250,
		minHeight: 250, // sonst geht es im IE6 nicht, function _size in ui.dialog.js, zeile 431 geht sonst nicht
		width:400,
		minWidth: 250,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		close: function () {
			__closeDialog();
		},
		buttons: {
			"Nein": function() {
				__closeDialog();
			},
			"Ja": function() {
//				alert("Lösche " + theLink.href);
//				alert("Lösche " + theLink);
				theFunction(theParam);
				__closeDialog();
			}
		}
	});
}

//=======================================================================================
// helper method to replace a certain tag with the content of the given URL

function ajaxReplace (targetID, url) {
	//alert(url);
	var theurl = null;
	if (url.indexOf("?") == -1) {
		theurl = url + "?client_request_ajaxcutid=" + targetID;
	}
	else {
		theurl = url + "&client_request_ajaxcutid=" + targetID;
	}
	$("#" + targetID).load(theurl);
}




function ajaxReplaceWithAction (targetID, url, action) {
	var theurl = null;
	if (url.indexOf("?") == -1) {
		theurl = url + "?client_request_ajaxcutid=" + targetID;
	}
	else {
		theurl = url + "&client_request_ajaxcutid=" + targetID;
	}
//	alert(targetID + ", " + theurl);
//	alert(action);
	$("#" + targetID).load(theurl, null, action);
}



//============================================ Begin of BETA code
function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 


var _loaded = false;

function _setLoaded() {
	_loaded = true;
}
function ajaxReplaceSynchron (targetID, url) {
	_loaded = false;
	ajaxReplaceWithAction(targetID, url, _setLoaded);
	var i = 0;
	while (!_loaded && i < 20) {
		pausecomp(100);
		i = i + 1;
	}
}
//============================================ End of BETA code

//=======================================================================================
// helper method to replace a certain tag with the content of the given URL
// this function allows to have different IDs of the part to be replaced and the part
// to use as the source from the page retrieved by the URL

function ajaxReplace2 (targetID, url, cutID) {
	var theurl = null;
	if (url.indexOf("?") == -1) {
		theurl = url + "?client_request_ajaxcutid=" + cutID;
	}
	else {
		theurl = url + "&client_request_ajaxcutid=" + cutID;
	}
//	alert(targetID + ", " + theurl);
	$("#" + targetID).load(theurl);
}

function ajaxReplaceWithData(targetID, url, cutID, data) {
	var theurl = null;
	if (url.indexOf("?") == -1) {
		theurl = url + "?client_request_ajaxcutid=" + cutID;
	}
	else {
		theurl = url + "&client_request_ajaxcutid=" + cutID;
	}
//	alert(targetID + ", " + theurl);
	$("#" + targetID).load(theurl, data);
}

//=======================================================================================
// datepicker utility

function addDatePickers () {
	$("#adate").datepicker(
			{
				numberOfMonths: 3,
				showButtonPanel: true
			}
		);
}

/* basket */

var repPath = pathprefix + "/wrapper/basketEntryList.html";
var prevTimer = 0;
var goodChars = new Array(0,1,2,3,4,5,6,7,8,9);

function notifyChange(el,product) {
	var amount = el.value;
	if (amount != amount * 1) {
		amount = transfromToPrettyInt(amount);
		el.value = amount;
	}
	if (prevTimer != 0) clearTimeout(prevTimer);
	var id = el.id;
	prevTimer = setTimeout(getFunc(amount, product, id),500);
}

function notifyInstantly(el, product) {
	var amount = el.value;
	if (amount != amount * 1) {
		amount = transfromToPrettyInt(amount);
		el.value = amount;
	}
	var id = el.id;
	if (prevTimer != 0) clearTimeout(prevTimer);
	getFunc(amount,product)();
}

function getFunc(amount, product, id) {
	return function() {
		var data = {'client_request_product': product, 'client_request_quantity': amount, 'param_submitPath' : clientPagePath, 'client_request_productAddedToBasket' : 'true'};
		$('#cartList').load(repPath, data, function(){
			if (id) {
				document.getElementById(id).focus();
			}
			var iceElement = document.getElementById("isCheckoutEnabled");
			var elc = iceElement && "false" == iceElement.innerHTML;
			if (elc) {
				var gtc = document.getElementById("goToCheckout");
				gtc.className = "disbtn";
				gtc.onclick = function(){return false};
			} else {
				var gtc = document.getElementById("goToCheckout");
				gtc.className = "btn";
				gtc.onclick = function(){};
			}
		});
		
	};
}

function transfromToPrettyInt(dirtyValue) {
	var prettyValue = "";
	for (var i = dirtyValue.length;i >= 0;i--) {
		var c = dirtyValue.charAt(i);
		for (var g = goodChars.length; g >= 0; g--) {
			if (g == c) prettyValue += c;
		}
	}
	return prettyValue;
}

$(document).ready(function() {
	$("#cartProductList input.portletAmountCounter").live("blur", function() {
		notifyInstantly(this, $(this).parent().find('input[name="client_request_product"]').val());
	});
	$("#cartProductList input.portletAmountCounter").live("keyup", function() {
		notifyChange(this, $(this).parent().find('input[name="client_request_product"]').val());
	});
});


var clickedOnProduct = false;
function checkInputValue(id){							
	var valid = true;
	var input = document.getElementById(id);
	var value = input.value;
	var length = value.length;
	if (_gaq) {
		_gaq.push(['_trackPageview', '/?q='+value]);							
	}
	if (length == 0 || $.trim(value).length == 0){
		valid = false;
		if (!clickedOnProduct){
			openModalDialogWithTitle(pathprefix+'/wrapper/cemhelp.html?client_request_checkInputValue=true', help);
		}
	}
	document.getElementById('searchQuery').value = value;
	if (valid){
		document.cemSearch.submit();
	}
}

function openHelpDialog() {
	try{
		$("#dialog").dialog("destroy");
		$("#dialog").show("fast");
	} catch (e) {}
		$("#dialog").dialog({
			stack: true,
			resizable: false,
			bgiframe: true,
			height: 300,
			width: 500,
			modal: true
		});
}
function testomat(){
	ajaxReplace('table-basket', pathprefix + '/wrapper/big-basket.html');
}

$(document).ready(function(){
	if ($.prettyPhoto) {
		$("a[rel^='prettyPhoto']").prettyPhoto({
			show_title: false
		});
	}
	
	$(".portletSortableList").sortable({
		axis: "y",
		cursor: "move",
		tolerance: "pointer",
		containment: "parent",
		cancel: "input",
		update: function (event, ui) {
			var odd = true;
			var classOdd = "portletOdd";
			var classEven = "portletEven";
			$(this).children().each(function() {
				$(this).removeClass(odd ? classEven : classOdd);
				$(this).addClass(!odd ? classEven : classOdd);
				odd ^= true;
			});
		}
	}).disableSelection();
	
	$(".portletToggle").each(function() {
		$(this).bind("click", function() {
			var target = $(this).siblings(".portletTogglable")[0];
			if (target.style.display == 'none') {
				$(target).fadeIn("fast");
			} else {
				$(target).fadeOut("fast");
			}
		});
	});
	$(".portletBookingServices input[type=checkbox]").live("click", function() {
		var form = $($(this).attr("form"));
		var skipValidation = "&i_cmd_bk:BookingRequest[]_setValues_param_validateSelectedServices=false";
		/* unused - preserve errors
		if (!form.find(".portletError").length) {
			skipValidation = "";
		}
		*/
		ajaxReplace("bookingServices", "/wrapper/services.html?" + form.find("*[name!=url]").serialize() + skipValidation);
	});
	$(".portletBookingServices form").live("submit", function() {
		// preserve actual location after first ajax-replace
		$(this).find("input[name=url]").val($("#effectivePath").val());
	});
	
	$("#portletCalendar .portletCalendarFunctions .portletFunction").live("click", function() {
		ajaxReplace("portletCalendar", this.href);
		return false;
	});
	
	var lockBookableInfo = false;
	
	function hideBookableInfo() {
		if (lockBookableInfo) return;
		
		$("#bookableInfo").hide();
	}
	
	$("#portletCalendar .bookable").live("hover", function() {
		if (lockBookableInfo) return;
		
		var trigger = $(this);
		$("#portletCalendar .bookable").each(function() {
			$(this).removeClass("infoHover");
		});
		trigger.addClass("infoHover");
		
		var st = trigger.attr("data-startTimes").split(",");
		var sts = trigger.attr("data-startTimestamps").split(",");
		var ix = -1;
		var bookableInfo = $("#bookableInfo");
		bookableInfo.find(".timeSlot").each(function() {
			if (++ix < st.length) {
				var timeSlot = $(this);
				var startTime = st[ix];
				var baseHREF = timeSlot.attr("data-baseHREF");
				timeSlot.css("display", "");
				timeSlot.html(startTime);
				timeSlot.attr("href", baseHREF + escape(sts[ix]));
			} else {
				$(this).css("display", "none");
			}
		});
		var bounds = trigger.offsetParent();
		bounds.one("mouseleave", function() {
			hideBookableInfo();
			$("#portletCalendar .bookable").each(function() {
				$(this).removeClass("infoHover");
			});
		});
		var pos = trigger.position();
		var orientationNS = pos.top + bookableInfo.outerHeight() > bounds.innerHeight();
		var orientationWE = bounds.innerWidth() / 2 - pos.left > 0;
		var top = pos.top - (orientationNS ? bookableInfo.outerHeight() - trigger.outerHeight() - 1 : - 1);
		var left = pos.left + (orientationWE ? (trigger.outerWidth() - 10) : - bookableInfo.outerWidth() + 10);
		if (orientationWE) {
			bookableInfo.addClass("orientationWE").removeClass("orientationEW");
		} else {
			bookableInfo.addClass("orientationEW").removeClass("orientationWE");
		}
		bookableInfo.css("top", top + "px");
		bookableInfo.css("left", left + "px");
		$("#bookableInfo").one("mouseleave", function() {
			trigger.removeClass("infoHover");
		});
		bookableInfo.show();
	});
	$("#bookableInfo .timeSlot").live("click", function() {
		lockBookableInfo = true;
		var ts = $(this);
		ajaxReplaceWithAction("bookingAvailabilityAppointment", this.href, function() {
			ts.effect("transfer", { to: $("#bookingAppointmentInfo") }, 750, function() {
				$("#bookingAppointmentInfo").effect("pulsate", {times: 1}, 500);
				lockBookableInfo = false;
				hideBookableInfo();
			});
			$("#bookingAvailabilityAppointment input[name=url]").val("/booking/availability.html")
		});
		return false;
	});
	$("#bookableInfo").live("mouseleave", function() {
		hideBookableInfo();
	});
	$("#bookableInfo .close").live("click", function() {
		hideBookableInfo();
		return false;
	});
	$("#bkConfirmLoginButton").live("click", function() {
		ajaxReplace("bookingConfirm", this.href + '?' + $("#bkConfirmLoginUserName, #bkConfirmLoginPassword").serialize() + "&param_loginLogon=true");
		return false;
	});
	$("#bkConfirmLoginUserName, #bkConfirmLoginPassword").live("keydown", function(event) {
		if (event.which == '13') {
			$("#bkConfirmLoginButton").click();
			return false;
		}
	});
});
