﻿function __doPostBack(eventTarget, eventArgument, theform) {
    if(!theform) {
	var theform = document.cb;
    }
    theform.__EVENTTARGET.value = eventTarget;
    theform.__EVENTARGUMENT.value = eventArgument;
    theform.submit();
}

function setCBValues(eventTarget, eventArgument, theform) {
    if(!theform) {
	var theform = document.cb;
    }
    theform.__EVENTTARGET.value = eventTarget;
    theform.__EVENTARGUMENT.value = eventArgument;
}

function ShowRoom(id, propid)
{
  var s = "window.open('http://online.citybreak.com/Accommodation/Room/Index.aspx?onlineid=1178623113&propertyid={1}&roomid={0}', 'roominfo', 'width=338, height=500, toolbar=no, top=' + (screen.availHeight - 400) / 2 + ', left=' + (screen.availWidth - 400) / 2 + ', screenX=' + (screen.availWidth - 400) / 2 + ', screenY=' + (screen.availHeight - 400) / 2);";

  s = s.replace(/\{0\}/g, id.toString());
  s = s.replace(/\{1\}/g, propid.toString());
  eval(s);
}


function testReplace(id)
{
    var myElem = document.getElementById(id);

    if(!myElem) {
	alert('Didnt get any element from id: ' + id);
    }
    else {
	myElem.innerHTML = "Hej";
    }
}

function formData2QueryString(docForm)
{
    var strSubmit       = '';
    var formElem;
    var strLastElemName = '';

    for (i = 0; i < docForm.elements.length; i++) {
	formElem = docForm.elements[i];
	switch (formElem.type) {
	    // Text, select, hidden, password, textarea elements
	case 'text':
	case 'select-one':
	case 'hidden':
	case 'password':
	case 'textarea':
	    strSubmit += formElem.name +
		'=' + escape(formElem.value) + '&'
		break;
	}
    }

    return strSubmit;
}

function makeRequest0(url, submit, id) {
    var http_request = false;

    waitLoading(id);

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
	    http_request.overrideMimeType('text/xml');
	    // See note below about this line
	}
    } else if (window.ActiveXObject) { // IE
	try {
	    http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	    try {
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch (e) {}
	}
    }

    if (!http_request) {
	alert('Something went wrong.  Try again\n( Cannot create an XMLHTTP instance');
	return false;
    }
    http_request.open('POST', url, true);
    http_request.setRequestHeader('Content-Type',
				  'application/x-www-form-urlencoded');
    http_request.onreadystatechange = function() {
	try
	{
	    if (http_request.readyState == 4) {
		if (http_request.status == 200) {
		    drawResult(http_request,id);
		}
		else {
		    alert('Something went wrong.  Try again\nhttp_request.status != 200, is: ' +
			  http_request.status);
		}
	    }
	}
	catch(e)
	{
	    alert('Something went wrong.  Try again\nException: ' +
		  e.description);
	}
    };
    http_request.send(submit);
}

function makeRequest(url, formName, id) {
    var submit = formData2QueryString(document.forms[formName]);
    makeRequest0(url, submit, id);
}

function waitLoading(id)
{
    var div = document.getElementById(id);
    div.innerHTML = '<p class="center"><img src="/img/loading_small.gif"/></p>';
}

function drawResult(http_request, id)
{
    var div = document.getElementById(id);
    // should sort out xml-declaration
    div.innerHTML = http_request.responseText;
}

function formDataDump(docForm)
{
    var strSubmit       = '';
    var formElem;
    var strLastElemName = '';

    for (i = 0; i < docForm.elements.length; i++) {
	formElem = docForm.elements[i];
	switch (formElem.type) {
	    // Text, select, hidden, password, textarea elements
	case 'text':
	case 'select-one':
	case 'hidden':
	case 'password':
	case 'textarea':
	    strSubmit += formElem.name +
		'=' + escape(formElem.value) + '\n'
		break;
	}
    }

    return strSubmit;
}

function checkChildAges(form)
{
    var docForm = document.forms[form];

    var formElem;
    var maStr;
    var accept = true;
    var reSel = /^ctrlRoomConfig:rpRooms:ctl(.*):rpAgeOfChild.*/;

    for (i = 0; i < docForm.elements.length; i++) {
	formElem = docForm.elements[i];
	if( reSel.exec(formElem.name) ) {
	    if( !formElem.value ) {
		accept = false;
		alert('Ange ålder på alla barn.');
	    }
	}
    }

    // check arrival and departure
    var arr;
    if( docForm.arrival )
	arr = docForm.arrival.value;
    else
	arr = docForm.arrival2.value;
    var dep;
    if( docForm.departure )
	dep = docForm.departure.value;
    else
	dep = docForm.departure2.value;
	
    var arrPart = arr.split('-');
    var depPart = dep.split('-');
    var arrival = new Date(arrPart[0], arrPart[1]-1, arrPart[2], 23, 59, 59);
    var departure = new Date(depPart[0], depPart[1]-1, depPart[2]);

    //alert('Arrival: '+arrival+'\ndeparture: '+departure+'\ndiff: '+(departure - arrival)/86400000);

    var now = new Date();
    if(arrival < now) {
	alert("Ankomst kan inte vara före i dag.");
        accept = false;
    }
    else if(departure < arrival) {
        alert("Ankomst måste vara före avresa.");
        accept = false;
    }
    else if((departure - arrival)/86400000 > 32) {
        alert("Du kan inte boka mer än 32 dagar i taget.\n"+
	      "Vill du boka mer, vänligen kontakta vår Booking Center på telefon 0752-40 10 10 / 031-751 86 25.");
        accept = false;
    }

    return accept;
}

function catcalc(cal, arrival, departure) {
    var date = cal.date;
    var time = date.getTime();
    // use the _other_ field
    var field = document.getElementById(departure);
    if (field == cal.params.inputField) {
	field = document.getElementById(arrival);
	if ( date.print("%Y-%m-%d") < field.value ||
	     field.value == "yyyy-mm-dd" )
	    {
		time -= Date.DAY;
		var date2 = new Date(time);
		field.value = date2.print("%Y-%m-%d");
	    }
    } else {
	if ( date.print("%Y-%m-%d") > field.value ||
	     field.value == "yyyy-mm-dd" )
	    {
		time += Date.DAY;
		var date2 = new Date(time);
		field.value = date2.print("%Y-%m-%d");
	    }
    }
    cal.hide();
    return true;
}

function gEI()
{
    var elems=new Array();
    for(var i=0;i<arguments.length;i++){
	var args=arguments[i];
	if(typeof args=="string"){
	    args=document.getElementById(args);
	}
	if(arguments.length==1){
	    return args;
	}
	elems.push(args);
    }
    return elems;
}

function searchboxClick()
{
    var qs = gEI("search_quick");
    if(!qs.beenclicked) {
	qs.beenclicked=true;
	qs.value="";
	qs.style.color="black";
    }
}


function updateGeoSelects(select, form) {
    var geo_ind = Number(select.name.split('_')[2]);
    var option = select.options[select.selectedIndex];
    var eol = option.attributes.endofline;
    var value = option.value;
    var myP = $('geo_ind_'+ geo_ind);

    // if someone backed up.... 
    $(form).run.value='';

    // clear any selects below
    for( var i=geo_ind + 1; i<=3; i++) {
	var elem = $('geo_ind_'+i);
	if( elem ) {
	    Effect.BlindUp(elem, { duration: 0.3,
			afterFinish: function(effect){ Element.remove(effect.element) }});
	}
    }
    if( !eol ) {
	$(form).geo_ind.value = geo_ind + 1;
	params = $(form).serialize();
	var loading = Builder.node('img', {
		style: 'display: none; position: absolute; top: 45%; left: 45%; z-index: 10',
		src: '/img/loading_large.gif' });
	$('geo_selects').appendChild(loading);
	Effect.Appear(loading, { duration: 0.5 });
	new Ajax.Request('/clean/cb_geo_selects.tt',
			 { parameters: params,
				 onComplete: function(transport)
				 {
				     Effect.Fade(loading, { duration: 0.4 });
				     myP.insert({ after: transport.responseText });
				     Effect.BlindDown('geo_ind_' + (geo_ind + 1), { duration: 0.3 });
				 }
			 });
    }
}

function frmLoad(frame, loading)
{
    $(loading).style.display = 'none';
    frame.style.display = 'block';
}


var RoomSelect = Class.create({
        initialize: function(noRooms, rooms)
	{
	    this.noRooms = noRooms;
	    this.rooms = rooms;
	},

	draw: function(divid)
	{
	    this.div = $(divid);

	    for(var i=0; i<this.noRooms; i++) {
		this.div.appendChild(this.oneRoomP(i));
	    }
	},

	redraw: function()
	{
	    // Clean up
	    while( this.div.firstChild ) {
		this.div.removeChild( this.div.firstChild );
	    }
	    this.draw(this.div);
	},

	oneRoomP: function(roomNr, hidden)
	{
	    var room = Builder.node('p');

	    if( hidden ) {
		room.style.display = 'none';
	    }

	    room.appendChild(Builder.node('label', 'Rum '+(roomNr+1)));
	    room.appendChild(Builder.node('br'));

	    var childSel = Builder.node('select', {
		    name: 'room_'+roomNr+'_children',
		    style: 'width: 48%; float: right;'});
	    Event.observe(childSel, 'change', this.updateChildSel.bind(this, roomNr, childSel));
            room.appendChild(childSel);

	    var children = 
	    
	      childSel.appendChild(Builder.node('option', { value: 0 },
						'0 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 1 },
						'1 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 2 },
						'2 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 3 },
						'3 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 4 },
						'4 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 5 },
						'5 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 6 },
						'6 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 7 },
						'7 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 8 },
						'8 barn'));
	    
	      childSel.appendChild(Builder.node('option', { value: 9 },
						'9 barn'));
	    
	    if( !this.rooms[roomNr].noChildren ) {
		this.rooms[roomNr].noChildren = 0;
	    }
	    childSel.value = this.rooms[roomNr].noChildren;

	    var adults = Builder.node('select', {
		    name: 'room_'+roomNr+'_adults',
		    style: 'width: 48%' });
            room.appendChild(adults);

	    
	      adults.appendChild(Builder.node('option', { value: 1 },
	                                      '1 vuxen'));
	    
	      adults.appendChild(Builder.node('option', { value: 2 },
	                                      '2 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 3 },
	                                      '3 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 4 },
	                                      '4 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 5 },
	                                      '5 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 6 },
	                                      '6 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 7 },
	                                      '7 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 8 },
	                                      '8 vuxna'));
	    
	      adults.appendChild(Builder.node('option', { value: 9 },
	                                      '9 vuxna'));
	    
	    if( !this.rooms[roomNr].noAdults ) {
		this.rooms[roomNr].noAdults = 1;
	    }
	    adults.value = this.rooms[roomNr].noAdults;

	    for(var i=0; i<this.rooms[roomNr].noChildren; i++) {
		if( !this.rooms[roomNr].children ) {
		    this.rooms[roomNr].children = new Array();
		}
		room.appendChild(this.oneChildSpan(roomNr, i));
	    }

	    return room;
	},

	oneChildSpan: function(roomNr, childNr, hidden)
	{
	    var childSpan = Builder.node('span', { id: 'room_'+ roomNr +'_child_'+ childNr });

	    if( hidden ) {
		childSpan.style.display = 'none';
	    }

	    childSpan.appendChild(Builder.node('br', { style: 'clear: both;' }));

	    var ageOfChild = Builder.node('select', {
		    name: 'room_'+roomNr+'_child_'+childNr+'_age',
		    style: 'width: 48%; float: right;' });
	    Event.observe(ageOfChild, 'change', this.updateChildAge.bind(this, roomNr, childNr, ageOfChild));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 0 },
						  '0 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 1 },
						  '1 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 2 },
						  '2 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 3 },
						  '3 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 4 },
						  '4 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 5 },
						  '5 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 6 },
						  '6 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 7 },
						  '7 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 8 },
						  '8 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 9 },
						  '9 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 10 },
						  '10 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 11 },
						  '11 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 12 },
						  '12 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 13 },
						  '13 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 14 },
						  '14 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 15 },
						  '15 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 16 },
						  '16 år'));
	    
	      ageOfChild.appendChild(Builder.node('option', { value: 17 },
						  '17 år'));
	    
	    if( !this.rooms[roomNr].children[childNr] ) {
		this.rooms[roomNr].children[childNr] = 1;
	    }
	    ageOfChild.value = this.rooms[roomNr].children[childNr];
	    childSpan.appendChild(ageOfChild);
	    childSpan.appendChild(Builder.node('label', { style: 'width: 48%' },
					       'Ålder barn '+ (childNr+1)));
	    return childSpan;
	},

	updateRooms: function(newRooms)
	{
	    newRooms = Number(newRooms);
	    if( newRooms > this.noRooms ) {
		for(var i=this.noRooms; i<newRooms; i++) {
		    if( !this.rooms[i] ) {
			this.rooms[i] = new Hash();
		    }
		    newP = this.oneRoomP(i, true);
		    this.div.appendChild(newP);
		    Effect.BlindDown(newP, { duration: 0.3 });	      
		}
	    }
	    else { // less...
		for(var i=newRooms; i<this.noRooms; i++) {
		    Effect.BlindUp(this.div.childNodes[i], { duration: 0.3,
							     afterFinish: function(effect){ Element.remove(effect.element) }});
		}
	    }
	    this.noRooms = newRooms;
	},

	updateChildSel: function(roomNr, select)
	{
	    var newChildren = Number(select.value);

	    if( newChildren > this.rooms[roomNr].noChildren ) {
		for(var i=this.rooms[roomNr].noChildren; i<newChildren; i++) {
		    if( !this.rooms[roomNr].children ) {
			this.rooms[roomNr].children = new Array();
		    }
		    newSpan = this.oneChildSpan(roomNr, i, true);
		    this.div.childNodes[roomNr].appendChild(newSpan);
		    Effect.BlindDown(newSpan, { duration: 0.3 });	      
		}
	    }
	    else { // less...
		for(var i=newChildren; i<this.rooms[roomNr].noChildren; i++) {
		    Effect.BlindUp($('room_'+ roomNr +'_child_'+ i), { duration: 0.3,
									afterFinish: function(effect){ Element.remove(effect.element) }});
		}
	    }
	    this.rooms[roomNr].noChildren = newChildren;
	},

	updateChildAge: function(roomNr, childNr, select)
	{
	    this.rooms[roomNr].children[childNr] = select.value;
	}
    });



// Rit::Guides::AJAX helpers

////////// UNFINISHED!
function blindUpdater(id, url, args_in) {
    var args = $H(args_in).merge({
	    onComplete: function(transport)
	    {
		Effect.BlindUp(id, { duration: 0.5 });
		$(id).innerHTML = transport.responseText;
		Effect.BlindDown(id, { duration: 0.6 });
	    }});
    new Ajax.Request(id, url, args);
}

function switchDivs(id)
{
    hidden = $(id + '-hid');
    shown  = $(id + '-shown');
    Event.observe(id + '-shown', 'click', function () {
	    Effect.Shrink(id + '-shown', { duration: 0.5 });
	    Effect.Grow(id + '-hid', { duration: 0.5, delay: 0.4 })
		});
}

function insertFormPart(form, part, clickable, after, new_id, parameters)
{
    Event.observe(clickable, 'click', function() {
	    $(after).insert({ after: Builder.node('img', {
			    id: new_id +'-loading',
				style: 'display: none; position: fixed; top: 45%; left: 45%;',
				src: '/img/loading_large.gif'
				}, '') });
	    Effect.Appear(new_id +'-loading', { duration: 0.5 });
	    new Ajax.Request('/rb/ajax/form/'+ form +'/'+ part +'.html', {
		    method: 'get',
			parameters: { data: parameters, in_ajax_insert: 'true' },
			onComplete: function(transport)
			{
			    Effect.Fade(new_id +'-loading', { duration: 0.5 });
			    $(after).insert({ after: transport.responseText });
			    new_id = $(after).next();
			    prepareForm();
			    Effect.Grow(new_id, { delay: 0.5, duration: 0.5 });
			}
	    })
	});
}

function set_date(delta)
{
      db = new Date();
      db.setHours(9);
      db.setMinutes(0);
      db.setSeconds(0);
      db.setMilliseconds(0)

      time = db.getTime();
      delta = delta || 0;
      time += delta * 24 * 60 * 60 * 1000;
      d = new Date();
      d.setTime(time);

      year =  d.getYear();
      if( year < 1901 )
      {
        year += 1900;
      }
      month = d.getMonth() + 1;
      day   = d.getDate();
      hour  = d.getHours();
      minute  = d.getMinutes();

      dstr = year + '-';
      dstr += ((month < 10) ? "0" : "") + month + '-';
      dstr += ((day < 10) ? "0" : "") + day + ' ';
      dstr += ((hour < 10) ? "0" : "") + hour + '.';
      dstr += ((minute < 10) ? "0" : "") + minute;

      return( dstr );
}