var monthsNumber = 0;
var bStopSubmit = false;
/*
function customRange(input) 
{ 
	return {
//        minDate: (input.id == "pDate" ? $("#pDate").datepicker("getDate") : null)
  	 } 
}
*/
function _$(obj)
{
	return document.getElementById(obj);
	
}

$().ready(function() {



    if (!monthsNumber) monthsNumber = 2;
    // Set autocomplete for locc

    if (document.getElementById("#locc") != null) {

        $("#locc").autocomplete("http://www.comparecarrentals.com.au/post/getlocations2.php",
        {
            width: 230,
            cacheLength: 1,
            max: 20,
            minChar: 3,
            focus: false,
            extraParams: { id: function() { return document.getElementById("country1").value; } }
        });

    }
    // Set autocomplete for loca
    /*    $("#loca").autocomplete("http://www.comparecarrentals.com.au/post/getlocations2.php?id=*", {
    width: 230,
    cacheLength: 1,
    max: 100,
    minChar: 2,
    focus: true,
    extraParams: {}
    });
    */

    /*   $("#def").autocomplete("/post/getlocations2.php?id=*", {
    width: 230,
    cacheLength: 1,
    max: 100,
    minChar: 2,
    focus: true,
    extraParams: 
    {

    }
    });
    */

    if (document.getElementById("#abc") != null) {
        $("#abc").treeview({ speed: "slow", collapsed: true });
    }

    if (document.getElementById("#loca") != null) {
        // What to do when we get results for locas autocomplete
        $("#loca").result(function(event, data, formatted) {
            if (data) {
                /*    document.getElementById("pickup_lon").value = data[2];
                document.getElementById("pickup_lat").value = data[3];

            $("#loca").val(data[1]);
                document.getElementById("locb").value = data[3];
                document.getElementById("locd").value = data[4];
                document.getElementById("country1").value = data[2];

            // if unchecked then the dropoff is the same as the pickup.
                if (!document.getElementById("droploc").checked) 
                {
                document.getElementById("dropoff_lon").value = data[2];
                document.getElementById("dropoff_lat").value = data[3];

 
    document.getElementById("locc").value = data[1];
                document.getElementById("drop_locb").value = data[3];
                document.getElementById("drop_locd").value = data[4];
                document.getElementById("drop_country1").value = data[2];
                }
                */
            }
            onsubmit: false;
        });
    }

    if (document.getElementById("#locc") != null) {
        // What to do when we get results for loccs autocomplete 
        $("#locc").result(function(event, data, formatted) {
            if (data) {
                document.getElementById("locc").value = data[1];

                document.getElementById("dropoff_lon").value = data[2];
                document.getElementById("dropoff_lat").value = data[3];


                //			$("#from2").val(data[1]);
                $("#locc").val(data[1]);
                document.getElementById("drop_locb").value = data[3];
                document.getElementById("drop_locd").value = data[4];
                document.getElementById("drop_country1").value = data[2];


            }
        });
    }

    // Set calendar to date inputs
    if (document.getElementById("pDate") != null) 
    {
        $('#pDate').datepicker({ minDate: 0, numberOfMonths: monthsNumber, dateFormat: 'dd/mm/yy', firstDay: 1 });

        // When a loca date is selected make the minDate for locc this date
        $('#pDate').change(function() {
            var date_tmp = $('#pDate').val().split("/");
            var date_help = $('#dDate').val();
            $('#dDate').datepicker('option', { minDate: new Date(date_tmp[2], date_tmp[1] - 1, date_tmp[0]) });
            $('#dDate').val(date_help);
        });
    }
    if (document.getElementById("dDate") != null) 
    {
        $('#dDate').datepicker({ minDate: 0, numberOfMonths: monthsNumber, dateFormat: 'dd/mm/yy', firstDay: 1 });

        // When a locc date is selected make the maxDate for loca this date
        $('#dDate').change(function() {
            var date_tmp = $('#dDate').val().split("/");
            var date_help = $('#pDate').val();
            $('#pDate').datepicker('option', { maxDate: new Date(date_tmp[2], date_tmp[1] - 1, date_tmp[0]) });
            $('#pDate').val(date_help);
        });
    }


    /*
    $("#loca, #locc").tooltip({ 
    track: true, 
    delay: 0, 
    showURL: false, 
    opacity: 1, 
    fixPNG: true, 
    showBody: " - ", 
    extraClass: "pretty fancy", 
    top: -15, 
    left: 5 
    });
    */


});
/*
function clearBox(el)
{
	if (el.value == "Type an airport, city or town.")
	  $(el).val('');
}
*/
/*
function setLocation(str, postForm)
{
  var loc = new Array();
  loc = str.split('#');

  $("#loca").val(loc[2]);
  $("#locc").val(loc[2]);
  //$("#ploc_id").val(loc[1]);
  //$("#dloc_id").val(loc[1]);
  //$("#country_id").val(loc[0]);

  //$("#dialog1").dialog('close');
}
*/
/*
function checkEnteredLocation()
{
  if($('#pDate').val() != "Click to choose")
  {
       var pData = $('#pDate').val().split("/");
       var pTData = $('#pTime').val().split(":");

    sel_time = new Date();
       sel_time.setYear(pData[2])
       sel_time.setMonth(pData[1]-1);
       sel_time.setDate(pData[0]);
       sel_time.setHours(pTData[0]*1-2);
    sel_time.setMinutes(pTData[1]);

    now = new Date();

       if (sel_time < now)
       {
         alert("Pick up time must be at least 2 hours in advance.");
         return false;
       }
  }



  if (parseInt($("#age").val()) != $("#age").val() )
  {
    alert("Please enter a valid age.")
	return false;
  }

  if ($("#loca").val() != "" && $("#ploc_id").val() == 0)
  {
    /*$("#dialog").html("<div id='dialog1' title='Select Pick Up Location'><span></span></div>");

	$("#dialog1").dialog({
		bgiframe: true, resizable: false,
		height: 340,
		width: 440,
		modal: true,
		overlay:
		{
		  backgroundColor: '#000',
		  opacity: 0.5
		},
		buttons:
		{
		  Cancel: function()
		  {
		  	$(this).dialog('close');
		  }
		}
	});

	$.get(
		"post/get_locations.php",  
		"&type=overlay&q=" + $("#loca").val()+"&id=*",

		function(data)
		{
		  $("#dialog1 span").html("<div>"+data+"</div>");
		  $('#dialog1').dialog('show');
		}
	);
* /
	return false;
  }

  if($('#pDate').val() == "Click to choose")
  {
    alert("Please enter a pick up date.");
    $("#pDate").datepicker('show');
	return false;
  }

  if($('#pDate').val() == "Click to choose")
  {
    alert("Please enter a drop off date.");
    $("#pDate").datepicker('show');
	return false;
  }

  if($('#pDate').val() == $('#pDate').val() && $("#pTime").val() == $("#dTime").val())
  {
    alert("Drop off date and time are the same as pick up date and time.");
    return false;
  }
  
  return true;
}
*/
/*
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) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
*/
/*
var dtCh= "/";
var minYear=2009;
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;
}
*/

/**
 *   Form Validation before sending
 **/
function sendData()//{{{
{
    return false;

  var err_list = "";
  //check date out
    if ((document.getElementById("loca").value.length==0) || (document.getElementById("loca").value == "loca airport"))
 	 err_list += "Please select the from location.\n";

	if (document.getElementById("pDate").value.length == 0)
	  err_list += "Please select the depart date\n";
	else if (document.getElementById("pDate").value == 'dd/mm/yyyy')
	  err_list += "Please select the depart date\n";

   if ((document.getElementById("locc").value.length==0) || (document.getElementById("locc").value == "arrival airport"))
	 err_list += "Please select locc airport.\n";

	//check date ret
	if (document.getElementById("journey_return").checked)
	{
		if (document.getElementById("dDate").value.length == 0)
	  		err_list += "Please select the return date\n";
		else if (document.getElementById("dDate").value == 'dd/mm/yyyy')
		  err_list += "Please select the return date\n";
	}


	var x = 1*document.getElementById("adults").value;
	if ( x < 1 )
	   err_list += "At least one of the passengers must be an adult\n";

	if(err_list)
	{
	  alert (err_list);
	  return false;
	}

	return true;
}//}}}

/*
function sendData_newWindow() {
	if(sendData())
	{
		document.search.submit();
	}
}
*/

function change_journey_type()//{{{
{
  if (!document.getElementById("journey_return").checked)
    document.getElementById("form_return_date").style.visibility = "hidden";
  else
    document.getElementById("form_return_date").style.visibility = "visible";
}//}}}


$.fn.infiniteCarousel = function() {/*{{{*/

    function repeat(str, num) {
        if (isNaN(num)) num = 1;
        return new Array(num + 1).join(str);
    }

    return this.each(function() {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),

            singleWidth = $single.outerWidth(),
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect

        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);

        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;

            $wrapper.filter(':not(:animated)').animate({
                scrollLeft: '+=' + left
            }, 500, function() {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                }

                currentPage = page;
            });

            return false;
        }

        $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');

        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function() {
            return gotoPage(currentPage - 1);
        });

        $('a.forward', this).click(function() {
            return gotoPage(currentPage + 1);
        });

        // create a public interface to move to a specific page
        $(this).bind('goto', function(event, page) {
            gotoPage(page);
        });
    });
}; /*}}}*/
