/* 
 * Company : Holidayzone Pty Ltd Melbourne Australia
 * Created on :10/08/2010   11:11:09 AM
  
 */
// this function will return id of selected chain in hidden field
 function findValue(li)
 {


var svalue=0;
        if( li == null ) return alert("No match!");


	if( !!li.extra )
           {
            svalue = li.extra[0];

           }

	// otherwise, let's just display the value in the text box
	else{
            svalue = li.selectValue;
        }
	// get_locations();
}
function formatItem(row) {

	return row[0] ;//+ " (id: " + row[1] + ")";
}

function selectItem(li) {

	findValue(li);
}
// this function will reset the given hidden field by making its value field to 0
// this function takes 1 argument id of the hidden field.
function clear_data(element)
{
  //  alert(element);
  document.getElementById(element).value=0;
}
// this function will bind the text field with auto complete
// ********************** ARGUMENT DESCRIPTION *********************
/* field - field is a text box which we need to bind with autocomplete
 *  url - url is a target url which will be called by the autocomplete  i.e. abc.php
 * extraprams -extraprams is a list of extra parameters which we need to pass to the php file other then typed value
i.e. if we want to send state ='victoria'  then extraprams value will be {state : 'victoria'}.
Autocomplete function will generate url in following format.
url= abc.php?q=typed value&state=victoria.
 * target_field - target_field is a id of hidden field where we want to store id of the autocomplete result. i.e if we are using autocomplete to get the state
 * in given country and if we select victoria from the autocomplete list then state_id of victoria will  be stored in the hidden field.
 * target_function - name of call back function that needs to be called when the result is selected from the auto complete list. Example load_data.
 * Please give only function name.
 */


function load_autocomplete(field,url,extraprams,target_field,target_function)
{


    $(document).ready(function() {

	$(field).autocomplete(
		url,
		{
			delay:10,
			minChars:3,
			matchSubset:0,
			matchContains:1,
			cacheLength:800,
                        onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
                       target:target_field,
                       callback_function:target_function,
                       extraParams:extraprams,
                       selectFirst:true,
			autoFill:true
		}
	);

            });

}
/*This function will remove extra space from the string. It takes string as an argument.*/
function trim(str){
	return str.replace(/^\s+|\s+$/g, '') ;
}
// this function will process the errors
// the function will split the output and then add that to error div
function process_error(error)
{
    var error_array=error.split(',');
    var error_details="";
    var temp_array;

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

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

            if(temp_array.length>1)
                {
//                    if(temp_array[1]!="")
//                    {
//                    error_details=error_details+temp_array[1]+"\n";
//                    }
                    if(i==0)
                        {
                            display_error(temp_array[0], temp_array[1], true);
                        }
                        else
                            {
                                 display_error(temp_array[0], temp_array[1], false);
                            }
            }
                else
                    {
                        if(temp_array[0]!="")
                        {
                            error_details=error_details+temp_array[0]+"\n";
                        }
                    }
        }
        // format the output and add that to the error div.
    if(error_details!="")
            {
                alert(error_details);
            }
}
// this function will display error in the error div
// this function takes 3 arguments 1st will be field name 2nd will be error and 3rd will be focus (boolean)
function display_error(field,error,fac)
{

    var error_field="error_"+field;
    document.getElementById(field).className="ui-state-error";
    document.getElementById(error_field).innerHTML=error;
    document.getElementById(error_field).style.display="block";
    if(fac)
        {
           document.getElementById(field).focus();
        }
}
/**
 * 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;
                         if(function_name!="")
                          {   
                             output=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 validate input variable based on arguments passed to this function
// if the required argument is true then the function will check for the empty value and it will an error if the value is empty.
// if the length variable is greater then 0 than the function will check for the variable's length and if the variable's length is greater than the given length then it will return an error.
// type field is to specify variable's type. Type can be
//                  1  Number
//                  2  String


function validate(field_name,value,type,length,required)
{
    value=trim(value);
    var error_flag=0;
    var errors=new Array();
    var value_length=value.length;

    if(required)
    {// check for the empty string


       if(value_length==0 || value=='' || value=='undefined')
         {
             errors['empty']=field_name+" cannot be empty.";
              error_flag=1;

          }

     }

     if(error_flag==1)
      {
            return errors;
     }
     switch(type)
     {
         case "Number"  : if(isNaN(value))
                           {

                                errors['number']=field_name+" must be number.";

                                error_flag=1;

                           }
                           break;
         case "String"   :
                            if(value_length>0)
                            {
                                if(value_length>length)
                                {
                                    errors['string_length']=field_name+" cannot be greater than "+length+" characters.";
                                    error_flag=1;

                                }
                            }
                            break;


     }
     if(error_flag==0)
     {
            return true;
     }
     else
     {
            return errors;
     }

}
/* 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).innerHTML="";
    document.getElementById("error_"+checkout_month_field).innerHTML="";

    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 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).innerHTML="";
    document.getElementById("error_"+checkin_month_field).innerHTML="";
     document.getElementById("error_"+checkout_day_field).innerHTML="";
    document.getElementById("error_"+checkout_month_field).innerHTML="";
    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);

}
/**
 * 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 load data in dropdown list based on arguments
//  ***************** Argument Description ***********************
//    1. url - url of php file which will be called to get data from the database
//    2. value - value will be used to search data it should be in following format
//    value_name:value_id (name and id separated by ':')  ie. if we want all the cities in victoria then the format of sate value must be victoria:123
//    3. field- field is a id of target dropdown where we want to load data.


function get_dropdown_data(url,value,field)
{


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()
	{
		var array_value;
		//alert(httpxml.onreadystatechange);
		if(httpxml.readyState==4)
		{
			//alert(httpxml.responseText);
			var myarray=eval(httpxml.responseText);
                  //   alert(myarray);
			var element=document.getElementById(field);
			// Before adding new we must remove previously loaded elements
			for(var j=element.options.length-1;j>=1;j--)
			{
                        	element.remove(j);
			}
			var optn = document.createElement("OPTION");


			for (var i=0;i<myarray.length;i++)
			{
				optn = document.createElement("OPTION");
				array_value=myarray[i].split(":");
				optn.text = array_value[0];
				optn.value = array_value[1];
				element.options.add(optn);

			}
		}
	}

	url=url+"?data="+value;
	url=url+"&sid="+Math.random();
	//alert(url);
	httpxml.onreadystatechange=request;
	httpxml.open("GET",url,true);
	httpxml.send(null);
}
/*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--;
   // alert(nights_field);
    document.getElementById(nights_field).innerHTML=1;

    document.getElementById(day_field).options.selectedIndex=day;
    
}
/**
 * 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;
}
