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: "", //deprecated...
    proxyUrl: "", //use this instead!

    getProxyUrl: function() {
        if(this.proxyUrl != "") {
            return this.proxyUrl;
        } else {
            return this.baseUrl + "AlpSystems/Proxy.php";
        }
    },

	currency: "EUR",
	
	PleaseWait: "Please wait...",
	PleaseReview: "Please review the following and try again",
	WeeklyRate: "Weekly rate",
	Unavailable: "Unavailable",
    oneNight: "1 night",
    xNights: "$number nights",
	
	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";
	},
	
	onLogoutUrl: null,

	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.");
				if(AlpSystems.onLogoutUrl == null) {
					document.location.reload();
				} else {
					window.top.document.location.href = AlpSystems.onLogoutUrl;	
				}
			}
         });
	},
	
	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",
	
	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() {
		$("#" + this.submitButtonId).bind("click", this.submitClicked.bind(this));
		$(document).ajaxError(this.onAjaxFailed.bind(this)); 
	},

	onAjaxSuccess: function(results) {

		var button = $('#' + this.submitButtonId)[0];
		if(typeof(button.value) != "undefined") {
			button.value = this.originalButtonText;
			button.disabled = false;
		} else {
			button.innerHTML = this.originalButtonHtml;
		}
		
		//handle form errors:
		if(results.success == false) {
			this.validationFailureHandler(results.errors);
			return;
		}
		
		if(this.processRedirectResponse) {
			if(results.FormRedirectAction != null) {
				// we're supposed to submit a form to redirect them to the bank:
				if($("#BankForm").length == 0) {
					var form = document.createElement("form");
					form.method = "POST";
					form.id = "BankForm";
					document.body.appendChild(form);
				}
				
				var form = $("#BankForm")[0];
				
				form.action = results.FormRedirectAction;
				form.innerHTML = results.FormRedirectContents;
				isRedirecting = true;
				form.submit();
				return;
				
			} else if(results.RedirectUrl != null) {
				//we're supposed to send them directly to the confirmation screen:
				isRedirecting = true;
				document.location.href = results.RedirectUrl;
				return;
			}
		}

		this.fireEvent("onFormResponse", results);
	},
	
	processRedirectResponse: false,
	
	onAjaxFailed: function(e, xhr, settings, exception) {
		$('#' + this.submitButtonId)[0].value = this.originalButtonText;
		$('#' + this.submitButtonId)[0].disabled = false;
		var error = "Error in: " + settings.url + ' - ' + xhr.responseText;
		this.validationFailureHandler([ { msg: error }]);
	},
	
	formData: null,
	
	restoreButton: function() {
		$('#' + this.submitButtonId)[0].value = this.originalButtonText;
		$('#' + this.submitButtonId)[0].disabled = false;
	},

	submitClicked: function() {
		this.originalButtonText = $('#' + this.submitButtonId)[0].value;
		this.originalButtonHtml = $('#' + this.submitButtonId)[0].innerHTML;
		
		var button = $('#' + this.submitButtonId)[0];
		if(typeof(button.value) != "undefined") {
			button.value = AlpSystems.PleaseWait;
			button.disabled = true;
		} else {
			button.innerHTML = AlpSystems.PleaseWait;
		}
		

		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, errorDiv, scrollTo, areMessagesAlreadyHtml) {
		
        if (typeof (errorDiv) == "undefined") {
            errorDiv = $("#Notification")[0];
        }

        if (typeof (scrollTo) == "undefined") {
            scrollTo = true;
        }

		if(typeof(areMessagesAlreadyHtml) == "undefined") {
			areMessagesAlreadyHtml = false;
		}
		
		var sError = "";
		if(errors.length == 1) {
			if(areMessagesAlreadyHtml) {
				sError = errors[0].msg;
			} else {
				sError = AlpSystems.Util.htmlEncode(errors[0].msg);
			}
		} else {
			var aErrors = [];
			for(var i=0; i < errors.length; i++) {
				if(areMessagesAlreadyHtml) {
					aErrors.push(errors[i].msg);
				} else {
					aErrors.push(AlpSystems.Util.htmlEncode(errors[i].msg));
				}
			}
			sError = AlpSystems.PleaseReview + ":<ul><li>" + aErrors.join("</li><li>") + "</li></ul>";
		}
		
        errorDiv.innerHTML = sError;
        $(errorDiv).addClass("ErrorMessage");
        $(errorDiv).removeClass("InfoMessage");
        errorDiv.style.display = "";
		
        if (scrollTo) {
		//scroll to top so they can see the problems:
            AlpSystems.Util.scrollToElement(errorDiv);
	}
    }

};

AlpSystems.Util = {
	
    hasLocalStorage: function () {
        return 'localStorage' in window && window['localStorage'] !== null;
    },

	scrollToElement: function(theElement){

	  var selectedPosX = 0;
	  var selectedPosY = 0;
				  
	  while(theElement != null){
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	  }
										  
	 window.scrollTo(selectedPosX,selectedPosY);
	},
	
	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) {
		
		if($("#" + id + "Hour").length > 0) {

			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]);
			}
		} else {
			//hr and min in same dropdown:
			
			for(var hour=0; hour < 24; hour++) {
				for(var minute=0; minute < 60; minute+=5) {
					var text = hour < 10 ? "0" + hour : "" + hour;
					text += ":" + (minute < 10 ? "0" + minute : "" + minute);
					var option = $.create("option", {attributes: {value: text}, children: text });
					option.appendTo($("#" + id + "HourMinute")[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 (inputs, value) {
		for(var i=0; i < inputs.length; i++) {
			var input = inputs[i];
			if (input.type == "text" || input.type == "hidden" || input.type == "textarea") {
				input.value = value;
			} else if (input.type == "checkbox") {
				input.checked = value != "" && value != null;
			} else if (input.type == "radio") {
				input.checked = value == input.value;
			} else {
				//select?
				for (var i = 0; i < input.length; i++) {
					if (input[i].value == value) {
						input[i].selected = true;
					}
				}
			}
		}
    },

    //get the current value of any text, textarea, select, radio, or checkbox:
    getValue: function (selectField) {

        if (selectField.type == "hidden" || selectField.type == "text") {
            return selectField.value;
        } else if (selectField.type == "checkbox") {
            return selectField.checked ? selectField.value : "";
        } else if (selectField.options) {
            return selectField.options[selectField.selectedIndex].value
        } else if (typeof (selectField.length) == "undefined") {
			//radio
			if (selectField.checked) {
				return selectField.value
			} else {
				return "";
			}
		} else {
			//radio group?
			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, " ");
	},
	
        hasUrlParam: 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 false;
            else
                return true;
        },


        getUrlParam: function (name, url) {
	        if(typeof(url) == "undefined")
		        url = document.location.href;

            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(url);
            if (results == null)
		return "";
	  else
		return AlpSystems.Util.urlDecode(results[1]);
	},
	
        toggleClass: function(divs, className, shouldHave) {
	        if(shouldHave) {
		        divs.addClass(className);
	        } else {
		        divs.removeClass(className);
	        }
        },

	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];
	},
	
        replaceUrlParam: function(strName, strValue, strURL)
        {
	        if(typeof(strURL) == "undefined")
		        strURL = document.location.href;
	
	        //remove anchor:
	        if(strURL.match(/#.*$/)) {
		        strURL = strURL.replace(/(#.*)$/, "");
	        }
		
	        ////If the current URL is an <ASP_URL>...
	        //  - If strName is a <name>, this function replaces the associated
	        //    <value> to strName with the new <value>, strValue.
	        //  - Otherwise, this function adds a new <key_pair> to the <ASP_URL>
	        //    with the given <name> and <value>, strName and strValue.
	        //
	        //  NOTE: Returns emptystring if the URL is malformed

	        strOldValue = AlpSystems.Util.getUrlParam(strName, strURL)
	
	        if(strOldValue == "")
	        {
		        //No matching pair, so add it:
		        if(strValue != "")
		        {
			        //Add new value to the beginning of the <querystring>:
			        iQMark = strURL.indexOf("?")

			        if(iQMark == -1)
			        {
				        strURL = strURL + "?" + escape(strName) + "=" + escape(strValue)
			        }
			        else
			        {
				        strRightSide = strURL.substring(iQMark + 1, strURL.length)
				        strLeftSide  = strURL.substring(0, iQMark + 1)
				
				        strURL = strLeftSide + escape(strName) + "=" + escape(strValue) + "&" + strRightSide
			        }
		        }
		        //else: actually is a delete, so leave unchanged.
	        }
	        else
	        {
		        //Replace the existing value:
		        iQMark = strURL.indexOf("?")

		        iValueStart = strURL.indexOf(escape(strName) + "=") + (escape(strName) + "=").length
		        strLeftSide = strURL.substring(0, iValueStart)
		        strRightSide = strURL.substring(iValueStart, strURL.length)

		        iAmp = strRightSide.indexOf("&")
		
		        if(iAmp == -1)
		        {
			        // Must be the last key_pair in the querystring.
			        if(strValue != "")
			        {
				        strURL = strLeftSide + strValue
			        }
			        else
			        {
				        //actually want to delete the <name> from the querystring.
				        //also delete the lefthand seperator, either '?' or '&':
				        iKeypairStart = strLeftSide.lastIndexOf(escape(strName) + "=")
				        strLeftSide = strLeftSide.substring(0, iKeypairStart)
				        strURL = strLeftSide
			        }
		        }
		        else
		        {
			        if(strValue != "")
			        {
				        strRightSide = strRightSide.substring(iAmp, strRightSide.length)
				        strURL = strLeftSide + escape(strValue) + strRightSide
			        }
			        else
			        {
				        //actually want to delete the <name> from the querystring.
				        //at this point there exists at least one other <key-pair> 
				        //to the right. So delete the righthand token, either '?' or
				        //'&', as well as this <key-pair>:
				        strRightSide = strRightSide.substring(iAmp + 1, strRightSide.length)
				        iKeypairStart = strLeftSide.lastIndexOf(escape(strName) + "=")
				        strLeftSide = strLeftSide.substring(0, iKeypairStart)
				        strURL = strLeftSide + strRightSide
			        }
		        }
	        }

	        return strURL
        },

	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);
		}
	},
	
	mouseX: function(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX)
	   return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
	},
	
	mouseY: function(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY)
	   return evt.clientY + (document.documentElement.scrollTop ?
	   document.documentElement.scrollTop :
	   document.body.scrollTop);
	else return null;
	}	
};


//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;
	}
};

