﻿var PVOA = {
	
	//http://www.peej.co.uk/articles/rich-user-experience.html
	getHTTPObject : function() {
		if (typeof XMLHttpRequest != 'undefined') { 
			return new XMLHttpRequest(); 
		} 
		
		try { 
			return new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				return new ActiveXObject("Microsoft.XMLHTTP"); 
			} 
			catch (e) {} 
		} 
		
		alert("This page is not compatible with your web browser, since it is running a very old version. Please upgrade it and try again.");
	},
	
	// public functions //
	callMethod: function(method, postParams, pleaseWait, onSuccess, onFailure) {
		var ajaxParams = new Object();
		ajaxParams.method = "post";
		var aParams = [ ];
		for(var key in postParams) {
		    aParams.push(encodeURIComponent(key) + "=" + encodeURIComponent(postParams[key]));
		}
		
		var sParams = aParams.join("&");

		PVOA.clientOnAjaxFailure = onFailure;
		PVOA.clientOnAjaxSuccess = onSuccess;
	
		PVOA.clearErrors();
		PVOA.showMask(pleaseWait);

		var url = PVOA.root + method;
		
		PVOA.http = PVOA.getHTTPObject(); 
		PVOA.http.open("POST", url, true); 
		PVOA.http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		PVOA.http.onreadystatechange = function() { 
			if (PVOA.http.readyState != 4) { 
				return;
			}
			
			if(PVOA.http.status == 200) {
				PVOA.onAjaxSuccess(PVOA.http); 
			} else {
				PVOA.onAjaxFailure(PVOA.http);
			}
		} 
		PVOA.http.send(sParams);
	},
	
	// private functions //
	
	hasItems: function(array) {
		
		//HACKHERE - how to get number of associtive items?
		for(key in array) {
			if(typeof(array[key]) == "string") {
				return true;
			}
		}
		
		return false;
	},

    getSelected: function(selectField)
    {
		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 ""
    	}
    },
	
	onAjaxFailure: function(response) {
		window.setTimeout(PVOA.onAjaxFailure2.bind(PVOA, response), 0);
	},

	onAjaxFailure2: function(t) {
		PVOA.hideMask();
		error = PVOA.strings.ajaxError.replace("@error", t.statusText + "' (" + t.status + ") - " + t.responseText);
		PVOA.showErrors({system: error});

		if(PVOA.clientOnAjaxFailure) {
			PVOA.clientOnAjaxFailure();
		}
	},

	onAjaxSuccess: function(response) {
		window.setTimeout(PVOA.onAjaxSuccess2.bind(PVOA, response), 0);
	},
	
	onAjaxSuccess2: function(response) {
		PVOA.hideMask();

		sResponse = response.responseText;
		
		// expected to be json in all cases:
		jResponse = JSON.parse(sResponse);
		//sResponse = sResponse.replace(/(\n|\r)/g, "");

		if(!jResponse) {
			PVOA.showErrors({system: PVOA.strings.ajaxError.replace("@error", "Unexpected response format (JSON) - " + sResponse)});
			if(PVOA.clientOnAjaxFailure) {
				PVOA.clientOnAjaxFailure();
			}
			return;
		}
		
		var errors = {};
		var hasErrors = false;
		for(var key in jResponse.ValidationFailures) {
			errors[key] = jResponse.ValidationFailures[key];
			hasErrors = true;
		}
		
		if(hasErrors) {
			PVOA.showErrors(errors);
			if(PVOA.clientOnAjaxFailure) {
				PVOA.clientOnAjaxFailure();
			}
			return;
		}
		
		if(jResponse.SuccessMessage != null) {
			// as in, enquiry sent, show a message to confirm:
			PVOA.showMessage(jResponse.SuccessMessage);
			$("pvoaActionBody").style.display = "none";
		} else if(jResponse.FormRedirectAction != null) {
			// we're supposed to submit a form to redirect them to the bank:
			$("redirectForm").action = jResponse.FormRedirectAction;
			$("redirectForm").innerHTML = jResponse.FormRedirectContents;
			$("redirectForm").submit();
		} else if(jResponse.RedirectUrl != null) {
			document.location.href = jResponse.RedirectUrl;
		}
		
		if(PVOA.clientOnAjaxSuccess) {
			PVOA.jResponse = jResponse;
			window.setTimeout(PVOA.onAjaxSuccess3, 1);
		}
	},
	
	onAjaxSuccess3: function() {
		PVOA.clientOnAjaxSuccess(PVOA.jResponse);
	},
	
	/// UI functions. override with your own if needed. //
	
	showMask: function(message)
	{
		//TODO - revise to create mask div on the fly and absolute position properly...
		return;
		
		PVOA.setInnerText(document.getElementById("ProgressMessage"), message)
	
		//document.body.onresize = PVOA.SetLayerPosition;
		//document.body.onscroll = PVOA.SetLayerPosition;
		PVOA.setLayerPosition();
	
		document.getElementById("masker").style.display = "absolute"; 
		document.getElementById("progress").style.display = "block"; 
	},
	
	hideMask: function()
	{
		//TODO - revise to create mask div on the fly and absolute position properly...
		return;
		window.onresize = function(){ }
		window.onscroll = function(){ }
	
		var masker = document.getElementById("masker");
		var progress = document.getElementById("progress");
	
		masker.style.display = "none"; 
		progress.style.display = "none";
	},
	
	showMessage: function(message) {
		$("Notification").className = "InfoMessage";
		$("Notification").innerHTML = message;
	},
	
	showErrors: function(errors) {
		errorMessage = [];
		for(field in errors) {
			if(typeof(errors[field]) != "string") {
				continue;
			}
			
			errorMessage.push(errors[field]);
		}
		
		$("Notification").className = "ErrorMessage";
	
		if(errorMessage.length == 1) {
			$("Notification").innerHTML = errorMessage[0];
		} else {
			$("Notification").innerHTML = "<ul><li>" + errorMessage.join("</li><li>") + "</li></ul>";
		}
	
		///Scroll to the top of the page so they can see the new message:
		//TODO - scroll to notification div, not top of page
		//elem = document.getElementById("Notification");
		//window.scrollTo(elem.scrollLeft, elem.scrollTop);
	},
	
	clearErrors: function() {
		$("Notification").innerHTML = "";
		$("Notification").className = "";
	},
	
	// helper methods used for the UI functions
	
	setInnerText: function(obj, newValue)
	{
		if (document.all) // IE;
			obj.innerText = newValue;
		else if (obj.textContent)
			obj.textContent = newValue;
	},
	
	setLayerPosition: function() 
	{
		///Masker should mask all the screen and scrolled areas:
		
		var shadow = document.getElementById("masker");
	
		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 = document.getElementById("progress");
		progress.style.left = parseInt((windowWidth - 200) / 2) + scrollLeft + "px";
		progress.style.top = parseInt((windowHeight - 100) / 2) + scrollTop + "px";
	},

	parseDate: function(value) {
		formats = [
			"d/m/y",
			"d/m/Y",
			"j/m/y",
			"j/m/Y",
			"d/n/y",
			"d/n/Y",
			"j/n/y",
			"j/n/Y" ];

		for(var i=0; i < formats.length; i++) {
			date = Date.parseDate(value, formats[i]);
			if(date) {
				return date;
			}
		}
		
		return null;
	},
	
	formatPriceRange: function(price1, price2) {
		if(parseInt(price1) == parseInt(price2)) {
			return PVOA.formatPrice(price1);
		} else {
			return "€" + parseInt(price1) + "-" + parseInt(price2);
		}
	},
	
	formatPrice: function(price1) {
		return "€" + parseInt(price1);
	},
	
	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,

	
	onScrollMonth: function(direction, propertyId, currentStart, numMonths) {
		
		var newDate = PVOA.parseUnivDate(currentStart);
		newDate.setMonth(newDate.getMonth() + direction*2);
		PVOA.loadingPropId = propertyId;
		PVOA.loadingNumMonths = numMonths;
		
		PVOA.callMethod("Website/GetPropertyInfo", {
			propertyIds: [propertyId],
			includeCal: "True",
			calStartYear: newDate.getFullYear(),
            calStartMonth: newDate.getMonth()+1,
            calNumMonths: numMonths,
            includePricingKey: true,
            includePrice: false 
			}, "Please wait...", PVOA.onLoadedMonth, PVOA.onFailedMonth);
	},
	
	loadingPropId: null,
	loadingNumMonths: null,
	
	onFailedMonth: function() {
		alert("Could not load calendar data. Please check your internet connection and try again.");
	},
	
	onLoadedMonth: function(data) {
		var propData = data["Properties"][0];
		$("Cal" + PVOA.loadingPropId).innerHTML = PVOA.outputCalendar(
			PVOA.parseUnivDate(data.CalStart),
			propData.CalData,
			data.PricingKey,
			true,
			PVOA.loadingPropId,
			true,
			PVOA.loadingNumMonths,
			false);
	},

	outputCalendar: function(
		calStart, 
		data, 
		legend, 
		includeScrollers, 
		propertyId, 
		includeLegend, 
		numMonths, 
		includeWrapper
	) {
		
		var monthsHtml = [];
		
		var index = 0;
		var numMonths = 0;
		var weekNumber = 0;
		for(var date = new Date(calStart); 
			index < data.length+1;
			index++, date.setDate(date.getDate()+1)
		) {
			
			if(date.getDate() == 1) {
				if(index > 0) {
					///fast forward to end of row:
					var ffAmount = (PVOA.firstDay + 7 - date.getDay()) % 7;
					
					for(var i=0;
						i < ffAmount;
						i++) {
						monthsHtml[numMonths-1] += "<td class='PvoaDaySpacer'></td>";
					}
					
					///Add blank weeks for February, etc:
					for(var i=weekNumber+1; i <= 6; i++) {
						monthsHtml[numMonths-1] += "<tr><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td><td class='PvoaDaySpacer'></td></tr>";
					}

					monthsHtml[numMonths-1] += "</table>";
					
					if(index == data.length) {
						break;
					}
				}
				
				numMonths++;
				weekNumber = 1;
				
				var monthHeader = PVOA.monthHeader;
				monthHeader = monthHeader.replace(/#year/g, date.getFullYear());
				monthHeader = monthHeader.replace(/#month/g, PVOA.months[date.getMonth()]);
				monthsHtml[numMonths-1] = "<table class='PvoaMonth' cellspacing='0'><thead><tr class='PvoaMonthName'><th colspan='7'>" + monthHeader + "</th></tr>";
				
				monthsHtml[numMonths-1] += "<tr class='PvoaWeekdays'>";
				for(var day=PVOA.firstDay; day < PVOA.firstDay+7; day++) {
					monthsHtml[numMonths-1] += "<th>" + PVOA.days[day % 7] + "</th>";
				}
				monthsHtml[numMonths-1] += "</tr></thead><tbody><tr>";

				///fast forward to the first of the month:
				var ffAmount;
				if(date.getDay() >= PVOA.firstDay) {
					ffAmount = date.getDay() - PVOA.firstDay;
				} else {
					ffAmount = date.getDay()+7 - PVOA.firstDay;
				}
				
				for(var i=0; i < ffAmount; i++) {
					monthsHtml[numMonths-1] += "<td class='PvoaDaySpacer'></td>";
				}
				
			} else if(date.getDay() == PVOA.firstDay) {
				monthsHtml[numMonths-1] += "</tr><tr>";
				weekNumber++;
			}
			
			if(data.charAt(index) == "X" 
						   || data.charAt(index) == "?" 
						   || data.charAt(index) == "/" 
						   || data.charAt(index) == "0") {
				//unavailable:
				monthsHtml[numMonths-1] += "<td class='PvoaUnavailable'></td>";
			} else {
				monthsHtml[numMonths-1] += "<td style='background-color:#" + legend[data.charAt(index)].Color + "'>" + date.getDate() + "</td>";
			}
		}
		
		var html = "";
		if(typeof(includeWrapper) == "undefined") {
			includeWrapper = true;
		}
		
		if(includeWrapper) {
			html += "<div id='Cal" + propertyId + "'>"; 
		}
		
		html += "<table class='PvoaMonths' align='center'><tr><td valign='middle'>";
		if(includeScrollers && calStart > new Date()) {
			html += "<div class='PvoaScrollerLeft' onclick='PVOA.onScrollMonth(-1, " + propertyId + ", \"" + PVOA.makeUnivDate(calStart) + "\", " + numMonths + ")'></div></td><td>";
		} else if(includeScrollers) {
			html += "<div class='PvoaScrollerPlaceholder'></div></td><td>";
		}
		
		for(var i=0; i<monthsHtml.length; i++) {
			if(i % 2 == 0 && i > 0) {
				html += "</td><td>";
			}
			html += monthsHtml[i];
		}
		
		if(includeScrollers) {
			html += "</td><td valign='middle'><div class='PvoaScrollerRight' onclick='PVOA.onScrollMonth(1, " + propertyId + ", \"" + PVOA.makeUnivDate(calStart) + "\", " + numMonths + ")'></div></td>";
		}
		
		html += "</tr></table>";
		
		if(includeLegend) {
			html += "<table class='PvoaLegend' align='center'>";
			for(var key in legend) {
				html += "<tr><td style='background-color:#" + legend[key].Color + "' class='PvoaLegendSymbol'></td>";
				html += "<td>" + htmlToText(legend[key].Name) + " - </td><td>" + PVOA.formatPriceRange(legend[key].MinPrice, legend[key].MaxPrice) + "</td></tr>";
			}
			
			html += "<tr><td class='PvoaLegendSymbol PvoaLegendUnavailable'></td><td colspan='2'>Unavailable/Please enquire</td></tr>";
			
			html += "</table>"
		}

		if(includeWrapper) {
			html += "</div>";
		}

		return html;
	},
	
	parseUnivDate: function(sDate) {
		var matches = sDate.match(/([0-9]+)\-([0-9]+)\-([0-9]+)/);
		return new Date(matches[1], matches[2]-1, matches[3]);
	},
	
	makeUnivDate: function(date) {
		return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
	}
}

htmlToText = function(ch) {
    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;");
	ch = ch.replace(/\n/g,"&nbsp;<br/>");
	return ch;
}

//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, " ");
}

function getUrlParam( 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 urlDecode(results[1]);
}

function getUrlParamNames( ) // 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;
}

function getUrlQuery() {
	return window.location.href.match(/(\?.*)?$/)[0];
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*
    http://www.JSON.org/json2.js
    2009-08-17

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

"use strict";

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());


// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
PVOA.showCalendar = function(id) {
	//make this simple: just use existing joomla/hotproperties feature:
	showCalendar(id);
/*
var el = document.getElementById(id);
 if (calendar != null) {
 // we already have one created, so just update it.
 calendar.hide(); // hide the existing calendar
 calendar.parseDate(el.value, "d/m/yy"); // set it to a new date
 } else {
 // first-time call, create the calendar
 var cal = new Calendar(true, null, selected, PVOA.closeHandler);
 calendar = cal; // remember the calendar in the global
 cal.setRange(2010, 2070); // min/max year allowed
 calendar.create(); // create a popup calendar
 calendar.parseDate(el.value, "d/m/yy"); // set it to a new date
 }
 calendar.sel = el; // inform it about the input field in use
 calendar.showAtElement(el); // show the calendar next to the input field

 // catch mousedown on the document
 Calendar.addEvent(document, "mousedown", PVOA.checkCalendar);
 return false;
*/
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
PVOA.checkCalendar = function(ev) {
	return;
/*
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
 for (; el != null; el = el.parentNode)
 // FIXME: allow end-user to click some link without closing the
 // calendar. Good to see real-time stylesheet change :)
 if (el == calendar.element || el.tagName == "A") break;
 if (el == null) {
 // calls closeHandler which should hide the calendar.
 calendar.callCloseHandler(); Calendar.stopEvent(ev);
 }
 */
} 
 
 
// And this gets called when the end-user clicks on the _selected_ date,
 // or clicks the "Close" (X) button. It just hides the calendar without
// destroying it.
PVOA.closeHandler = function(cal) {
	return;
/*
cal.hide(); // hide the calendar

 // don't check mousedown on document anymore (used to be able to hide the
 // calendar when someone clicks outside it, see the showCalendar function).
 Calendar.removeEvent(document, "mousedown", checkCalendar);
 */
} 
