/* 
 * Company : Holidayzone Pty Ltd Melbourne Australia
 * Created on :14/12/2009   11:44:54 AM
  
 */

// this function will process the errors
// the function will split the output and then add that to error div
function process_error(output)
{
    var error_array=output.split(',');
    var error_details="";
    var temp_array;

    for(var i=0; i<error_array.length; i++)
        {
            // each element of an array will be in fieldname:error format

            temp_array=error_array[i].split(':');

            if(temp_array.length>1)
                {
                    var field_id=temp_array[0];
                    var error=temp_array[1];
//                    if(error!="")
//                    {
//                        error_details=error_details+error+"\n";
//                    }
                    document.getElementById("error_"+field_id).innerHTML=error;
                    document.getElementById("error_"+field_id).style.display="block";
                    document.getElementById(field_id).className="ui-state-error";
                }
                else
                    {
                      if(temp_array[0]!="")
                       {
                            error_details=error_details+temp_array[0]+"\n";
                       }
                }
        }
        if(error_details!="")
            {
                alert(error_details);
            }
}

/* This function will validate date
 * The function will return true if the date is valid or else it will return false.
 *
 **/
function validate_date(date)
{
     var valid=true;
    var date_array=date.split("-");
    var month=trim(date_array[1]);
    var day=parseFloat(date_array[2]);
    var year=trim(date_array[0]);

    switch(month)
    {
        case '01':if(day>31)
                {
                    valid=false;
                }
                break;
       case '02':if(checkleapyear(year) && day>29)
                {
                    valid=false;
                }
                if(!checkleapyear(year) && day>28)
                    {
                        valid=false;
                    }
                break;
       case '03':if(day>31)
                {
                    valid=false;
                }
                break;
       case '04':if(day>30)
                {
                    valid=false;
                }
                break;
       case '05':if(day>31)
                {
                    valid=false;
                }
                break;
       case '06':if(day>30)
                {
                    valid=false;
                }
                break;
       case '07':if(day>31)
                {
                    valid=false;
                }
                break;
       case '08':if(day>31)
                {
                    valid=false;
                }
                break;
      case '09':if(day>30)
                {
                    valid=false;
                }
                break;
      case '10':if(day>31)
                {
                    valid=false;
                }
                break;
      case '11':if(day>30)
                {
                    valid=false;
                }
                break;
       case '12':if(day>31)
                {
                    valid=false;
                }
                break;
    }
  //  alert(valid);
    return valid;
}
/* This function will check leap year
 * This function takes year
 * if the year is leap year then it will return true or else it will return false
 **/
function checkleapyear(year)
{
       year = parseInt(year);
        if(year%4 == 0)
        {
                if(year%100 != 0)
                {
                        return true;
                }
                else
                {
                        if(year%400 == 0)
                                return true;
                        else
                                return false;
                }
        }
return false;
}

/* This function will validate checkin date
 * If the date is in past then this function will return false else this function will return true.
 * */
function check_checkin_date(checkin_date)
{

     checkin_date=checkin_date.replace(/-/gi, '/');


    var checkin_date1=new Date(checkin_date);
    // get the today's date'
    var today=new Date(); // the function will return date in date/time format example Wed Feb 17 2010 16:28:52 GMT+1100 (AUS Eastern Daylight Time)
    // we need date in yyyy/mm/dd format
    var current_year=today.getFullYear(); // get the current year
     var current_month=today.getMonth(); // get the current month
     var current_date=today.getDate(); // get the current date
     // increment month because in javascript month starts from 0 i.e 0 for january.
    current_month++; // increment month
    var today_string=current_year+"/"+current_month+"/"+current_date; // build the date string
    today=new Date(today_string); // get the date in required format yyyy/mm/dd
    // Convert both dates to milliseconds
    var checkin_ms = checkin_date1.getTime();

    var today_ms = today.getTime();

    if(today_ms>checkin_ms)
        {
            return false;
        }
        else
            {
                return true;
            }
}

 /*This function will update checkout date in hidden field if it is selected from the dropdown list
  * ********************************** ARGUMENT DESCRIPTION ***************************************
  *  checkout_day_field : Id of the checkout day dropdown list
  *  checkout_month_field: Id of the checkout_month_year field
  *  checkout_hidden_field: Id of the checkout hidden field where the actual date will be stored
  *  checkin_field: Id of the checkin field where the actual checkin date will be stored
  *  nights_field: Id of the span where number of nights will be displayed.
  **/
function set_checkout_date(checkout_day_field,checkout_month_field,checkout_hidden_field,checkin_hidden_field,nights_field){
    // clear all fields
    document.getElementById(checkout_day_field).className="autowidth";
    document.getElementById(checkout_month_field).className="autowidth";
    // clear all divs
    document.getElementById("error_"+checkout_day_field).style.display="none";
    document.getElementById("error_"+checkout_month_field).style.display="none";

    var checkout_day=document.getElementById(checkout_day_field).value;
    var checkout_month_year=document.getElementById(checkout_month_field).value;
    // build the date string
    var checkout_date=checkout_month_year+"-"+checkout_day;
     document.getElementById(checkout_hidden_field).value=checkout_date;
   if(validate_date(checkout_date))
   {

            var checkin_date=document.getElementById(checkin_hidden_field).value;
        // validate date
            if(check_dates(checkin_date,checkout_date))
            {
                // if the date is valide then calculate number of nights
                var nights=days_between(checkin_date,checkout_date);
                 
                                    document.getElementById(nights_field).innerHTML=nights;
                              
            }
            else
                {
                    process_error(checkout_month_field+":Checkout date must be after checkin date.,"+checkout_day_field+":");
                }
   }
   else
       {
            process_error(checkout_month_field+":Invalid date.,"+checkout_day_field+":");
       }
}
/*This function will update calendar
 *It takes field id.Example '#checkout',day_field,date in 'yyyy-mm-dd' format and the id of nights_field.*/
function update_calendar(field_id,day_field,date,nights_field)
{
   field_id="#"+field_id;
   date=date.replace(/-/gi, '/');
    var checkin_date=new Date(date);
    checkin_date.setDate(checkin_date.getDate()+1);
    $(field_id).datepicker('setDate',checkin_date);
    var day=checkin_date.getDate();
    day--;
    document.getElementById(nights_field).innerHTML=1;
    document.getElementById(day_field).options.selectedIndex=day;

}

/* This function will update checkin date in hidden field if it is selected from the dropdown list
 * ********************************** ARGUMENT DESCRIPTION ***************************************
  *  checkin_day_field : Id of the checkin day dropdown list
  *  checkin_month_field: Id of the checkin_month_year field
  *  checkin_hidden_field: Id of the checkin hidden field where the actual date will be stored
  *  checkout_hidden_field:Id of the checkout hidden field where the actual checkout date will be stored
  *  nights_field: Id of the span where the number of nights will be displayed.
  *  checkout_day_field: ID of the checkout day field.
  *  checkout_month_year_field: ID of the checkout month and year field
 * */
function set_checkin_date(checkin_day_field,checkin_month_field,checkin_hidden_field,checkout_hidden_field,nights_field,checkout_day_field,checkout_month_field)
{
    // clear all fields
    document.getElementById(checkin_day_field).className="autowidth";
    document.getElementById(checkin_month_field).className="autowidth";
    document.getElementById(checkout_day_field).className="autowidth";
    document.getElementById(checkout_month_field).className="autowidth";
    // clear all divs
    document.getElementById("error_"+checkin_day_field).style.display="none";
    document.getElementById("error_"+checkin_month_field).style.display="none";
     document.getElementById("error_"+checkout_day_field).style.display="none";
    document.getElementById("error_"+checkout_month_field).style.display="none";

    var checkin_day=document.getElementById(checkin_day_field).value;
    var checkin_month_year=document.getElementById(checkin_month_field).value;
    // build the date string
    var checkin_date=checkin_month_year+"-"+checkin_day;
  //  alert(checkin_date);
     document.getElementById(checkin_hidden_field).value=checkin_date;
   if(validate_date(checkin_date))
       {
//                // call update_calendar function to update checkout calendar.
                                update_calendar(checkout_hidden_field,checkout_day_field,checkin_date,nights_field);
                var checkout_date=document.getElementById(checkout_hidden_field).value;
            // validate checkin date
                if(!check_checkin_date(checkin_date))
                    {
                            process_error(checkin_month_field+":Checkin date cannot be in past.,"+checkin_day_field+":");

                    }
//                     else
//                     {
//
//                            if(check_dates(checkin_date,checkout_date))
//                            {
//                               // var nights=days_between(checkin_date,checkout_date);
//
//                                 //       document.getElementById(nights_field).innerHTML=nights;
//
//                            }
//
//                     }
       }
       else
           {

               process_error(checkin_month_field+":Invalid date.,"+checkin_day_field+":");
           }

}
/* This function will validate checkin and checkout dates.
* If the checkout date is greater than checkin date then the function will return true else function will return false.
 */
function check_dates(checkin_date,checkout_date)
{
     // convert javascript format i.e. YYYY/MM/DD so replace '-' with '/'

    checkin_date=checkin_date.replace(/-/gi, '/');
    checkout_date=checkout_date.replace(/-/gi, '/');

    var checkin_date1=new Date(checkin_date);
    var checkout_date1=new Date(checkout_date);

    // Convert both dates to milliseconds
    var checkin_ms = checkin_date1.getTime();
    var checkout_ms = checkout_date1.getTime();
    if(checkout_ms>checkin_ms)
        {
            return true;
        }
        else
            {
                return false;
            }

}
/* This function will calculate difference between two dates and return number of nights between two dates.
 * The function takes checkin and checkout dates
 **/
function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // convert javascript format i.e. YYYY/MM/DD so replace '-' with '/'

    date1=date1.replace(/-/gi, '/');
    date2=date2.replace(/-/gi, '/');

    var date3=new Date(date1);
    var date4=new Date(date2);

    // Convert both dates to milliseconds
    var date1_ms = date3.getTime();
    var date2_ms = date4.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}
/**
 * This function will send an ajax request.
 * It takes argument string,url and function name.
 * it calls the function given in function name once it gets output from ajax script.
 */
function send_ajax_request(argument,url,function_name)
{
     var httpxml;


	try
	{
		// Firefox, Opera 8.0+, Safari
		httpxml=new XMLHttpRequest();
	}
	catch (e)
	{
	// Internet Explorer
		try
		{
			httpxml=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				httpxml=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}

	function request()
	{


		if(httpxml.readyState==4)
		{
			var output=httpxml.responseText;
                        trim(output);
                         window[function_name](output);

                }
	}
    // alert(argument);


	httpxml.onreadystatechange=request;
	httpxml.open("POST",url,true);

//Send the proper header information along with the request
httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpxml.setRequestHeader("Content-length", argument.length);
httpxml.setRequestHeader("Connection", "close")

httpxml.send(argument);
}
/*This function will remove extra space from the string. It takes string as an argument.*/
function trim(str){
	return str.replace(/^\s+|\s+$/g, '') ;
}
/**
 * Convert string into number and anything that is not belong to the number will be set to 0
 * @param <String> str
 * @return <float>
 */
function cast_to_number(str){
    if(str == null || trim(str) == "" || isNaN(str))
       {
        return 0;
       }
    else
        {
          return parseFloat(str);
        }
}
/**
 * This function will return an array of discount amount and discounted total.
 * It takes rate,extra_adult_cost,extra_child_cost,discount type, discount value,offer discount flag (y/n) and number of rooms as an argument.
 * It returns discount array Array([0]=>12,[1]=>120)
 * First element will be discount amount and the second element will be discounted total.
 */
function get_discounted_total(rate,extra_adult_cost,extra_child_cost,discount_type,discount,offer_discount_flag,num_rooms)
{
    var discount_array=new Array();
   var total=(rate * num_rooms)+extra_adult_cost+extra_child_cost;
    discount_array[0]=0;
    discount_array[1]=total;
    if(discount_type=="p")
        {
            if(offer_discount_flag=="y")
            {
                var discount_amount=(total*discount)/100;
                discount_amount=Math.round(discount_amount);
                 var discounted_total=total-discount_amount;
                discount_array[0]=discount_amount;
               discount_array[1]=discounted_total;
            }
        }
        if(discount_type=="n")
            {
               if(offer_discount_flag=="y")
                {   discount_amount=discount*num_rooms;
                    discount_amount=Math.round(discount_amount);
                    discounted_total=total-discount_amount;
                    discount_array[0]=discount_amount;
                    discount_array[1]=discounted_total;
                }
            }
            return discount_array;
}
