/**
 * This class extends searchForm and is specific to Port Aventura hotel and ticket search
 * 1) Submits PortAventura form
 * 2) Checks dates of arrival with ticket selection
 * 3) Gets available tickets for a certain date via AJAX and updates select box in form
 * 4) Gets price for a specific ticket selection and updates HTML
 * 
 * @param opts object {x:y}
 * @return
 */
function SearchFormPA(opts){
	
	Object.extend(this, new baseOptions());
	Object.extend(this, new searchForm(opts));
	this.objName = "oSearchFormPA";
	this.formNameId = "frmSearch";
	// set up variables
	this.selTicket = "ticket_id";
	this.selTicketValue = "";
	this.xmlField = 'id';
	this.inputDateTic = 'aDateTicket';
	this.xmlDescr = 'name';
	this.data 	= "";
	this.dataType = "xml";
	this.arCurList = "";
	this.lang  	= "";
	this.token 	= "";
	this.type 	= "";
	this.action = "getTicket";
	this.postcmd = "";
	this.calDate = "";
	
	
	// Divs and selects
	this.divPriceResultBase = "div-ticket-price-result";
	this.divPriceBase		= "div-ticket-price";
	
	// Texts
	this.arText = new Array;
	
	// Set options
	this.setOpts(opts,this);
	// Set Object Name
	this.setObjectName = function(name){this.objName = name;};
	
	this.doFormSubmit = function(frm){
		 // Check Dates
		
		 var isValidDates= this.checkDates(frm);
		 if(!isValidDates){return false;}
		 
		 // if HotelPA check that ticket date is not before arrival and after departure
//		 alert($("#"+this.selType+"[checked]").val() );
//		 return false;
		 if(this.getType() == 'HotelPA'){
			if(!this.checkTicketDate(frm)){return false;}
			
			if($('#'+this.selTicket).val() == '' ){
				alert(this.arTxt['no ticket selected']);
				$('#'+this.selTicket).focus();
				return false;
			}else{
				
			}
		 }
		 
		 this.submitSearch(frm);
		 
		 return true;
	};
	
	this.checkDates = function(frm){
		  
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		
		var arDateFrom = $("#"+this.formNameId).find('[name='+this.selArrYear+']').val().split('-'); 
		 arDateFrom[2] = $("#"+this.formNameId).find('[name='+this.selArrDay+']').val();
		 
		 var arDateTo = $("#"+this.formNameId).find('[name='+this.selDepYear+']').val().split('-'); 
		 arDateTo[2] = $("#"+this.formNameId).find('[name='+this.selDepDay+']').val();
		 
//		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
			  // Check that the date format is correct
			  if(arDateFrom.length != 3 || arDateTo.length != 3){
				alert("101 " + this.arTxt['error dates']);  
				$("#"+this.formNameId).find('[name='+this.inputDateFrom+']').focus();
				return false;
			  }
		  
		  var dateCheck = new Date();
		  var dateFrom = new Date(parseInt(arDateFrom[0]),parseInt(arDateFrom[1],10)-1,parseInt(arDateFrom[2],10));
		  var dateTo = new Date(parseInt(arDateTo[0]),parseInt(arDateTo[1],10)-1,parseInt(arDateTo[2],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.checkTicketDate = function(frm){
		this.formNameId = (frm != undefined ) ? frm : this.formNameId;
		
		 var arDateFrom = $("#"+this.formNameId).find('[name='+this.inputDateFrom+']').val().split('/'); 
		 var arDateTo = $("#"+this.formNameId).find('[name='+this.inputDateTo+']').val().split('/');
		 var arDateTic = $("#"+this.formNameId).find('[name='+this.inputDateTic+']').val().split('/');
		 
		 var arDateFrom = $("#"+this.formNameId).find('[name='+this.selArrYear+']').val().split('-'); 
		 arDateFrom[2] = $("#"+this.formNameId).find('[name='+this.selArrDay+']').val();
		 
		 var arDateTo = $("#"+this.formNameId).find('[name='+this.selDepYear+']').val().split('-'); 
		 arDateTo[2] = $("#"+this.formNameId).find('[name='+this.selDepDay+']').val();
		 
		 var dateFrom = new Date(arDateFrom[0],arDateFrom[1],arDateFrom[2]);
		 var dateTo = new Date(arDateTo[0],arDateTo[1],arDateTo[2]);
		 var dateTicket = new Date(arDateTic[2],arDateTic[1],arDateTic[0]);
		 
		 if(dateTicket < dateFrom ){
			 alert(this.arTxt['error ticket arrival']);  
			 $("#"+this.formNameId).find('[name='+this.inputDateTic+']').focus();
			 return false;  
		 }
		 
		 if(dateTicket > dateTo ){
			alert(this.arTxt['error ticket departure']);  
			$("#"+this.formNameId).find('[name='+this.inputDateTic+']').focus();
			return false;  
		 }
		 
		 return true;
	};
	
	this.updateTicket = function (obj,params,postcmd){
		// set param link
		var strParams = this.createParamsString(params);
		
		// set post cmd
		obj.postcmd = postcmd;
		$.ajax({
			type: "GET",
			url: "/includes/service/ServiceRequest.php",
			data: "type="+this.type+"&action="+this.action+"&token="+this.token+strParams,
			dataType: "xml",
			success: function(data) {
					obj.checkResponseXml(data,obj.postcmd,params.selTicketValue);

	  			}, // End Ajax Success Call
					error: function(data, txtStatus, eText){
					// Remove page Loader

					},
					complete: function(){
					}


				});
	};
	
	this.checkResponseXml = function (xml,postcmd,selValue) {
		var data = $(xml).find("data"); 
		var status = $(xml).find("status"); 
		var lang = $(xml).find("lang");
		
		if(status.text() == "Y"){
			this.doPopulateSelectXmlAttr(this.selTicket,data,this.xmlField, this.xmlDescr,this.arTxt['no ticket selected'],selValue);
		}else{
			var errorMsg = $(xml).find("errorMsg");
			this.doResetSelect(this.selTicket,errorMsg.text());
		}
		
		
	};
	
	this.getResult = function (obj,oParams,strParams){
		// set param link
		var strParams = (oParams) ? this.createParamsString(oParams) : strParams;
		$.ajax({
			type: "GET",
			url: "/includes/service/ServiceRequest.php",
			data: "type="+this.type+"&action="+this.action+"&token="+this.token+"&"+strParams,
			dataType: (this.dataType) ? this.dataType : 'json',
			success: function(data) {
				obj.checkResponse(data);

	  			}, // End Ajax Success Call
			error: function(data, txtStatus, eText){
			// Remove page Loader
				alert(eText);
//				obj.checkError(data, txtStatus, eText);
			},
			complete: function(){
				// Hide loader
			}


				});
	};
	
	this.checkError = function (data){
		switch(this.action){
			case "checkTicketAvaliability":
			break;
			case "getTicketPrice":
				if(data.result.date == null)
					alert("Date: " + this.arTxt["no date selected"]);
			
			break;
		}
		
	};
	
	this.checkResponse = function (data){
		// Hide Loader
		switch(this.action){
			case "checkTicketAvaliability":
			if(data.result.status==false){
				alert("Date: " + this.arTxt["ticket not available"]);
			}
			break;
			case "getTicketPrice":
				var divResult = this.divPriceResultBase + data.result.pId;
				var divPrice = this.divPriceBase+data.result.pId;
				if(data.result.status==false){
					$("#"+divResult).hide();
					var hasTicket = false;
					for(i in data.result.arTicket){
						if(data.result.arTicket[i] > 0){
							hasTicket = true;
						}
					}
					if(hasTicket == false){
						alert(this.arTxt["no ticket selected"]);
					}else{
						alert("Date: " + this.arTxt["ticket not available"]);
					}
					
				}else{
					// Update result div
					$("#"+divPrice).html(this.arTxt['total'] + " " +data.result.price.total + " &euro;");
					$("#"+divResult).show();
				}
			break;
		}
	};
	
	this.setResult = function(data){
		this.result = data;
//		alert(data);
	};
	
	this.checkTickAvailabilty = function(date,id){
		
		this.action = "checkTicketAvaliability";
		this.dataType = "json";
		var params = {"date": date, "lang" :this.lang, "pId": id};
		this.getResult(this, params);
//		var status = $(this.result).find("status"); 
//		alert(this.result);
//		alert(res);
	};
	
	this.getTicketPriceInit = function (){
		// Bind Ajax to Form
//		var options = {
//				type:		"post",
//				dataType:  	"json",
//				url:		"/includes/service/ServiceRequest.php",
//				success: 	this.updateTicketPrice
//		};
//		
//		$('form').ajaxForm(options);
		// Remove Form Submit
//		$('form').submit(function() {
//			  return false;
//			});
	};
	
	this.updateTicketPrice = function (form){
		this.action ="getTicketPrice";
//		alert("Start Update Price : "+ form);
//		alert($("form[id="+form+"]").serialize());
		var date = $("form[id="+form+"]").find("[name=aDate]").val();
		var data = $("form[id="+form+"]").serialize();
		if(date == ''){
			$("form[id="+form+"]").find("[name=aDate]").focus();
			alert(arTxt['no date selected']);
			
		}else{
			this.getResult(this, false, data);
		}
		
		// Start
//		alert("Receive Post data: " + data);
	};
	
	this.submitTicketForm = function (formEl){
		
		$("#"+formEl).attr("action", "https://www.barcelonapoint.com/tpv/tpv_ticket_form.php");
//		$("#"+formEl).attr("action", "/tpv/tpv_ticket_form.php");
//		alert($("#"+formEl).attr("action"));
		$("#"+formEl).submit();
		
	};
	
	this.submitSearch = function (frm){
		$("#"+frm).attr("action", "/results.php");
		$("#"+frm).submit();
		
	};
	
}
