/*
###################################################################
## Title		 : Javascript Validations
#  Description	 : Dreamticket - Search Module validations
## Date			 : 12th Dec 2007
#  Last Modified :
## Functions	 : 
#
####################################################################
*/

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s)
{
	var i;
    for (i = 0; i < s.length; i++)
	{   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    
	// All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
	{   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    
	return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) 
{
    var arrDays = new Array();
	for (var i = 1; i <= n; i++) 
	{
		arrDays[i] = 31;

		if (i==4 || i==6 || i==9 || i==11)
			arrDays[i] = 30;

		if (i==2) 
			arrDays[i] = 29;
    } 
   return arrDays;
}

function compare(Dat1,Dat2) 
{
	var d1;
	var d2;

	d1=Dat1.split('/');
	d2=Dat2.split('/');

	var Date1=new Date(d1[2],d1[1],d1[0]);
	var Date2=new Date(d2[2],d2[1],d2[0]);
	
	// khalid 07/10/2005
	if(d1.length!=10)
	{
		var Date1=new Date(d1[2],d1[1],d1[0]);
		var Date2=new Date(d2[2].substring(2,4),d2[1],d2[0]);
		//alert(d1[2].substring(2,4));
	}

	if(d2.length!=10)
	{
		var Date1=new Date(d1[2].substring(2,4),d1[1],d1[0]);
		var Date2=new Date(d2[2],d2[1],d2[0]);
		//alert(d1[2].substring(2,4));
	}
	
	if (Date1 > Date2)  
	 return "Y";
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);

	strYr=strYear;
	
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	
	month=parseInt(strMonth);
	
	day=parseInt(strDay);
	
	year=parseInt(strYr);
	
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy")
		alert("Please enter a valid date.\nThe date format should be : dd/mm/yyyy");
		return false;
	}
	
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	/*
	if (strYear.length <4 || year==0 || strYear.length >4 ){
		alert("Please enter a valid 4 digit year")
		return false
	}
	*/
	if (strYear.length <2 || year==0 || strYear.length >4 ){
		alert("Please enter a valid 2 or 4 digit year");
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date");
		return false;
	}
return true;
}

function getCheckedValue(radioObj)
{
	if(!radioObj)		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++)
	{
		if(radioObj[i].checked) 
		{
			return radioObj[i].value;
		}
	}
	return "";
}
function hideRetDate(trip, retdate, rdatimg)
{
	if(trip.value == "s")
	{
		document.search.ret_time.disabled = true;
		retdate.value = '';
		retdate.disabled = true;
		rdatimg.style.display = "none";
	}
	else
	{
		document.search.ret_time.disabled = false;
		retdate.disabled = false;
		rdatimg.style.display = "";
	}
}
/*
function hideRetDate1(trip, retdate)
{
	alert("1");
	if(trip.value == "s")
		retdate.disabled = true;
	else
		retdate.disabled = false;
}
*/

	var cardExp = /[a-zA-Z\. \;\:\'\"\,\>\!\-\?\<\$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|]/;
	var mikExp = /[1234567890\;\:\'\"\>\!\-\?\<\$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|]/;

	function doCheckAlpha(val) 
	{
		
		var strPass = val.value;
		var strLength = strPass.length;
		var tmp;

		for(tmp=strLength; tmp>0; tmp--)
		{
			var lchar = val.value.charAt((tmp) - 1);

//				alert(lchar);
			
			if(lchar.search(mikExp) != -1)
			{
				var tst = val.value.substring(0, (strLength) - 1);
				val.value = tst;
				tmp--;
			}
		}
	}
	function doCheckNum(val) 
	{
		
		var strPass = val.value;
		var strLength = strPass.length;
		var lchar = val.value.charAt((strLength) - 1);
		
		if(lchar.search(cardExp) != -1) 
		{
			var tst = val.value.substring(0, (strLength) - 1);
			val.value = tst;
	   }
	}

function ValidateForm(form)
{  
	var dt1=document.search.dept_dat;
	var dt2=document.search.arr_dat;
	var dt3=document.search.next_year_date;
	var dt4=document.search.today_date;
	
	//alert(document.search.inclusive_tour.value);

/*
	if (form.dept.value == "")
	{
		alert ("Please Enter Departure Airport");
		form.dept.focus();
		return false;
	}
	else
	{
		 var depAir = form.dept.value;

		 if(depAir.search(mikExp) != -1)
		{
			alert('Please Enter the Departure Airport Properly');
			form.dept.focus();
			return false;
		}
	}
*/
    
	if (form.arrival.value == "")
	{
		alert ("Please Enter Arrival Airport");
		form.arrival.focus();
		return false;
	}
	else
	{
		 var arrAir = form.arrival.value;

		 if(arrAir.search(mikExp) != -1)
		{
			alert('Please Enter the Arrival Airport');
			form.arrival.focus();
			return false;
		}
        
	}  

	form.dept_dat.value = getFormatedDate(form.dept_dat.value);  
    if (form.dept_dat.value == "")
    {
        alert ("Please Enter Departure Date");
        form.dept_dat.focus();
        return false;
    }
    else
    { 
         var depDate = form.dept_dat.value;
         if(depDate.length != 10)
         {
             alert('Please Enter the Departure Date as (DD/MM/YYYY) No spaces included');
             form.dept_dat.focus();
             return false;
         }

         if(depDate.search(cardExp) != -1)
        {
            alert('Please Enter the Departure Date Properly as in the form of (DD/MM/YYYY)');
            form.dept_dat.focus();
            return false;
        }
    }

//    if (form.formType.value == 'Advanced')
//    {
//        var radioFlag = form.single[0].checked;
//    }
//    else
//    {
        var radioFlag = true;
//    }
        
    form.arr_dat.value = getFormatedDate(form.arr_dat.value);   
    if(radioFlag)
    if (form.arr_dat.value == "")
    {
        alert ("Please Enter Return Date");
        form.arr_dat.focus();
        return false;
    }
    else
    {    
         var arrDate = form.arr_dat.value;

         if(arrDate.length != 10)
         {
             alert('Please Enter the Return Date as (DD/MM/YYYY) No spaces included');
             form.arr_dat.focus();
             return false;
         }

         if(arrDate.search(cardExp) != -1)
        {
            alert('Please Enter the Return Date Properly as in the form of (DD/MM/YYYY)');
            form.arr_dat.focus();
            return false;
        }
    }

	if(form.adult.value == 0)
	{
		alert("Please Enter Atleast One Adult");
		form.adult.focus();
		return false;
	}
	else
	{
		var adultCount;
		var childCount;
		//var infantCount;
        var ageCount=0;;
		var totalPassengers; // = 

		adultCount = form.adult.value;
		childCount = form.child.value;
		//infantCount = form.infant.value;

		totalPassengers = parseInt(adultCount) + parseInt(childCount);

        
        for(i=1;i<=childCount;i++){
            if(document.getElementById('ages' + i).value < 0){
                alert('Please select child age');
                document.getElementById('ages' + i).focus();
                return false;
            }
            else if(document.getElementById('ages' + i).value <= 1){
                ageCount++;
            }
        }

        document.getElementById('infant').value = ageCount;
        
		if(totalPassengers > 9)
		{
			alert('Sorry for the Inconvinience, You can only book 9 Tickets at a time');
			form.adult.focus();
			return false;
		}
		if(form.adult.value < ageCount)
		{
            if(form.adult.value < ageCount/2){
                alert('We are only able to book reserved seats for up to two infants per traveller');
                form.adult.focus();
                return false;
            }
			else if(form.adult.value < ageCount && rILa.checked==true){
                alert('We are only able to book one infant in lap per traveller');
                form.adult.focus();
                return false;
            }
			
		}
	}

	if(document.search.userType.value == 'agent') 
    {
       /* if(document.search.schedule_flight.checked == true && document.search.charter_flight.checked == true)
	    {
		    document.search.flight_type.value = "schedule,charter";			
	    }
	    else if(document.search.schedule_flight.checked == true)
	    {
		    document.search.flight_type.value = "schedule";		
	    }
	    else if(document.search.charter_flight.checked == true)
	    {
		    document.search.flight_type.value = "charter";		
	    }
	    else
	    {
		    alert('Please Select flight type');
		    form.schedule_flight.focus();
            return false;		
	    }
        */
                
	    var flightTypeArr = new Array();
        var index = 0;
        if(document.search.schedule_flight.checked == true)
        {             
            flightTypeArr[index] =    "schedule";
            index = index + 1;            
        }
        
        if(document.search.charter_flight.checked == true)
        {            
            flightTypeArr[index] =    'charter';     
            index = index + 1;            
        }
        
        if(document.search.multicom_flight.checked == true)
        {            
            flightTypeArr[index] =    'multicom';  
            index = index + 1;              
        }
        
        var count = flightTypeArr.length;
        if(count == 0)
        {
            alert('Please Select flight type');
            form.schedule_flight.focus();
            return false;
        }
        else
        {
            document.search.flight_type.value = flightTypeArr.join(',');            
        }
        
	    if(document.search.psearch.checked == true)
	    {
		    document.search.scheduled_type.value = "published,discounted";			
	    }
	    else
	    {
		    document.search.scheduled_type.value = "discounted";
	    }
    }
    else
    {
        document.search.flight_type.value = "schedule,charter,multicom";
        //document.search.flight_type.value = "schedule,multicom";
        //document.search.flight_type.value = "schedule,charter";
        //document.search.flight_type.value = "multicom";
        document.search.scheduled_type.value = "published,discounted";              
    }
		

	
		
	

	/*if(typeof(form.fare_search) == 'undefined')
	{
		form.method = "post";
		form.action = "holdpage.php";
		form.submit();
	}
	else if((typeof(form.fare_search[0]) != 'undefined') && form.fare_search[0].checked)
	{
		form.method = "post";
		form.action = "search_wait.php";
		form.submit();
	}
	else if((typeof(form.fare_search[1]) != 'undefined') && form.fare_search[1].checked)
	{
		form.method = "post";
		form.action = "holdpage.php";
		form.submit();
	}*/


	
	if(getCheckedValue(document.forms['search'].elements['single'])=='s')
	{
		//alert('Radio Checked value is: '+getCheckedValue(document.forms['search'].elements['single']))
		if (form.dept_dat.value == "")
		{
			alert ("Please Enter Departure Date");
			form.dept_dat.focus();
			return false;
		}
		if (isDate(dt1.value)==false){
			dt1.focus();
			return false;
		}
		
		if (compare(dt1.value,dt3.value) == "Y")
		{	
			//alert ("We can only accept dates that occur between  " +dt4.value + " and " +dt3.value+ ".Please enter a new date.")
			document.search.valid_date_flag.value=true;	
			//return false
		}
		else
		{
			document.search.valid_date_flag.value=false;	
		}
	}
	else
	{

		if (isDate(dt1.value)==false){
			dt1.focus()
			return false;
		}
		if (isDate(dt2.value)==false){
			dt2.focus()
			return false;
		}
		if (compare(dt1.value,dt2.value) == "Y")
		{
			alert ("Return Date can not exceed Departure Date");
			return false;
		}

		if (dt3 && (compare(dt1.value,dt3.value) == "Y"))
		{	
			//alert ("We can only accept dates that occur between  " +dt4.value + " and " +dt3.value+ ".Please enter a new date.")
			document.search.valid_date_flag.value=true;	
			//return false
		}
		else
		{
            if (document.search.valid_date_flag)
            {
			    document.search.valid_date_flag.value=false;	
            }
		}

		if (dt3 && (compare(dt2.value,dt3.value) == "Y"))
		{	
			//alert ("We can only accept dates that occur between  " +dt4.value + " and " +dt3.value+ ".Please enter a new date.")
			document.search.valid_date_flag.value=true;	
			//return false
		}
		else
		{
            if (document.search.valid_date_flag)
            {
			    document.search.valid_date_flag.value=false;	
            }
		}
	}
	

	
	
 }
 
 
  /* This function verifies if a given string is a regular expression */
function regExpr(text, reg) {  
    for(var i = 0; i < text.length; i++) { 
        if (reg.indexOf(text.charAt(i)) == -1)
            return false;
    }

    return true;
}



/* This function tries to format a given date to dd/mm/yyyy 
 * If not possible it returns back the given date*/
function getFormatedDate(date) {  
    var table = new Array();
    table = date.split('/');
    var temp = "";
    var result = "";
    var reg = "0123456789";
    
    if(table.length != 3)
      return date;
    
    if(!regExpr(table[0], reg) || !regExpr(table[1], reg) || !regExpr(table[2], reg))
      return date;
    
    temp = table[0];  
    if(temp.length > 2) return date;
    if(temp.length == 1)  table[0] = "0" + table[0];
    
    temp = table[1];  
    if(temp.length > 2) return date;
    if(temp.length == 1)  table[1] = "0" + table[1];
    
    temp = table[2];  
    if(temp.length != 2 && temp.length != 4) return date;
    if(temp.length == 2)  table[2] = "20" + table[2];
    
    result = table[0] + "/" + table[1] + "/" + table[2];
    
    return result;
}
