AlpSystems = {
	
	init: function() {
		$(".LogoutButton").bind("click", this.logout, this);

		if($("#Notification").length > 0) {
			if(AlpSystems.Util.getCookie("Notification") != "") {
				AlpSystems.Notification.showMessage(AlpSystems.Util.getCookie("Notification"));
				AlpSystems.Util.deleteCookie("Notification");
			}
		}
	},
	
	baseUrl: "",
	currency: "EUR",
	
	showMask: function(message)
	{
		if($("#ProgressMessage").length == 0) {
			//feature not in this page.
			return;
		}
		
		AlpSystems.Util.setHtml($("#ProgressMessage"), message)
	
		//document.body.onresize = Oasys.SetLayerPosition;
		//document.body.onscroll = Oasys.SetLayerPosition;
		AlpSystems.setLayerPosition();
	
		$("#masker")[0].style.display = "block"; 
		$("#progress")[0].style.display = "block"; 
	},
	
	hideMask: function()
	{
		if($("#ProgressMessage").length == 0) {
			//feature not in this page.
			return;
		}
		
		window.onresize = function(){ }
		window.onscroll = function(){ }
	
		var masker = $("#masker")[0];
		var progress = $("#progress")[0];
	
		masker.style.display = "none"; 
		progress.style.display = "none";
	},

	logout: function(target) {
		
		AlpSystems.showMask("Logging out...");

		//TODO change to call only for THIS call:
		$(document).ajaxError(function() {
			AlpSystems.hideMask();
			alert("A problem occured while logging out. Please try again later or contact us for more details.");
		}); 
		
		$.ajax({  
             url: AlpSystems.baseUrl + "AlpSystems/Proxy.php?method=::Logout",
             type: "POST",
             data: { },
			 cache: false,
			 dataType: "json",
             success: function(results) {
				 //reload and have the next screen show a message, since could be on a booking
				 //form or something that's not easy to adjusts state to public/non-logged in:
				AlpSystems.Util.setCookie("Notification", "You have been successfully logged out.");
				document.location.reload();
			}
         });
	},
	
	ajaxError: "An error occured connecting to the booking engine. Please try your query again later or contact us by email or telephone indicating the following error details - @error",
	
	pleaseWait: "Please wait...",

	months: [
		"January",
		"February",
		"March",
		"April",
		"May",
		"June",
		"July",
		"August",
		"September",
		"October",
		"November",
		"December"
	],
	
	days: [ "S", "M", "T", "W", "T", "F", "S" ],
	
	monthHeader: "#month #year",
	
	firstDay: 1,
	
	apiDateFormat: "yyyy-M-d",
	apiDateTimeFormat: "yyyy-M-d H:m",

	setLayerPosition: function() 
	{
		///Masker should mask all the screen and scrolled areas:
		
		var shadow = $("#masker")[0];
	
		if(typeof window.pageYOffset != "undefined")
		{
			///FireFox
			scrollTop = window.pageYOffset
			scrollLeft = window.pageXOffset
			
			///But this INCLUDES the scrollbar sizes, causing scrollbars to change/flicker during the 
			///masking
			scrollFudge = -30
		}
		else
		{
			//IE
			scrollTop = window.scrollTop
			scrollLeft = document.scrollLeft
			scrollFudge = 0
		}
		
		if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrollTop = window.pageYOffset;
		scrollLeft = window.pageXOffset;
	  } else {
		//DOM compliant
		scrollTop = document.body.scrollTop;
		scrollLeft = document.body.scrollLeft;
	  }
	
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			windowWidth = window.innerWidth;
			windowHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	  
		///Masker (shadow) should fill the entire scrollable area:
		shadow.style.width = windowWidth+ scrollFudge + "px";
		shadow.style.height = windowHeight + scrollFudge + "px";
		shadow.style.left = scrollLeft + "px"
		shadow.style.top = scrollTop + "px"
	
		///Progress div should be centered but in the current scrolled window area:
		var progress = $("#progress")[0];
		progress.style.left = parseInt((windowWidth - 200) / 2) + scrollLeft + "px";
		progress.style.top = parseInt((windowHeight - 100) / 2) + scrollTop + "px";
	}	
};

AlpSystems.AjaxForm = new Class({
	
	Implements: [Events],

	submitButtonId: "SubmitButton",
	formId: "Form",

	initialize: function(config) {
		$.extend(this, config);
	},

	validationFailureHandler: function(errors) {
		alert("Some inputs are not correct. Please double check and try again.");
	},

	init: function() {
		$("#SubmitButton").bind("click", this.submitClicked.bind(this));
		$(document).ajaxError(this.onAjaxFailed.bind(this)); 
	},

	onAjaxSuccess: function(results) {
		
		$('#SubmitButton')[0].value = this.originalButtonText;
		$('#SubmitButton')[0].disabled = false;
		
		//handle form errors:
		if(results.success == false) {
			this.validationFailureHandler(results.errors);
			return;
		}

		this.fireEvent("onFormResponse", results );
	},
	
	onAjaxFailed: function(e, xhr, settings, exception) {
		$('#SubmitButton')[0].value = this.originalButtonText;
		$('#SubmitButton')[0].disabled = false;
		var error = "Error in: " + settings.url + ' - ' + xhr.responseText;
		this.validationFailureHandler([ { msg: error }]);
	},
	
	formData: null,
	
	restoreButton: function() {
		$('#SubmitButton')[0].value = this.originalButtonText;
		$('#SubmitButton')[0].disabled = false;
	},

	submitClicked: function() {
		this.originalButtonText = $('#SubmitButton')[0].value;
		$('#SubmitButton')[0].value = "Please wait...";
		$('#SubmitButton')[0].disabled = true;

		this.formData = $("#" + this.formId).serialize();

		this.errors = [];
		this.fireEvent("beforeSubmit", { });
		
		if(this.errors.length > 0) {
			this.restoreButton();
			this.validationFailureHandler(this.errors);
			return;
		}
		
		$.ajax({  
             url: $("#" + this.formId)[0].action,   
             type: "POST",  
             data: this.formData,       
			 cache: false,
			 dataType: "json",
             success: this.onAjaxSuccess.bind(this)
         });  
	}
});

AlpSystems.Notification = {
	
	showMessage: function(message) {
		$("#Notification")[0].innerHTML = message;
		$("#Notification").addClass("InfoMessage");
		$("#Notification").removeClass("ErrorMessage");
		$("#Notification")[0].style.display = "";
		
		//scroll to top so they can see the problems:
		var elem = $("#Notification")[0];
		window.scrollTo(elem.scrollLeft, elem.scrollTop);
	},
	
	showErrors: function(errors) {
		var sError = "";
		if(errors.length == 1) {
			sError = AlpSystems.Util.htmlEncode(errors[0].msg);
		} else {
			var aErrors = [];
			for(var i=0; i < errors.length; i++) {
				aErrors.push(AlpSystems.Util.htmlEncode(errors[i].msg));
			}
			sError = "Please review the following and try again:<ul><li>" + aErrors.join("</li><li>") + "</li></ul>";
		}
		
		$("#Notification")[0].innerHTML = sError;
		$("#Notification").addClass("ErrorMessage");
		$("#Notification").removeClass("InfoMessage");
		$("#Notification")[0].style.display = "";
		
		//scroll to top so they can see the problems:
		var elem = $("#Notification")[0];
		window.scrollTo(elem.scrollLeft, elem.scrollTop);
	}
};

AlpSystems.Util = {
	
	zeroPad: function(number, zeros) {
		//HACKHERE - 2!
		if(number < 10) {
			return "0" + number;
		} else {
			return number;
		}
	},
	
	setCookie: function(sName, sValue)
	{
	  document.cookie = sName + "=" + escape(sValue) + "; expires=; ; path=/"
	},
	
	getCookie: function(sName)
	{
	  // cookies are separated by semicolons
	  var aCookie = document.cookie.split("; ");
	  for (var i=0; i < aCookie.length; i++)
	  {
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) 
		{
			if(!aCrumb[1])
			{
				//alert("returning nothing");
				return ""
			}
			else
			{
				//alert("returning: " + unescape(aCrumb[1]))
				return AlpSystems.Util.urlDecode(aCrumb[1]);
			}
		}
	  }
	
	  // a cookie with the requested name does not exist
	  return "";
	},
	
	deleteCookie: function( name ) 
	{
		d = new Date()
		document.cookie = name + "=blah; expires=" + d.toGMTString() + "; ; path=/";
	},
	
	setHtml: function(elements, html) {
		for(var i=0; i < elements.length; i++) {
			elements[i].innerHTML = html;
		}
	},
	
	replaceHtml: function(elements, searchText, replacement) {
		for(var i=0; i < elements.length; i++) {
			elements[i].innerHTML = elements[i].innerHTML.replace(searchText, replacement);
		}
	},
	
	addCommas: function(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	},
	
	fillTimeOptions: function(id) {

		for(var i=0; i < 24; i++) {
			var option = $.create("option", {attributes: {value: i}, children: i < 10 ? "0" + i : i });
			option.appendTo($("#" + id + "Hour")[0]);
		}

		for(var i=0; i < 60; i+=5) {
			var option = $.create("option", {attributes: {value: i}, children: i < 10 ? "0" + i : i });
			option.appendTo($("#" + id + "Minute")[0]);
		}
		
	},

	htmlEncode: function(ch, preserveLineBreaks) {
	
		if(typeof(preserveLineBreaks) == "undefined") {
			preserveLineBreaks = true;
		}
		
		if(ch == null) {
			return null;
		}
		
		ch = new String(ch);
		
		//http://www.asp-php.net/tutorial/asp-php/glossaire.php?glossid=57
		ch = ch.replace(/&/g,"&amp;");
		ch = ch.replace(/\"/g,"&quot;");
		ch = ch.replace(/\'/g,"&#039;");
		ch = ch.replace(/</g,"&lt;");
		ch = ch.replace(/>/g,"&gt;");
		
		if(preserveLineBreaks) {
			ch = ch.replace(/\n/g,"&nbsp;<br/>");
		}
		
		return ch;
	},

	setValue: function(input, value) {
		for(var i=0; i < input.length; i++) {
			if(input[i].value == value) {
				input[i].checked = true;
			}
		}
	},

	//get the current value of any text, textarea, select, radio, or checkbox:
    getValue: function(selectField)
    {
		if(selectField.type == "hidden") {
			return selectField.value;
		}
		
		if(selectField.options)
		{
	    	return selectField.options[selectField.selectedIndex].value
	    }
	    else
    	{
    		////This is a <radio> object
    		if(typeof(selectField.length) == "undefined")
    			if(selectField.checked)
	    			return selectField.value
	    		else
	    			return ""
    		else
    			for(var i=0; i < selectField.length; i++)
    			{
    				if(selectField[i].checked)
    					return selectField[i].value
    			}

    		return ""
    	}
    },
	
	fillDropdown: function(id, minimum, maximum) {
		for(var i=minimum; i <= maximum; i++) {
			 $.create("option", {attributes: {value: i}, children: i}).appendTo($("#" + id)[0]);
		}
	},
	
	addMinuteOptions: function(selectId) {
		for(var i=0; i < 60; i+=5) {
			if(i < 10) {
				text = "0" + i;
			} else {
				text = i;
			}
			 $.create("option", {attributes: {value: i}, children: text}).appendTo($("#" + selectId)[0]);
		}
	},
	
	//http://www.netlobo.com/url_query_string_javascript.html
	urlDecode: function(encodedString) {
	  var output = encodedString;
	  var binVal, thisString;
	  var myregexp = /(%[^%]{2})/;
	  while ((match = myregexp.exec(output)) != null
				 && match.length > 1
				 && match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	  }
	  return output.replace(/\+/g, " ");
	},
	
	getUrlParam: function( name )
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return AlpSystems.Util.urlDecode(results[1]);
	},
	
	getUrlParamNames: function( ) // gpn stands for 'get parameter names'
	{
		var params = new Array( );
		var regex = /[\?&]([^=]+)=/g;
		while( ( results = regex.exec( window.location.href ) ) != null )
			params.push( results[1] );
		return params;
	},
	
	getUrlQuery: function() {
		return window.location.href.match(/(\?.*)?$/)[0];
	},
	
	formatMoney: function(money) {
		if(AlpSystems.currency == "EUR") {
			return "€" + AlpSystems.Util.sprintf("%.2f", money);
		} else {
			return "CHF " + AlpSystems.Util.addCommas(AlpSystems.Util.sprintf("%.2f", money));
		}
	},

	formatMoneyRange: function(moneyFrom, moneyTo) {
		if(moneyFrom == moneyTo) {
			return AlpSystems.Util.formatMoney(moneyFrom);
		} else {
			return AlpSystems.Util.formatMoney(moneyFrom) + "-" + AlpSystems.Util.formatMoney(moneyTo);
		}
	}
};


//http://www.webtoolkit.info/javascript-sprintf.html
sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
AlpSystems.Util.sprintf = sprintfWrapper.init;

AlpSystems.Properties = { 
};

AlpSystems.Transport = { 

	getPlaceById: function(places, id) {
		for(var i=0; i < places.length; i++) {
			if(id == places[i].PlaceId) {
				return places[i];
			}
		}
	},
	
	getChildrenPlaces: function(places, placeId) {
		var children = [];
		for(var i=0; i < places.length; i++) {
			if(placeId == places[i].Parent) {
				children.push(places[i]);
			}
		}
		
		return children;
	}
};

