  // Object to control search form
  // Requires dhtmlutils.js

  /**
   * This class controls the search forms
   * Functionality:
   * 1)	Check dates for validity
   * 2) Create Hotel rooms and occupancy. NOTE: the object initOccupancy can be set during initialization with a the corresponding session variable jsOcupancy
   * 3) Creates child age selector
   * 4) Gets destination information via HttpRequest and populates teh correct selectbox
   * 
   * NOTE: initial country, zone and town can be set in the constructor
   * 
 * @param opts object {x:y}
 * @return
 */
function searchForm(opts){
	  
	  Object.extend(this, new baseOptions());
	  
	  this.arTxt = {};
	  this.lang = "en";
	  this.objName = "searchForm";
	  this.autocompleteURL = "/autocomplete.php";
	  this.selType = "accommType";
	  this.inputDateFrom = "aYearCal";
	  this.inputDateTo = "dYearCal";
	  
	  this.selArrDay = "aDay";
	  this.selArrYear = "aYear";
	  this.selDepDay = "dDay";
	  this.selDepYear = "dYear";
	  
	  this.formNameId = "frmSearch";
	  
	  // Initial Locatio info
	  this.initDest = "";
	  this.initCou  = "";
	  this.initReg	= "";
	  this.initTown	= "";
	  
	  // Geo Fields
	  this.selDestAuto= "fldDest";
	  this.selCountry = "fldCountry";
	  this.selDest	  = "fldZona";
	  this.selCityDistrict = "fldDestiny";
	  
	  // occupation fields
	  this.selAdultBase = "nAdult";
	  this.selChildBase = "nChild";
	  this.selRooms = "numRooms";
	  this.roomCounter= "roomcounter";
	  this.divRoomContainer = "divRooms";
	  this.divRoomClass = "form-room";
	  this.divRoomBase = "div-room-";
	  this.selClass = "fld w3";
	  this.selMultiFix = "add";
	  this.numRooms = 0;
	  
	  // element containers
	  this.divApt = "divRoomsAp";
	  this.divHotel = "divRoomsHo";
	  this.diChildAge = "divChildAge";
	  
	  // This is the format for the initial number of rooms / adults / children / Ages
	  this.initOccupancy = {
			  "rooms":[
			           {"adults":"2","children":"0","ages":[2]}
			          ]
	  };
	  
	  this.setOpts(opts, this);
	  
	  this.getType = function(frm){
		  this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		  
		  var el =$("#"+this.formNameId).find('[name='+this.selType+']'); 
		  
		  if($(el).attr('type') == 'hidden'){
			  return $(el).val();  
		  }else{
			  return $("#"+this.formNameId).find('[name='+this.selType+']:checked').val();   
		  }
		  
	  };
	  
	  this.setInitOccupancy = function (obj){
		  if(obj != null && obj != ''){
			  this.initOccupancy = obj;  
		  }
	  };
	  
	  this.getPrice = function (){
		  
	  };
	  
	  this.checkDates = function(frm){
		  
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		var from = $("#"+this.formNameId).find('[name='+this.inputDateFrom+']').val();
		var to = $("#"+this.formNameId).find('[name='+this.inputDateTo+']').val();
//		alert(this.formNameId + " => "+this.inputDateFrom+" = " +from +  "  : "+to);
		// Check dates
		  if($("#"+this.formNameId).find('[name='+this.inputDateFrom+']').val() && 
				  $("#"+this.formNameId).find('[name='+this.inputDateTo+']').val()
			){
			  var arDateFrom = $("#"+this.formNameId).find('[name='+this.inputDateFrom+']').val().split('/'); 
			  var arDateTo = $("#"+this.formNameId).find('[name='+this.inputDateTo+']').val().split('/');
			  
			  // Check that the date format is correct
			  if(arDateFrom.length != 3 || arDateTo.length != 3){
				alert(this.arTxt['error dates']);  
				$("#"+this.formNameId).find('[name='+this.inputDateFrom+']').focus();
				return false;
			  }
		  }else{
			  alert(this.arTxt['error dates']);  
			  $("#"+this.formNameId).find('[name='+this.inputDateFrom+']').focus();
				return false;  
		  }
		  
		  var dateCheck = new Date();
		  var dateFrom = new Date(arDateFrom[2],parseInt(arDateFrom[1],10) - 1 ,parseInt(arDateFrom[0],10));
		  var dateTo = new Date(arDateTo[2],parseInt(arDateTo[1],10) - 1,parseInt(arDateTo[0],10));
		  // Case arrival before departure
		  if(dateFrom >= dateTo){
			alert(this.arTxt['error dates']);  
			$("#"+this.formNameId).find('[name='+this.inputDateFrom+']').focus();
			return false;
		  }
		  
		  return true;
	  };
	  
	  this.doFormSubmit = function(){
//		  alert("Checking Dates2");
		  var isValidDates= this.checkDates();
		  if(!isValidDates){return false;}
		  
		  // Check for destination
		  if($('#'+this.selCountry).val() == '' || $('#'+this.selDest).val() == ''){
			alert(this.arTxt['error destination']); 
			$('#'+this.inputDateFrom).focus();
			return false;
		  }
		  
		  // if ok then submit
		  $('#'+this.formNameId).submit();
		  return true;
	  };
	  
	  // Select Form Type
	  this.changeFormType = function(frm){
		var type = this.getType(frm);
		
		// Reset Autocomplete field
//		$("#"+this.selDestAuto).val('');
		
		if(type == 'hotel' || type == 'HotelFCB' || type == null){
			$('#'+this.divApt).hide();
			$('#'+this.divHotel).show();
		}else{
			$('#'+this.divApt).show();
			$('#'+this.divHotel).hide();
		}
//		alert("ChangeFormType");
//		this.drawCountries();
//		this.doDrawDestination();
//		this.drawRoomsInit();
		
	  };
	  
	  // Set Initial Values
	  this.doDrawDestination = function (){
			$('#'+this.selCountry).val(this.initCou);
			$('#'+this.selCountry).change();
			
			$('#'+this.selDest).val(this.initReg);
			$('#'+this.selDest).change();
			
			$('#'+this.selCityDistrict).val(this.initTown);
			
		};
	  
	  // Popualate Select
		this.doPopulateSelect = function (el,data,fldCode, fldDescr,txt){
			var domEl = $("#"+el).get(0);
			domEl.options.length	= 0;	
			domEl.options[domEl.options.length]	= new Option(txt,'');	
			if(data && data != null && data != ''){
				$(data).each(function () {
					var val = $(this).attr(fldCode);
					var text = $(this).attr(fldDescr);
					domEl.options[domEl.options.length]	= new Option(text,val);			
				});
			}
		};
		
	  // Draw Country Select
	  this.drawCountries = function (){ 	  	
		 var fldCountry = document.getElementById(this.selCountry); 	 
		 var httpRequest = new HTTPRequest();  	       
		 var xmlDocument = httpRequest.doSyncGet(this.autocompleteURL,'fldType=countries&fldLang='+this.lang+'&fldWhat='+this.getType()); 	  
		 var fldZona = document.getElementById("fldZona"); 
		 var fldDestiny = document.getElementById("fldDestiny");
		 
		 var data = $(xmlDocument).find("item"); 
		 this.doPopulateSelect("fldZona", false, 'code', 'descrip',this.arTxt['select region']);
		 this.doPopulateSelect("fldDestiny", null, 'code', 'descrip',this.arTxt['select town']);
		 this.doPopulateSelect("fldCountry", data, 'code', 'descrip',this.arTxt['select country']);
		 
//		 updateSelectFromDocument(null,fldZona,'- Zones -')
//		 updateSelectFromDocument(null,fldDestiny,'- Destiny -');                                                                                    
//		 updateSelectFromDocument(xmlDocument,fldCountry,'- Countries -');
		};
		
	  //Draw Regions select
	  this.drawZones = function (){
		 var fldCountry = document.getElementById("fldCountry"); 	  	  
		 var fldZona = document.getElementById("fldZona"); 	   
		 var httpRequest = new HTTPRequest();        	  
		 var xmlDocument = httpRequest.doSyncGet(this.autocompleteURL,'fldType=zone&fldCountry='+
				 								 $('#fldCountry').val()+'&fldLang='+this.lang+'&fldWhat='+this.getType()
				 								); 	  
		 
		 var data = $(xmlDocument).find("item"); 
		 this.doPopulateSelect("fldZona", data, 'code', 'descrip',this.arTxt['select region']);
		 this.doPopulateSelect("fldDestiny", null, 'code', 'descrip',this.arTxt['select town']);
//		fldZona.disabled=false;	     
//		updateSelectFromDocument(xmlDocument,fldZona,'- Zones -');                                                                                    
	  };
	  
	  // Draw Towns
	  this.drawTowns = function (){
	 	  var fldCountry = document.getElementById("fldCountry"); 	 
	 	  var fldZona = document.getElementById("fldZona");  	  
	 	  var fldDestiny = document.getElementById("fldDestiny"); 
	 	  
	 	  var httpRequest = new HTTPRequest();     	 
	      var xmlDocument = httpRequest.doSyncGet(this.autocompleteURL,'fldType=destiny&fldCountry='+
	    										$('#fldCountry').val()+'&fldLang='+this.lang+'&fldWhat='+this.getType()+
	    										'&fldDest='+$('#fldZona').val()
	    										); 	  
	      
	      var data = $(xmlDocument).find("item"); 
		  this.doPopulateSelect("fldDestiny", data, 'code', 'descrip',this.arTxt['select town']);
//	    fldDestiny.disabled=false;
//	    updateSelectFromDocument(xmlDocument,fldDestiny,'- Destiny -');                                                                                    
	  }; 
	  
	  this.drawRoomsInit = function(multiFix,frm){
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		multiFix = (multiFix == undefined || multiFix == false || multiFix == '') ? "" : this.selMultiFix;
		
		$('form[name='+this.selAdultBase+']').val(this.initOccupancy['rooms'][0]['adults']);
		$('form[name='+this.selChildBase+']').val(this.initOccupancy['rooms'][0]['children']);
		
//		if(this.getType() != 'apartment'){
//		if(this.getType() == 'hotel' || this.getType() == 'HotelPA'){
		if(true){
//			this.removeRoom();
			if(this.initOccupancy['rooms'].length == 1){
				this.numRooms = 0;
				$('#'+this.formNameId).find('[name='+this.roomCounter+']').val(0);
//				alert(frm);
				$('[name='+this.selRooms+']').val(1);
				this.drawRoom(this.initOccupancy['rooms'][0]['adults'], this.initOccupancy['rooms'][0]['children'], this.initOccupancy['rooms'][0]['ages'],multiFix,frm);
			}else{
				$('[name='+this.roomCounter+']').val(this.initOccupancy['rooms'].length);
				$('[name='+this.selRooms+']').val(this.initOccupancy['rooms'].length);
				for(i in this.initOccupancy['rooms']){
		//			alert(this.initOccupancy['rooms'][i]['adults'] + " : "+i['children']);
					this.drawRoom(this.initOccupancy['rooms'][i]['adults'], this.initOccupancy['rooms'][i]['children'], this.initOccupancy['rooms'][i]['ages'],multiFix,frm);
				}
			}
			
		}else{
			
		}
		
	  };
	  
	  this.drawRoom = function(selAdult,selChild,arrChildAges,multiFix, frm){
		  multiFix = (multiFix == undefined || multiFix == false) ? "" : this.selMultiFix;
		  this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		  // Set number of rooms
//		  var numberActiveRooms = parseInt($('#'+this.formNameId).find('[name='+this.selRooms+']').val());
		 var el = $('#'+this.formNameId).find('[name='+this.roomCounter+']');
		 var counter;
		  if(el.length > 0){
			  var counter = parseInt(el.val());
			  counter++;
			  this.numRooms = counter;
//			  alert("Form Counter : " + counter + " - " +this.formNameId);
			  $('#'+this.formNameId).find('[name='+this.roomCounter+']').val(counter);
			  var el = $('#'+this.formNameId).find('[name='+this.roomCounter+']');
//			  alert("Form Counter : " + counter + " - " +this.formNameId + " - "+el.val());
			  
	  	  }else{
	  		
	  		this.numRooms++; 
	  		counter = this.numRooms;
//	  		alert("Object Counter "+counter);
	  	  }
//		  $("[id="+this.selRooms+multiFix+"]").val(this.numRooms);
		// Number of pax permited
			var paxAdult = new Array(1,2,3,4,5,6);
			var paxChild = new Array(0,1,2,3,4,5);
		  
		  var roomId = this.divRoomBase+counter;
		  var adultId = this.selAdultBase+counter;
		  var childId = this.selChildBase+counter;
		  var container = this.divRoomContainer+multiFix;
		  
		// Add Room to Container
		  var classRoomnode = (this.numRooms > 1) ? "plus" : "";
		
		var roomHtml = "<div id='"+roomId+multiFix+"' class='room-el"+ " "+classRoomnode+"'></div>";
		
		if(multiFix == undefined || multiFix == false || multiFix == ''){
//			alert(this.divRoomContainer);
			$("#"+this.divRoomContainer).append(roomHtml);
		}else{
//			alert(container);
			$("#"+container).append(roomHtml);
		}
//		alert(roomHtml);
//		alert('drawRoom |' +container+'|'+roomHtml);
		// Add Adult Select
		$("#"+roomId+multiFix).append('<div class="label-sel-adults"><div><em>'+this.arTxt['adults']+'</em></div><select id="'+adultId+multiFix+'" name="'+adultId+'" class="'+this.selClass+'"></select></div>');
		var domEl = $("#"+adultId+multiFix).get(0);
		$.each(paxAdult,function (i) {
			domEl.options[domEl.options.length]	= new Option(paxAdult[i],paxAdult[i]);			
		});
		// Set Adult Value
		if(selAdult){
			$("#"+adultId+multiFix).val(selAdult);
			
		}
		
		// Add Child Select
		$("#"+childId+multiFix).remove();
		$("#"+roomId+multiFix).append('<div class="label-sel-child"><div><em>'+this.arTxt['children']+'</em></div><select id="'+childId+multiFix+'" name="'+childId+'" class="'+this.selClass+'" onchange="'+this.objName+'.drawChildAges(\''+roomId+multiFix+'\',\''+childId+'\',false,\''+multiFix+'\')"></select></div>');
		var domEl = $("#"+childId+multiFix).get(0);
		$.each(paxChild,function (i) {
			domEl.options[domEl.options.length]	= new Option(paxChild[i],paxChild[i]);			
		});
		
		if(selChild){
			$("#"+childId+multiFix).val(selChild);
			for(i=0; i<selChild; i++){
				this.drawChildAges(roomId, childId, arrChildAges,multiFix);
			}
		}
	  };
	  
	  this.removeRoom = function(roomId,multiFix,frm){
		
		  multiFix = (multiFix == undefined || multiFix == false) ? "" : this.selMultiFix;  
		  this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		// If a specific room is not given remove the last one
		if(roomId == null || roomId == 'undefined'){
			var selNumRooms = $('#'+this.formNameId).find('[name='+this.selRooms+']').val();
			var roomId = this.divRoomBase+selNumRooms+multiFix;
		}
		
		$("#"+roomId+multiFix).remove();
//		this.numRooms--;
	  };
	  
	  this.changeNumberRoom = function(multiFix,frm){
		  multiFix = (multiFix == undefined || multiFix == false) ? "" : this.selMultiFix;
		  this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		  
//		  alert('changeNumberRoom : '+multiFix);
		  var selNumRooms = $('#'+this.formNameId).find('[name='+this.selRooms+']').val();
		  var el = $('#'+this.formNameId).find('[name='+this.roomCounter+']');
		  if(el.length > 0){
			  var counter = parseInt(el.val());
			  var diffRoom = selNumRooms - counter;
//			  alert(counter + " - " + selNumRooms);
	  	  }else{
	  		  var counter = this.numRooms;
	  	  }
		  
//		  alert(selNumRooms + " : " +this.numRooms);
		  if(counter > selNumRooms){
			for(x=counter; x>selNumRooms; x--){
				var roomId = this.divRoomBase+x;
				this.removeRoom(roomId,multiFix,frm);
				counter--;
				if(el.length > 0){
					el.val(counter);
					this.numRooms = counter;
				}else{
					this.numRooms = counter;
				}
			}
		  }else{
			  for(x=counter; x < selNumRooms; x++){
					this.drawRoom(false, false, false, multiFix,frm);  
				  }  
		  }
//		  alert("Original Change Rooms");
//		  if(diffRoom >= 1){
//			  for(x=1; x<selNumRooms; x++){
//				this.drawRoom(false, false, false, multiFix);  
//			  }
//		  }
	  };
	  
	  // Draw Rooms
	  this.drawRooms = function (multiFix,frm){
		multiFix = (multiFix == undefined || multiFix == false) ? "" : this.selMultiFix;
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		
		var numRooms = $("#"+this.selRooms+multiFix).val();
		
		$("#"+this.divRoomContainer+multiFix).html("");
		
		// Number of pax permited
		var paxAdult = new Array(1,2,3,4,5,6);
		var paxChild = new Array(0,1,2,3,4,5);
		for(x=0;x<numRooms;x++){
			
			var roomId = this.divRoomBase+x;
			var adultId = this.selAdultBase+x;
			var childId = this.selChildBase+x;
			// Add Room to Container
			$("#"+this.divRoomContainer+multiFix).append("<div id='"+roomId+multiFix+"' class='room-el'></div>");
			// Add Adult Select
			$("#"+roomId+multiFix).append('<label><em>'+this.arTxt['adults']+'</em><select id="'+adultId+multiFix+'" name="'+adultId+'" class="'+this.selClass+'"></select></label>');
			var domEl = $("#"+adultId).get(0);
			$.each(paxAdult,function (i) {
				domEl.options[domEl.options.length]	= new Option(paxAdult[i],paxAdult[i]);			
			});
			// Add Child Select
			$("#"+childId+multiFix).remove();
			$("#"+roomId+multiFix).append('<label><em>'+this.arTxt['children']+'</em><select id="'+childId+multiFix+'" name="'+childId+'" class="'+this.selClass+'" onchange="'+this.objName+'.drawChildAges(\''+roomId+multiFix+'\',\''+childId+'\',false,\''+multiFix+'\')"></select></label>');
			var domEl = $("#"+childId).get(0);
			$.each(paxChild,function (i) {
				domEl.options[domEl.options.length]	= new Option(paxChild[i],paxChild[i]);			
			});
		}
	  };
	  
	  this.drawChildAges = function(roomId,childId,values,multiFix){
		multiFix = (multiFix == undefined || multiFix == false) ? "" : this.selMultiFix;
		var numChild = $("#"+childId+multiFix).val(); 
		var ages = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
		var divId = roomId + childId+multiFix;
		$("#"+divId).remove();
		if(numChild > 0){
		$("#"+roomId).append('<div id="'+divId+'" class="div-child-ages">'+this.arTxt['ages']+': <br/></div>');
			for(x=0;x<numChild;x++){
				var selChildAge = childId+"cAge"+x;
//				var selChildAgeId = childId+multiFix+"cAge"+x;
				$("#"+divId).append('<select id="'+selChildAge+multiFix+'" name="'+selChildAge+'" class="'+this.selClass+'"></select>');
				var domEl = $("#"+selChildAge+multiFix).get(0);
				domEl.options[domEl.options.length]	= new Option('---','novalue');
				$.each(ages,function (i) {
					domEl.options[domEl.options.length]	= new Option(ages[i],ages[i]);			
				});
				if(values){
					if(values[x] > 2){
						$("#"+selChildAge+multiFix).val(values[x]);
					}
				}
			}
		}
	  };
	
	  this.setFormDate = function(type,day,month,year,frm){
		  this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		  
		  day = (String(day).length < 2 ) ? "0"+day : day;
		  month = (String(month).length < 2 ) ? "0"+month : month;
		  yearMonth = year + "-"+ month;
//		  alert(type + " : "+ day + " - " +yearMonth);
		  switch (type){
			  case "arrival":
				  $("#"+this.formNameId).find("[name="+this.selArrDay+']').val(day);
				  $("#"+this.formNameId).find("[name="+this.selArrYear+']').val(yearMonth);
				  break;
			  case "departure":
				  $("#"+this.formNameId).find("[name="+this.selDepDay+']').val(day);
				  $("#"+this.formNameId).find("[name="+this.selDepYear+']').val(yearMonth);
				  break;
			  }
		  
		};
		
	this.setFormHiddenDate = function (field,type,frm){
		
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;

		switch (type){
			case "a":
				var day = $("#"+this.formNameId).find("[name="+this.selArrDay+']').val();
				var yearMonth = $("#"+this.formNameId).find("[name="+this.selArrYear+']').val();
				var parts = yearMonth.split("-");
				
				break;
			case "d":
				var day = $("#"+this.formNameId).find("[name="+this.selDepDay+']').val();
				var yearMonth = $("#"+this.formNameId).find("[name="+this.selDepYear+']').val();
				var parts = yearMonth.split("-");
				break;
		}
		
		date = day+"/"+parts[1]+"/"+parts[0];
		if($('#aDateTicket').get() != undefined && $('#aDateTicket').get() != '' && type== 'a'){
			if($('#aDateTicket').val() < date){
				$('#aDateTicket').val(date);
			}
			searchForm.updateTicket(searchForm,{"date": $('#aDateTicket').val(), "lang" :lang});
		}
		
		$('[id='+field+']').val(date);
		
//	alert(field + ' :' + date + ' : '+ $('#'+field).val());
	};
		
	this.getCurrentFormDate = function (type, frm){
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		
		switch (type){
			case "a":
				var day = $("#"+this.formNameId).find('select[name='+this.selArrDay+']').val();
				var yearMonth = $("#"+this.formNameId).find('select[name='+this.selArrYear+']').val();
				var parts = yearMonth.split("-");
				date = new Date(parts[0],parseInt(parts[1],10)-1,day);
				break;
			case "d":
				var day = $("#"+this.formNameId).find('select[name='+this.selDepDay+']').val();
				var yearMonth = $("#"+this.formNameId).find('select[name='+this.selDepYear+']').val();
				var parts = yearMonth.split("-");
				date = new Date(parts[0],parseInt(parts[1],10)-1,day);
				break;
		}
//		alert(date);
		return date;
	};
	
	this.getCurrentFormDateText = function (type,frm){
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		switch (type){
			case "a":
				var day = $("#"+this.formNameId).find('[name='+this.selArrDay+']').val();
				var yearMonth = $("#"+this.formNameId).find('[name='+this.selArrYear+']').val();
				var parts = yearMonth.split("-");
				break;
			case "d":
				var day = $("#"+this.formNameId).find('[name='+this.selDepDay+']').val();
				var yearMonth = $("#"+this.formNameId).find('[name='+this.selDepYear+']').val();
				var parts = yearMonth.split("-");
				break;
		}
		dateText = day + "/"+parts[1]+"/"+parts[0];
//		alert(date);
		return dateText;
	};
	  
  }
