//alert("Parsed");

//var checkService	= 'http://kaufraum.dyndns.org/eh/exit-checkdates/';
//var bookService		= 'http://kaufraum.dyndns.org/eh/exit-bookdates/';
//var contactService	= 'http://kaufraum.dyndns.org/eh/exit-contact/';
var checkService	= 'http://www.kaufraum.de/eh/exit-checkdates/';
var bookService		= 'http://www.kaufraum.de/eh/exit-bookdates/';
var contactService	= 'http://www.kaufraum.de/eh/exit-contact/';
var map
var showProgress	= true;

function encodeUTF8 (rohtext) {
	rohtext = rohtext.replace(/\r\n/g,"\n");
	var utftext = "";
	for(var n=0; n<rohtext.length; n++) {
		var c=rohtext.charCodeAt(n);
		if (c<128)
			utftext += String.fromCharCode(c);
		else if((c>127) && (c<2048)) {
			utftext += String.fromCharCode((c>>6)|192);
			utftext += String.fromCharCode((c&63)|128);
		} else {
			utftext += String.fromCharCode((c>>12)|224);
			utftext += String.fromCharCode(((c>>6)&63)|128);
			utftext += String.fromCharCode((c&63)|128);
		}
	}
	return utftext;
}
	
function decodeUTF8 (utftext) {
	var plaintext = ""; var i=0; var c=c1=c2=0;
	while (i<utftext.length) {
		c = utftext.charCodeAt(i);
		if (c<128) {
			plaintext += String.fromCharCode(c);
			i++;
		} else if ((c>191) && (c<224)) {
			c2 = utftext.charCodeAt(i+1);
			plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
			i+=2;
		} else {
			c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
			plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
			i+=3;
		}
	}
	return plaintext;
}	

// templates for modal
//
var checkSuccessTmp = "";
checkSuccessTmp += '<h3>Ihre Anfrage war erfolgreich</h3>';
checkSuccessTmp += '<h4>Buchungsdaten</h4>';
checkSuccessTmp += '<table>&rows;</table>';
checkSuccessTmp += '<p><strong>Preis: &price;</strong></p>';
checkSuccessTmp += '<button id="book" value="book" type="button" onclick="return doForm(\'booking\', \'' + bookService + '\', bookSuccess, bookFailure);">Buchung durchführen</button>';
checkSuccessTmp += '<button id="cancel" value="cancel" type="button" onclick="hideModal();">Anfragedaten ändern</button>';

var checkMissTmp = "";
checkMissTmp += '<h3>Ihre Anfrage war nicht erfolgreich</h3>';
checkMissTmp += '<p>Zu dem angegebenen Zeitpunkt ist die Anzahl der von Ihnen gewünschten Zimmer nicht verfügbar.</p>';
checkMissTmp += '<button id="cancel" value="cancel" type="button" onclick="hideModal();">Anfragedaten ändern</button>';

var bookMissTmp = "";
bookMissTmp += '<h3>Ihre Buchung war nicht erfolgreich</h3>';
bookMissTmp += '<p>Versuchen Sie es bitte zu einem späteren Zeitpunkt noch einmal.</p>';
bookMissTmp += '<button id="cancel" value="cancel" type="button" onclick="hideModal();">Anfragedaten ändern</button>';

var bookSuccessTmp = "";
bookSuccessTmp += '<h3>Ihre Buchung war erfolgreich</h3>';
bookSuccessTmp += '<h4>Buchungsdaten</h4>';
bookSuccessTmp += '<table>&rows;</table>';
bookSuccessTmp += '<p>Vielen Dank für Ihre Buchung.</p>';
bookSuccessTmp += '<p>Sie erhalten von uns in Kürze Ihre Buchungsbestätigung.</p>';
bookSuccessTmp += '<button id="cancel" class="successed_book" value="cancel" type="button" onclick="hideModal(); document.location=\'index.html\';">Weiter</button>';

var contactSuccessTmp = "";
contactSuccessTmp += '<h3>Vielen Dank für Ihre Nachricht</h3>';
contactSuccessTmp += '<button id="cancel" value="cancel" type="button" onclick="hideModal(); document.location=\'index.html\';">Weiter</button>';

var failureTmp = "";
failureTmp += '<h3>Verbindungfehler</h3>';
failureTmp += '<p>Versuchen Sie es bitte zu einem späteren Zeitpunkt noch einmal.</p>';
failureTmp += '<button id="cancel" value="cancel" type="button" onclick="hideModal();">Weiter</button>';


function germanDate(str)
{
	var arr = str.split(/\./);
	return new Date(parseFloat(arr[2]), parseFloat(arr[1])-1, parseFloat(arr[0]));
}

function citySuccess(req)
{
	showProgress = true;
	try
	{
		// eval JSON
		//
		eval("o = " + req.responseText);
		
		// fill city suggest popup
		//
		var a = o;
		cityAC.options.array.clear();
		a.postalCodes.each(function(pc) {cityAC.options.array.push(pc.placeName);});

		// if only one city name found for zip and city field still empty - fill it
		//
		if (($F('city') == "") && (a.postalCodes.length == 1))
		{
			$('city').value = a.postalCodes[0].placeName;
		}
	}
	catch(e)
	{
	}
}

function cityFailure(req)
{
	showProgress = true;
	cityAC.options.array.clear();
}

function getCity(plz)
{
	try
	{
		showProgress = false;
		
		var proxyURL	= "proxy.php";
		var url			= escape("http://ws.geonames.org/postalCodeSearchJSON?postalcode=" + plz + "&maxRows=10&style=SHORT&country=DE");	
		var data		= "proxy_url=" + url;
		var req			= new Ajax.Request(proxyURL, {method: 'get', parameters: data, onSuccess: citySuccess, onFailure: cityFailure});		
	}
	catch(e)
	{
		showProgress = true;
	}
}

function proxyRequest(proxyURL, url, params, successfunc, failurefunc)
{
	try
	{
		var data		= "proxy_url=" + url + escape("?" + params);	
		var req			= new Ajax.Request(proxyURL, {method: 'get', parameters: data, onSuccess: successfunc, onFailure: failurefunc});		
	}
	catch(e)
	{
	}
}

function doValidateElem(e)
{
	var val		= $F(e);
	var intval	= parseInt(val);
	
	// validate not empty
	//		
	if(Element.hasClassName(e, 'required') || Element.hasClassName(e.parentNode, 'required') && val=="")
	{
		return false;
	}

	// validate date
	//		
	if(Element.hasClassName(e, 'datefield') && val != "" && !dojo.validate.isValidDate(val, "DD.MM.YYYY"))
	{
		return false;
	}

	// validate email
	//		
	if(Element.hasClassName(e, 'emailfield') && val != "" && !dojo.validate.isEmailAddress($F(e)))
	{
		return false;
	}

	// validate number
	//		
	if(Element.hasClassName(e, 'nrfield') && val != "" && intval < 0 )
	{
		return false;
	}

	// validate postive number
	//		
	if(Element.hasClassName(e, 'posnrfield') && val != "" && intval < 1 )
	{
		return false;
	}
	
	return true;
}

function buildResTable(req, formName, condFunc, successTemplate, missTemplate)
{
	var res = failureTmp;

	try
	{
		eval("o = " + req.responseText);
		
		res = missTemplate;
		
		if (condFunc(o))
		{
			var elems = Form.getElements(formName);
			var rows="";
			
			for (i=0; i<elems.length; i++)
			{
				var e = elems[i];
				if (!Element.hasClassName(e, "noconfirm"))
				{
					var l = e.previousSibling;
					var lt = l.innerHTML;
					var rowTmp ='<tr><td class="fname">&name;</td><td class="fval">&val;</td></tr>';
					rowTmp = rowTmp.replace("&name;", lt);
					rowTmp = rowTmp.replace("&val;", $F(e));
					rows += rowTmp;
				}

			}
			
			res = successTemplate.replace("&rows;", rows);		
			res = res.replace("&price;", o.price.toFixed(2) +"€");
			
		}
	}
	catch (e)
	{	
	}
	
	if(res.search("Ihre Buchung war erfolgreich") != -1) {		
		
		var google_conversion_id = 1046392857;
		var google_conversion_language = "de";
		var google_conversion_format = "1";
		var google_conversion_color = "ffffff";
		var google_conversion_label = "q4pvCMeapgEQmeD68gM";
		
		if (54.0) {
		  var google_conversion_value = 54.0;
		}
		
		res += '<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js"></script>';
		res += '<noscript>';
		res += '<div style="display:inline;">';
		res += '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1046392857/?value=54.0&amp;label=q4pvCMeapgEQmeD68gM&amp;guid=ON&amp;script=0"/>';
		res += '</div>';
		res += '</noscript>';
		res += '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1046392857/?value=54.0&amp;label=q4pvCMeapgEQmeD68gM&amp;guid=ON&amp;script=0"/>';
		
		//alert(res);
	}
	
	return res;
}

function showModal(content)
{
	if ($('modalContent'))
		Element.remove($('modalContent'));

	content = '<div id="modalContent"><div class="bookResult">' + content + '</div></div>';
	
	new Insertion.Bottom('modal', content);
	layerOn('modal', 1.0, 1.0,'#fff');
}


function hideModal()
{
	layerOff('modal', 1.0);
}

// Ajax callbacks and condition funcs for check, book, contact
//
function checkSuccess(req)
{
	var res = buildResTable(req, 'booking', checkCond, checkSuccessTmp, checkMissTmp)
	showModal(res);	
}

function checkFailure(req)
{
	showModal(failureTmp);	
}

function checkCond(o)
{
	return o.result && o.price > 0;
}

function bookSuccess(req)
{
	var res = buildResTable(req, 'booking', bookCond, bookSuccessTmp, bookMissTmp)
	showModal(res);	
}

function bookFailure(req)
{
	showModal(failureTmp);	
}

function bookCond(o)
{
	return o.result;
}


function contactSuccess(req)
{
	showModal(contactSuccessTmp);	
}

function contactFailure(req)
{
	showModal(failureTmp);	
}


function errorElement(e)
{
	Element.addClassName(e, 'error');
	new Effect.Shake(e);
}

function doForm(formName, action, successfunc, failurefunc)
{
	try
	{
		var success = true;
		var elems = Form.getElements(formName);
		var errElem = null;
		
		// do basic validation for each field according to type
		//
		for (i=0; i<elems.length; i++)
		{
			var e = elems[i];
			Element.removeClassName(e, 'error');
	
			if(!doValidateElem(e))
			{
				errorElement(e);
				if (success)
					errElem = e;
				
				success = false;
			}	
		}
		
		// do booking date validation
		//
		if ($('nrsingle'))
		{
			if ((parseInt($F('nrsingle')) == 0) && (parseInt($F('nrdouble')) == 0))
			{
				errorElement($('nrsingle'));
				errorElement($('nrdouble'));

				if (success)
					errElem = $('nrsingle');
				
				success = false;
			}

			var nowDate			= new Date();
			nowDate.setHours(0);										
			nowDate.setMinutes(0);										
			nowDate.setSeconds(0);										
			nowDate.setMilliseconds(0);										
				
			var nowTime			= nowDate.getTime();
			var arrivalTime		= germanDate($F('arrival')).getTime();
			var departureTime	= germanDate($F('departure')).getTime();
									
									
			if (arrivalTime < nowTime || arrivalTime >= departureTime)
			{
				errorElement($('arrival'));
				errorElement($('departure'));

				if (success)
					errElem = $('arrival');
				
				success = false;
			}
		}
		
		if (success)
		{
			var url		= action;
			var data	= Form.serialize(formName);
			//var req		= new Ajax.Request(url, {method: 'get', parameters: data, onSuccess: successfunc, onFailure: failurefunc});		

			proxyRequest("proxy.php", action, data, successfunc, failurefunc);
		}
		else
		{
			Field.activate(errElem);
		}
	}
	catch(e)
	{
		alert(e);
	}
	
	return false;
}


function pickerChanged()
{
	// date picker callback if date selected by user
	//
	var datepicker = dojo.widget.byId("datepicker");
	var date = datepicker.storedDate;
		
	// fill attached input field with picker value
	//
	$(datepicker.attElement).value = date;
	
	// dispose picker and hide layer
	//
	destroyPicker();
	progressOff(0.5);
}

function layerOn(layer, duration, opacity, color)
{
	var pr	= $(layer);

	if (color)
		pr.style.backgroundColor = color;

	// fake "position:fixed;"
	//
	var deltaX =  window.pageXOffset
	            || document.documentElement.scrollLeft
	            || document.body.scrollLeft
	            || 0;
	var deltaY =  window.pageYOffset
	            || document.documentElement.scrollTop
	            || document.body.scrollTop
	            || 0;
	 
	pr.style.left = deltaX + "px";
	pr.style.top = deltaY + "px";
	
	new Effect.Fade('content_r', {duration: duration});	
	new Effect.Appear(layer, {duration: duration, from: 0, to:opacity, queue: {position: 'end', scope: layer, limit: 2}});
}

function layerOff(layer, duration)
{
	new Effect.Fade(layer, {duration: duration, from: 0.5, to:0, queue: {position: 'end', scope: layer, limit: 2}});
	new Effect.Appear('content_r', {duration: duration});	
}

function progressOn(duration, opacity, color)
{
	if(showProgress)
		layerOn('progress', duration, opacity, color);
}

function progressOff(duration)
{
	layerOff('progress', duration);
}


function createPicker(element)
{
	// insert picker container
	//
	new Insertion.Bottom('progress','<div id="pickerstyle"><table height=100% align="center"><tr><td id="picktd" style="vertical-align:middle"><div id="picker"></td></tr></table></div>');

	// insert picker itself
	//
	var datepicker = dojo.widget.createWidget("datepicker", {"id" : "datepicker", "preventClobber" : false }, $('picker'));

	// bind callback
	//
	dojo.event.connect(datepicker, "setDate", pickerChanged);

	// set attached form field
	//
	datepicker.attElement = element;
	
	Element.hide($('booking'));  
}

function destroyPicker()
{
	dojo.widget.byId("datepicker").destroy();
	Element.remove($('pickerstyle'));
	Element.show($('booking'));  
}

function registerRules()
{
	// rules for all pages
	//
	var generalRules = {
	/*
		// set content invisible
		//
		'#content_r': function(element) {
			Element.setOpacity(element, 0);
		},
	*/
		// general form field rules
		//
		'form input': function(element) {
			element.onfocus = function() {
				Element.addClassName(this, 'focus');
			};
			element.onchange = function() {
				Element.removeClassName(this, 'error');
			};
			element.onblur = function() {
				Element.removeClassName(this, 'focus');
				Element.removeClassName(this, 'error');
			};
		},
		
		'form textarea': function(element) {
			element.onfocus = function() {
				Element.addClassName(this, 'focus');
			};
			element.onchange = function() {
				Element.removeClassName(this, 'error');
			};
			element.onblur = function() {
				Element.removeClassName(this, 'focus');
				Element.removeClassName(this, 'error');
			};
		},
	
		// date field rule
		//
		'img.date': function(element) {
			element.onclick = function() {
				createPicker($(element.id.substr(1)));
				progressOn(0.5,0.8, '#fff');
			};
		},
		
		// flash main navi rule
		//
		'ul#navigation li a': function(element) {
			element.onclick = function() {
				new Effect.Highlight(this, {startcolor:'#ffffff', endcolor:'#ba0303'});
			};
		},
		
		// current nav item rule
		//
		'ul#navigation li a': function(element) {
			if (element.href == document.location)
			{
				element.id = "current";
			}
		}
	};
	
	Behaviour.register(generalRules);
	
	// rules for reservierung
	//
	var bookingRules = {
		// zip field rule
		//

		'form input#zip': function(element) {
			element.onblur = function() {
				Element.removeClassName(this, 'focus');
				Element.removeClassName(this, 'error');
				return getCity($F(element));
			};
	    },
	
	 	// booking form rule
		//	      
		'form#booking': function(element) {
			element.onsubmit = function() {return doForm('booking', checkService, checkSuccess, checkFailure);};
	    }

	};
	
	if ($('booking'))
	{
		//replaceIESelect("title");

		Behaviour.register(bookingRules);
	}

	// rules for kontakt
	//
	var contactRules = {	
	 	// contact form rule
		//	      
		'form#contact': function(element) {
			element.onsubmit = function() {return doForm('contact', contactService, contactSuccess, contactFailure);};
	    }
	};
	
	if ($('contact'))
	{
		Behaviour.register(contactRules);
		}
	
	// rules for anreise
	//
	var locRules = {	
	 	// contact form rule
		//	      
		'#schnelsen': function(element) {
			element.onclick = function() {map.panTo(posSchnelsen, 13);};},
		'#showPos': function(element) {
			element.onclick = function() {alert (map.getCenter());};
	    }
	};
	
	if ($('schnelsen'))
	{
		Behaviour.register(locRules);
		}
	
	Behaviour.apply();
}


Behaviour.addLoadEvent (
function()
{
	registerRules();

	// fade in content
	//
    //Element.setOpacity('content_r', 0);
	//new Effect.Appear('content_r');
	
	var globalAjaxHandlers = {
	  onCreate:		function() { progressOn(0.5, 0.5, '#000'); },
	  onComplete:	function() { progressOff(0.5); },
	  onException:	function(req, e) { alert(e); progressOff(0.5);}
	};
	
	Ajax.Responders.register(globalAjaxHandlers);
	
	new Insertion.Bottom('container','<div id="progress" class="posfixed" style="top:0; left:0; display:none;"></div>');
	new Insertion.Bottom('container','<div id="modal" class="posfixed" style="top:0; left:0; display:none;"></div>');

	// autocompletion for city in booking form
	//
	if ($('city'))
	{
		cityAC = new Autocompleter.Local('city', 'city_list', [''], {});
	}
	
	// google map on anreise page
	//
	if($('map'))
	{
		// positions for google map
		//
		posHotel		= new GLatLng(53.6631, 10.0009);
		posSchnelsen	= new GLatLng(53.6452, 9.9291);
		posHbf			= new GLatLng(53.5523, 10.0048);

		if (GBrowserIsCompatible())
		{
        	map = new GMap2(document.getElementById("map"));
        	map.setCenter(new GLatLng(53.6, 10.01), 13);
        	map.addControl(new GMapTypeControl());
        	map.addControl(new GSmallZoomControl());
        	
			Event.observe(window, 'unload', GUnload, false);
        }
	}
}
);

dojo.require("dojo.widget.html.DatePicker");
dojo.require("dojo.widget.DropdownDatePicker");
dojo.require("dojo.validate.datetime");
dojo.require("dojo.validate.web");

dojo.date.months = ["Januar", "Februar", "März", "April", "Mai", "Juni",
	"Juli", "August", "September", "Oktober", "November", "Dezember"];
dojo.date.shortMonths = ["Jan", "Feb", "Mär", "Apr", "Mai", "Juni",
	"Juli", "Aug", "Sep", "Okt", "Nov", "Dez"];
dojo.date.days = ["Sonntag", "Montag", "Dienstag", "Mittwoch",
	"Donnerstag", "Freitag", "Samstag"];
dojo.date.shortDays = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
 
