var AH = {
	Event: {
		track: function (tracker, action, label) {
            if(typeof tracker != "undefined"){
                tracker._trackEvent(action, label);
            }
        }
    },
    Calendar: {
       init: function () {
            // If this is a page that needs a calendar interface...
            if (document.getElementById('yearMonth')) {
                // Configure the jQuery datepicker plugin
               // $.datePicker.setDateFormat('dmy','/'); // Set date format
               /* $.datePicker.setLanguageStrings(
                    dpDayArray,
                    dHmonthArray,
                    {
                        p: dpPrevious,  // Previous
                        n: dpNext,      // Next
                        c: dpClose,     // Close
                        b: dpChooseDate // Choose the date
                    }
                );*/
                // Create variables to represent today's date
                var today   = new Date();
                var dd      = today.getDate(),
                    mm      = today.getMonth() + 1,
                    yyyy    = today.getFullYear();

                // Attach a popup calendar widget to the checkin date field
                // and run the dropdown update script when it changes
            /*    $('#datePicker,#b_datePicker').datePicker({
					startDate: dd+'/'+mm+'/'+yyyy,  // Start date is today
                    endDate: (calEndDate != null)? calEndDate : '11/11/2074',          // My hundredth birthday! :D
                    firstDayOfWeek: 1               // week starts on Monday				
				}).change(function () {
                    AH.Calendar.changeFunc(this);
                });
*/
                // Find tomorrow's date
                var tomorrow = new Date();
				tomorrow.setDate(tomorrow.getDate()+1);

                // Update variables for tomorrow's date
                dd = tomorrow.getDate();
                mm = tomorrow.getMonth() + 1;
                yyyy = tomorrow.getFullYear();

                // Attach a popup calendar widget to the checkout date
               /* $('#checkout_datePicker,#bcheckout_datePicker').datePicker({

					startDate: dd+'/'+mm+'/'+yyyy,  // Start date is today
                    endDate: (calEndDate != null)? calEndDate : '11/11/2074',          // My hundredth birthday! :D
                    firstDayOfWeek: 1               // week starts on Monday

				}).change(function () {
                    AH.Calendar.changeFunc(this);
                });
*/
				// Make dropdown changes also change the hidden text field
                $('#day,#yearMonth,#b_day,#b_yearMonth').change(function () {

                    var prefix = (this.id.match(/^b/)) ? 'b' : '';
					var checkoutDatePicker= $('#'+prefix+'checkout_datePicker');
					if (prefix!='') prefix+= '_';

					var yearMonthArr= $('#'+prefix+'yearMonth').val().split('-');

                    // Update the hidden field with the new date chosen in the dropdowns
                    $('#'+prefix+'datePicker').val(AH.Calendar.getDatePickerString($('#'+prefix+'day').val(), yearMonthArr[1],  yearMonthArr[0]));

                    // Update the checkout date using the new checkin date
                    AH.Calendar.updateCheckoutDate(checkoutDatePicker, AH.Calendar.getDateFromDatePicker($('#'+prefix+'datePicker')));
				});

                // Make checkout dropdown changes also update the hidden field
                $('#checkout_day,#checkout_yearMonth,#bcheckout_day,#bcheckout_yearMonth').change(function () {

                    var prefix = ((this.id.match(/^b/))? 'b' : '') + 'checkout_';

					var yearMonthArr= $('#'+prefix+'yearMonth').val().split('-');

                    // Update the hidden field with the new checkout date chosen in the dropdowns
                    $('#'+prefix+'datePicker').val(AH.Calendar.getDatePickerString($('#'+prefix+'day').val(), yearMonthArr[1],  yearMonthArr[0]));
                });

            }
        },
        // A function that is called every time the hidden date fields are changed
        changeFunc: function (elem) {

            // Find out if this is the normal datepicker or the brochure availability form
            var underscorePos= elem.id.indexOf('_');
            var prefix = (underscorePos == -1) ? '' : elem.id.substr(0, underscorePos);
            var checkoutDatePicker = $('#'+prefix+'checkout_datePicker');
            if (prefix!='') prefix+= '_';

            // Setup date update event to repopulate dropdowns
            var dd = elem.value.substr(0,2),
                mm = elem.value.substr(3,2),
                yyyy = elem.value.substr(6,4);

            // Fix weird octal/hex parsing bug
            if (dd == '08') dd = 8;
            if (dd == '09') dd = 9;
            if (mm == '08') mm = 8;
            if (mm == '09') mm = 9;

            // Update the dropdowns to the correct values
            $('#'+prefix+'day').val(parseInt(dd));
            $('#'+prefix+'yearMonth').val(yyyy+'-'+parseInt(mm));

            // Update the checkout date for the new checkin date
            AH.Calendar.updateCheckoutDate(checkoutDatePicker, new Date(yyyy, parseInt(mm)-1, dd));

        },

        fixSingleDigits: function (number) {
            return (parseInt(number) > 9) ? number : '0' + number;
        },
		getDatePickerString: function(day, month, year){
            return AH.Calendar.fixSingleDigits(day) + '/' +
                   AH.Calendar.fixSingleDigits(month) + '/' +
                   year
		},
		getDateFromDatePicker: function (datePicker) {
            if (datePicker != null && datePicker.val() != null && datePicker.val() != '') {
				var split = datePicker.val().split('/');
                // Fix weird octal/hex parsing bug
                if (split[0] == '08') split[0] = 8;
                if (split[0] == '09') split[0] = 9;
                if (split[1] == '08') split[1] = 8;
                if (split[1] == '09') split[1] = 9;
                var new_date = new Date(split[2], parseInt(split[1]) - 1, split[0]);
                return new_date;
			} else {
				return null;
			}
		},
		updateCheckoutDate: function(checkoutDatePicker, checkInDate) {

			if (checkoutDatePicker != null) {

				//Update checkoutDatePicker if the field exists, and the checkout date is before the checkin date.

				var newCheckOutDate = null;
				var checkoutDate = null;

                // Get the current checkout date
                checkoutDate = AH.Calendar.getDateFromDatePicker(checkoutDatePicker);

                // If the checkout date isn't set or is before the checkin date...
                if (checkoutDate == null || checkoutDate <= checkInDate) {
                    // Create a new checkout date the day after the checkin date
                    newCheckOutDate = new Date();
					//newCheckOutDate.setTime(checkInDate.getTime());
					//newCheckOutDate.setDate(newCheckOutDate.getDate() + 1);
				}

				if (newCheckOutDate != null) {
					checkoutDatePicker.val(AH.Calendar.getDatePickerString(newCheckOutDate.getDate(),  newCheckOutDate.getMonth() + 1, newCheckOutDate.getFullYear()));
					checkoutDatePicker.trigger('change');
				}
			}
		}
	},
    Key:{
        getTopPos: function(el)	{
            var t = el.offsetTop + el.offsetHeight;
            while( (el = el.offsetParent) != null ) {
                t += el.offsetTop;
            }
            if (navigator.userAgent.indexOf("MSIE") && parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+4)) <= 5) {
                t -= 200;
            }
            return t;
        },
        getLeftPos: function(el) {
            var l = el.offsetLeft;
            while( (el = el.offsetParent) != null ) {
            l += el.offsetLeft;
            }
            return l;
        },
        show: function(el, div) {
            var eventAction = (div.match(/ratingkey/)) ? 'Alt Rating' : 'Facilites Key';
            var tp = AH.Key.getTopPos(el) + 5;
            var lt = AH.Key.getLeftPos(el) + 5;
            if (typeof div == 'string') div = $('#'+div);
            $(div).css({ left: lt, top: tp }).show();
            AH.Event.track(AH.Event.displayTracker, eventAction, 'Show');
        },
        hide: function(div) {
            if (typeof div == 'string') div = $('#'+div);
            $(div).hide();
        }

    },
    Availability:{
        newlocation: function(){
            $('div#search li.query').remove();
            $('div#search #searchForm ul').prepend('<li class="query"><label for="sbquery" class="sep">'+ newsearchlabeltext + ':</label><input type="text" name="query" id="sbquery"/></li>');
            $('div#search form#searchForm').attr('action',newsearchurl);
            if(!document.getElementById('availability_msg')){
                $('div#search select#nights').prepend('<option value="0" selected="selected">--</option>');
            }
            $('div#search input.btn').attr("src", function(index) { return active_image_url + 'button_search' + (this.src).substring((this.src).length-7,(this.src).length); });
            return false;
        }
    }
}

$(document).ready(function () {
    if (!document.getElementById('subfs')) {
		AH.Calendar.init();
	}
    $('#changedates').click(function () {
        $('#search').show();
        $('#availability_msg').hide();
        return false;
    });

    $('#changeloc').click(function () {
        $('#availability_msg').hide();
        $('#search').show();
        AH.Availability.newlocation();
        return false;
    });

    $('#changebrochuredates').click(function () {
        $('#enterdates').show();
        $('#availability').hide();
        return false;
    });

    $('#newloc').click(function(){
        AH.Availability.newlocation();
        return false;
    });

    $('#newsearch').click(function(){
        $('#search').show();
        if(!document.getElementById('availability_msg_top')){
            $('div#search select#nights').prepend('<option value="0" selected="selected">--</option>');
        }
        $(this).parent('div').hide();
        return false;
    });

    $('#achangedates').click(function () {
        $('#topsearch').show();
        $('#availability_msg_top').hide();
        return false;
    });

    //for ab test
    $('#bchangedates').click(function () {
        $('#search').show();
        $('#availability_msg').hide();
        return false;
    });

    if(document.getElementById('pricefilter')){
        $('input.filter_cb').click(function(){
                window.location = $(this).parent('a').attr("href");
        });
    }

    $('#searchForm2 li.dates, #searchForm2 li.nights, #searchForm2 li.rooms').css(
        {
            position: 'absolute',
            left: '-999em'
        }
    );

    $('#searchForm2 input#sbquery').focus(function () {
        $('#searchForm2 li.dates, #searchForm2 li.nights, #searchForm2 li.rooms').css(
            {
                position: 'static',
                left: 'auto'
            }
        );
    });

    $('.facilities img').removeAttr('title');

    if(document.getElementById('recent_view')){
        $('#recent_view li').mouseover(function(){
             $(this).addClass("hovered");
        });
        $('#recent_view li').mouseout(function(){
             $(this).removeClass("hovered");
        });
        $('#recent_view li').click(function(){
             document.location = $(this).children('a').attr('href');
        });
    }

    if(document.getElementById('datealert')){
        setTimeout("$('#datealert').show();",2000);

        $('.combined #search').click(function(){
            $('#datealert').hide();
            $.cookie('dateAlert', 'dontshow', { path: '/' });
        });
    }

    $('#datealert a').click(function(){
        //close box
        $('#datealert').hide();
        //set cookie to not show again
        $.cookie('dateAlert', 'dontshow', { path: '/' });
        return false;
    });

    // condense results
    if(document.getElementById('filteralert')){
        setTimeout("$('#filteralert').show();",3000);

        $('.filters li a').click(function(){
            $('#filteralert').hide();
            $.cookie('filteralert', 'dontshow', { path: '/' });
        });
    }

    $('#filteralert a').click(function(){
        //close box
        $('#filteralert').hide();
        //set cookie to not show again
        $.cookie('filteralert', 'dontshow', { path: '/' });
        return false;
    });

    //need to make this a generic function
    $('p.what').bind("click", function(e) {
        $('#socialdesc').css({top:$(this).offset().top-$('#socialdesc').height()-2,left:$(this).offset().left}).show();
        e.stopPropagation();
        $(document).one("click", function(f){
            $('#socialdesc').hide();
        });
    });

    $('#socialdesc').bind("click", function(e){
        e.stopPropagation();
    });

    if(typeof allTrafficByAggregatePageType != "undefined"){
        // Create all event trackers
        AH.Event.displayTracker = allTrafficByAggregatePageType._createEventTracker("Display");
        AH.Event.recentlyViewedTracker = allTrafficByAggregatePageType._createEventTracker("Recently Viewed");
        AH.Event.mapTracker = allTrafficByAggregatePageType._createEventTracker("Map");
        AH.Event.photoGalleryTracker = allTrafficByAggregatePageType._createEventTracker("Photo Gallery");
        AH.Event.bookingProcessTracker = allTrafficByAggregatePageType._createEventTracker("Booking Process");
        AH.Event.filterTracker = allTrafficByAggregatePageType._createEventTracker("Filter");
        AH.Event.sortTracker = allTrafficByAggregatePageType._createEventTracker("Sort");
    }

    // Bind event trackers to various events (some are also inline in other code)
    $('#recent_view a').click(function () {
        AH.Event.track(AH.Event.recentlyViewedTracker, 'Click', document.body.className);
    });
    if (document.getElementById('photogallery')) {
        var eventAction = ($('#photogallery li').length > 5) ? 'Display with scroll' : 'Display w/o scroll';
        AH.Event.track(AH.Event.photoGalleryTracker, eventAction, 'Show');
        $('#photogallery > a').click(function () {
            AH.Event.track(AH.Event.photoGalleryTracker, 'Click', 'Scroll');
        });
        $('#photogallery li a').each(function (i) {
            $(this).click(function () {
                AH.Event.track(AH.Event.photoGalleryTracker, 'Click', i + 1);
            });
        });
    }
    $('#pricefilter a').click(function () {
        var eventAction = ($(this).children('input').attr('checked')) ? 'Unchecked' : 'Checked';
        AH.Event.track(AH.Event.filterTracker, eventAction, $(this).text().replace(/^\s+/, ''));
    });
    $('#newsortby a').click(function () {
        var eventLabel = (this.className.match(/down/)) ? 'Ascending' : 'Descending';
        AH.Event.track(AH.Event.sortTracker, $(this).text().replace(/\s+$/, ''), eventLabel)
    });


});


// show / hide filters
      $(document).ready(function() {
        $('div.filters > ul[class!=open]').hide();
        $('div.filters > ul.open').prev('h3').addClass('up');
        $('div.filters > h3').click(function() {
    	    $(this).next().slideToggle('fast');
              if ($(this).hasClass('down')) {
                  $(this).removeClass('down').addClass('up');
              } else {
                  $(this).removeClass('up').addClass('down');
              }
              return false;

          });

        $('ul#quickselection li').wrapInner("<a href=" + "></a>");

        $('ul#quickselection li').click(function() {
    	    $('div.filters > ul[class!=open]').slideToggle('fast');

              if ($('div.filters > h3').hasClass('down')) {
                  $('div.filters > h3').removeClass('down').addClass('up');
              } else {
                  $('div.filters > h3').removeClass('up').addClass('down');
              }
                $('html, body').animate({ scrollTop: $("div#condenseresults").offset().top }, 'slow');
              return false;
          });

      });

