function resetTabHighlight()
{
  // reset all the tabs to no selection
  $("#description-tab-switch").removeClass('selected');
  $("#album-tab-switch").removeClass('selected');
  $("#map-tab-switch").removeClass('selected');
  $("#prices-tab-switch").removeClass('selected');
  $("#availability-tab-switch").removeClass('selected');
  $("#book-this-cottage").fadeIn('fast');
  $("#msg-choose-dates").fadeOut('fast');
  $("#property-print").fadeOut('fast');
  $("#availability-print").fadeOut('fast');
  disableLegendFix();
}

function resetTabHeights(selectedtab)
{
  // make sure all the tabs have no height so only the one selected can
  $("#description-tab").addClass('noheight');
  $("#photoalbum-tab").addClass('noheight');
  $("#map-tab").addClass('noheight');
  $("#prices-tab").addClass('noheight');
  $("#propertyavailability").addClass('noheight');
  // add height to the selected one
  $(selectedtab).removeClass('noheight');
}

function resetSubTabHighlight()
{
  // Reset all the subtabs to no selection
  $("#ataglance-tab-switch").removeClass('selected');
  $("#details-tab-switch").removeClass('selected');
  $("#features-tab-switch").removeClass('selected');
}

function enableLegendFix()
{
  // fix the calendar key to the top of the screen when the user scrolls down
  // this should only happen when the focus is on the availability tab
  // to do this need to add position: fixed to avail-key and position: absolute to avail-key-floater
  measured_offset = $("#avail-key-upper").offset().top;

  if($("#availability-tab-switch").hasClass('selected'))
  {
    $(window).scroll(function(){
      // if($(window).scrollTop()>313)
      if($(window).scrollTop()>measured_offset)
      {
        $('#avail-key-upper').addClass('floating');
        $('.avail-key-floater').addClass('floating');
      } else {
        $('#avail-key-upper').removeClass('floating');
        $('.avail-key-floater').removeClass('floating');
      }
    });
  } else {
    disableLegendFix();
  }
}

function disableLegendFix()
{
  $('#avail-key-upper').removeClass('floating');
  $('.avail-key-floater').removeClass('floating');
  
  $(window).unbind('scroll');
}

function switchMainImage(imagenum)
{
  // fade out all the other images
  $("img.mainpropertyimage").each(function(i) {
    if($(this).attr('id') != "mainimage_"+imagenum) {
      $(this).fadeOut('fast');
    }
  });
  
  $("#mainimage_"+imagenum).fadeIn('fast');
  currentmainimage = imagenum;
  imagenum++;
  $("span#currentimage").html(imagenum);
}

function imageSetup()
{
  $("img.thumbimage").click(function() {
    switchMainImage(this.id.split("_")[1]);
  })
  
  switchMainImage(0);
  
  $("a#mainimageprev").click(function() {
    nextimage = currentmainimage;
    nextimage--;
    if(nextimage==-1)
    {
      nextimage = (maximages-1);
    }
    switchMainImage(nextimage);
  })
  
  $("a#mainimagenext").click(function() {
    nextimage = currentmainimage;
    nextimage++;
    if(nextimage==maximages)
    {
      nextimage = 0;
    }
    switchMainImage(nextimage);
  })
}

function highslideSetup()
{
  $("div.photo-album-left .highslide").each(function() {
    $(this).click(function() {
      return hs.expand(this, { captionId: 'maincaption_'+parseInt(this.id.split("_")[1]), slideshowGroup: 'photoalbum' });
    });
  });

  $("div.photo-album-right .highslide").each(function() {
    $(this).click(function() {
      return hs.expand(this, { captionId: 'maincaption_'+parseInt(this.id.split("_")[1]), slideshowGroup: 'photoalbum' });
    });
  });

	$("div.property-ataglance .highslide").each(function() {
		$(this).click(function() {
      contentidprefix = this.id.split("-")[1];
			return hs.htmlExpand(this,{ contentId: contentidprefix+'-helper', captionEval: '', align: 'auto' });			
		});
	});
	
	$("div.property-availability-container .highslide").each(function() {
		$(this).click(function() {
      contentidprefix = this.id.split("-")[1];
			return hs.htmlExpand(this,{ contentId: contentidprefix+'-helper', captionEval: '', align: 'auto' });			
		});
	});
	
	// Add the quick map popup link to each of the also viewed
	$(".highslide").each(function() {
    $(this).click(function() {
	  	_gaq.push(['_trackEvent','Property','Small map viewed']);
      return hs.expand(this, { captionEval: '', align: 'auto' });
    });
  });
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

function calendarSetup()
{
  // link up all the checkboxes, so that checking one or more results in the popup describing what is selected and offering the book button
  // selecting a checkbox should also highlight the associated week on the calendar with 'selectedweek' class
  // if checkbox is on the first week of the month, it should also try and highlight the last week in the previous month if it is addressable
  // ensure that none of the checkboxes are checked upon page load
  
  $("input.smcheck").each(function(i) {
    $(this).attr('checked', false);
    $(this).attr('disabled', false);
    
    // check to see if this checkbox relates to a reserve week, if it does then style the appropriate week accordingly
    if($("span#"+this.id+"_hiddenprice").html()=="Reserve")
    {
      $("tr#cal_"+this.id+" td, tr#cal_nextweek_"+this.value+" td").addClass('reservable');
    }
    
    $(this).click(function(){
			
      // test to see if box is checked or unchecked
      // if checked, add the relevant class, if unchecked removed the class
      if($(this).is(':checked'))
      {
				_gaq.push(['_trackEvent','Property','Availability','Week marked']);
        // if a week selected which has a reserved note on it, we need to get authorisation first
        // the user must enter a password
        if($("input#extradata_"+this.id).val()=="reserved" && reservation_authd == 0)
        {
          openConfirmDialog('booking-confirmation-bar');
        }
        
        if($("input#extradata_"+this.id).val()=="christmas" && christmas_authd == 0)
        {
          openConfirmDialog('booking-christmas-bar');
        }
        
        if($("input#extradata_"+this.id).val()=="newyear" && newyear_authd == 0)
        {
          openConfirmDialog('booking-newyear-bar');
        }

        if($("input#extradata_"+this.id).val()=="proximity" && proximity_authd == 0)
        {
          openConfirmDialog('booking-proximity-bar');
        }

        if($("input#important_info_present").val()=="true" && iinfo_authd == 0)
        {
          openConfirmDialog('booking-info-bar');
        }
        
        checkedboxes++;
        
        $("tr#cal_"+this.id).addClass('selectedweek');
        
        // check to see if a partial week exists in the previous month, if so then add the class to that one too!
        if($("tr#cal_nextweek_"+this.value).length > 0) {
          $("tr#cal_nextweek_"+this.value).addClass('selectedweek');
        }
        
      } else {
				_gaq.push(['_trackEvent','Property','Availability','Week unmarked']);
        if($("input#extradata_"+this.id).val()=="reserved")
        {
          closeConfirmDialog('booking-confirmation-bar');
        }
        
        if($("input#extradata_"+this.id).val()=="christmas")
        {
          closeConfirmDialog('booking-christmas-bar');
        }
        
        if($("input#extradata_"+this.id).val()=="newyear")
        {
          closeConfirmDialog('booking-newyear-bar');
        }

        if($("input#extradata_"+this.id).val()=="proximity")
        {
          closeConfirmDialog('booking-proximity-bar');
        }
        
        checkedboxes--;
        
        $("tr#cal_"+this.id).removeClass('selectedweek');
        
        if($("tr#cal_nextweek_"+this.value).length > 0) {
          $("tr#cal_nextweek_"+this.value).removeClass('selectedweek');
        }
      }
      
      // run the week select function to control the popup
      //weekSelect(this.id);
      weekSelect();
    });
    
    // $.uniform.update();
  });
  
  // make sure the dialog is initialised and ready to rock
  // $("#property-date-selection").dialog({ 
  //   resizable: false,
  //   autoOpen: false,
  //   height: 190,
  //   width: 400,
  //   close: function() { clearSelection(); $('#book-this-cottage-button').unbind('click'); }
  //  });
}

function clearSelection()
{
  // provide a single function to reset the user selection - can be triggered via the clear button in the dialog
  // or automatically when the dialog is closed
  // uncheck all the checkboxes then call weekSelect() to update the calendars

  // checkedboxes holds the count of currently selected boxes
  $("input.smcheck").each(function(i) {
    if($(this).is(':checked'))
    {
      checkedboxes--;
    
      $("tr#cal_"+this.id).removeClass('selectedweek');
    
      if($("tr#cal_nextweek_"+this.value).length > 0) {
        $("tr#cal_nextweek_"+this.value).removeClass('selectedweek');
      }
    }
    
    $(this).attr('checked', false);
    $(this).attr('disabled', false);
    $('td#'+this.id+'_price').removeClass('disabledprice');
  });
  
  servicedboxes = 0;
  checkedboxes = 0;
  laststartsecs = 0;
  lastendsecs = 0;

	$('#book-this-cottage-button').unbind('click');
  // $.uniform.update();
}

function closeDialog()
{
	_gaq.push(['_trackEvent','Property','Availability','Dialog close']);
	var bversion = parseInt($.browser.version);
	if($.browser.msie && bversion == 6)
	{
		$("#booking-selection-bar").removeClass('ddbardown');
	} else {
		$("#booking-selection-bar").animate({"top": "-200px"}, "slow","easeInOutExpo");
	}
	clearSelection();
}

function openDialog()
{
	_gaq.push(['_trackEvent','Property','Availability','Dialog open']);
	var bversion = parseInt($.browser.version);
	if($.browser.msie && bversion == 6)
	{
		$("#booking-selection-bar").addClass('ddbardown');
	} else {
		$("#booking-selection-bar").animate({"top": "0px"}, "slow","easeOutBounce" );
	}

	// add the form submit action to the book button
	$('a#book-this-cottage-button').click(function() {
		$('#bookingcalendar').submit();
	});
	
	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod')
	{
		alert('After selecting your week(s) scroll to the top of the page to see your booking summary and to continue booking.');
	};
}

function closeConfirmDialog(whichbar)
{
	var bversion = parseInt($.browser.version);
	if($.browser.msie && bversion == 6)
	{
		$("#"+whichbar).removeClass('ddbardown');
	} else {
		$("#"+whichbar).animate({"top": "-200px"}, "slow","easeInOutExpo");
	}
}

function openConfirmDialog(whichbar)
{
	var bversion = parseInt($.browser.version);
	if($.browser.msie && bversion == 6)
	{
		$("#"+whichbar).addClass('ddbardown');
	} else {
		$("#"+whichbar).animate({"top": "0px"}, "slow","easeOutBounce" );
	}
}

function weekSelect() //checkedbox
{
  // whenever a checkbox is selected or deselected, run this function
  // things to do...
  // 1. if going from no checkboxes to 1, ensure the popup is displayed
  // 2. if going from x checkboxes to x+1 (where x != 0), ensure consecutive (maybe disable checkboxes that are not adjacent)
  // 3. update popup with correct summary of dates selected
  // 4. if going from 1 box to none, ensure the popup is cleared and checkboxes re-enabled
  
  // when reserving a property, all of the boxes should either have no price, or all the boxes should have a price
  // there should be no mix of the two types.
  var totalprice = 0;
  var reservation = false;
  $("input.smcheck:checked").each(function(i) {
    totalprice += parseInt($('span#'+this.id+'_hiddenprice').html());
    if($('span#'+this.id+'_hiddenprice').html() == 'Reserve')
    {
      reservation = true;
    }
  });
  
  var enableall = false;
  var boxchange = checkedboxes - servicedboxes; // should not be possible for change to be zero, only 1 or -1
  
  if(servicedboxes==0 && boxchange==1)
  {
    // if we get into here the popup should be created
    //$('#property-date-selection').dialog('open');
    openDialog();
  }
  
  if(servicedboxes==1 && boxchange==-1)
  {
    // if we get into here the popup should be removed
    // $('#property-date-selection').dialog('close');  
    // $("#booking-selection-bar").animate({"top": "-200px"}, "slow","easeInOutExpo" );
    // clearSelection();
    if($("input#important_info_present").val()=="true")
    {
      closeConfirmDialog('booking-info-bar');
    }
    closeDialog();
    
    // and all boxes should be enabled
    enableall = true;
  }
  
  // update the checkboxes so that only the relevant ones are enabled (do not allow user to select non consecutive weeks)
  // checkedbox has the id of the box that was checked in this instance, this means all others that are below id - 1 (but not below 0), and above id + 1 should be disabled
  // excluding those which are already ticked
  //checkedid = parseInt(checkedbox.split("_")[1]);
  $("input.smcheck").each(function(i) {

    if(enableall==false)
    {
      compareid = parseInt(this.id.split("_")[1]);
      // compareid is the current week number
      
      // if each side of this one is checked then disable
      if($('#week_'+(compareid+1)).is(':checked') && $('#week_'+(compareid-1)).is(':checked'))
      {
        $(this).attr('disabled', true)
      }
      
      // if each side of this one is not checked then disable - unless this one is checked
      else if(!$('#week_'+(compareid+1)).is(':checked') && !$('#week_'+(compareid-1)).is(':checked') && !$(this).is(':checked'))
      {
        $(this).attr('disabled', true);
        $('td#'+this.id+'_price').addClass('disabledprice');
      }
      
      // if this one isn't checked, but the next one is
      
      // if this one isn't checked, but the previous one is
      // if the previous one is more than 1 week seconds
      // make sure its disabled!
      else if((!$(this).is(':checked') && $('#week_'+(compareid-1)).is(':checked') && ($(this).val() - $('#week_'+(compareid-1)).val())>604800)
      || (!$(this).is(':checked') && $('#week_'+(compareid+1)).is(':checked') && ($('#week_'+(compareid+1)).val() - $(this).val())>604800))
      {
        $(this).attr('disabled', true);
        $('td#'+this.id+'_price').addClass('disabledprice');
      }
      else 
      {
        $(this).attr('disabled', false);
        $('td#'+this.id+'_price').removeClass('disabledprice');
      }
      
      // if this is a reservation then all those boxes that have a price should be disabled
      if(reservation == true && $('span#'+this.id+'_hiddenprice').html() != 'Reserve')
      {
        $(this).attr('disabled', true);
        $('td#'+this.id+'_price').addClass('disabledprice');
      }
      
      // if this is a booking (not a reservation), then all those boxes that do now have a price (they have the word 'reserved') should be disabled
      if(reservation == false && $('span#'+this.id+'_hiddenprice').html() == 'Reserve')
      {
        $(this).attr('disabled', true);
        $('td#'+this.id+'_price').addClass('disabledprice');
      }
      
    } else if(enableall==true) {
      $(this).attr('disabled', false);
      $('td#'+this.id+'_price').removeClass('disabledprice');
    }
  });
  
  servicedboxes = checkedboxes;
  
  // update the contents of the dialog div to show the selected date range and price
  // start date will be the value of the lowest/first checkbox
  // end date will be the value of the highest/last selected checkbox + 604800 (1w seconds)
  // store these for next time so that we can find out which ones have changed
  var startsecs = parseInt($("input.smcheck:checked:first").attr('value'));
  var endsecs = parseInt($("input.smcheck:checked:last").attr('value'))+604800;

  var startdate = new Date(startsecs*1000);
  var enddate = new Date(endsecs*1000);
	var selecteddays = (endsecs-startsecs)/86400;


	if(enableall==false)
	{
	  if(reservation==false)
	  {
      $('input#is_reservation').val('0');
	    $('div#booking-reserve-info').css('display','none');
      $('div#booking-selection-dates').css('display','block');
      
    	$('span#selected-start-date').html(weekday[startdate.getUTCDay()]+' '+ordi(startdate.getUTCDate())+' '+month[startdate.getUTCMonth()]+' '+startdate.getUTCFullYear());
    	$('span#selected-end-date').html(weekday[enddate.getUTCDay()]+' '+ordi(enddate.getUTCDate())+' '+month[enddate.getUTCMonth()]+' '+enddate.getUTCFullYear());
  		$('span#selected-duration').html(selecteddays+' nights');
  	  $('span#selected-dates-price').html('&pound;'+totalprice);
  	  
      // and the continue booking button needs to change
      $('span.booking-button-text').each(function() {
        $(this).html('Continue booking');
      });
      
      $('a.book-this-cottage span').each(function() {
        $(this).removeClass('narrow');
      });
    } else if(reservation==true)
    {
      $('input#is_reservation').val('1');
      // if this is a reservation need to change the whole layout of the dialog, not just the date fields
      $('div#booking-selection-dates').css('display','none');
      $('div#booking-reserve-info').css('display','block');
      
      $('div#booking-reserve-info').html('I would like to reserve <strong>'+currentpref+' '+currentpname+'</strong> for the <strong>'+selecteddays+' night</strong> period <strong>\
      '+ordi(startdate.getUTCDate())+' '+month[startdate.getUTCMonth()]+' '+startdate.getUTCFullYear()+' - '+ordi(enddate.getUTCDate())+' '+month[enddate.getUTCMonth()]+' '+enddate.getUTCFullYear()+'</strong>. I understand this reservation will not be confirmed unless or until Cornish Traditional Cottages receives authorisation from the owner that the property will be available for letting and prices have been agreed. I will check the description again for any changes <strong>before</strong> I confirm the booking.');
      $('span#selected-dates-price').html('To be advised');
      
      // and the continue booking button needs to change
      $('span.booking-button-text').each(function() {
        $(this).html('I agree');
      });
      
      $('a.book-this-cottage span').each(function() {
        $(this).addClass('narrow');
      });
    }
	}

  // check this against the last processed times so that if its changed we can highlight in the dialog
  if(startsecs!=laststartsecs && laststartsecs!=0)
  {
    // startsecs has changed!
    // $('span#selected-start-date').effect("highlight", { 'color':'#50617D' }, 500);    
  }
  laststartsecs = startsecs;
  
  if(endsecs!=lastendsecs && lastendsecs!=0)
  {
    // endsecs has changed!
    // $('span#selected-end-date').effect("highlight", { 'color':'#50617D' }, 500);
  }
  lastendsecs = endsecs;
}

function groupPropertySetup(startstate)
{	
	if(startstate == "open")
	{
		$('div#expand-group').hover(function() {
			$(this).html('Show only the selected property');
		},
		function() {
			$(this).html('This property is part of a group, click to show only the selected property');
		})
	
		$('div#expand-group').toggle(function() {
	  	_gaq.push(['_trackEvent','Property','Group hidden']);
			$(this).html('Show all properties in this group');
			$(this).css('background-image','url("/media/image/property/group-expand.png")');
			$('div#group-content').slideUp({easing: 'easeInOutExpo', complete: enableLegendFix});	
			$('div#expand-group').hover(function() {
				$(this).html('Show all properties in this group');
			},
			function() {
				$(this).html('This property is part of a group, click to show all properties in the group');
			})	
		},
		function() {
			$(this).html('Only show the selected property');
			$(this).css('background-image','url("/media/image/property/group-reduce.png")');
  		_gaq.push(['_trackEvent','Property','Group shown']);
			$('div#group-content').slideDown({easing: 'easeInOutExpo', complete: enableLegendFix});
			$('div#expand-group').hover(function() {
				$(this).html('Show only the selected property');
			},
			function() {
				$(this).html('This property is part of a group, click to show only the selected property');
			})
		})
	} else {
		$('div#expand-group').hover(function() {
			$(this).html('Show all properties in this group');
		},
		function() {
			$(this).html('This property is part of a group, click to show all properties in the group');
		})
	
		$('div#expand-group').toggle(function() {
			$(this).html('Only show the selected property');
			$(this).css('background-image','url("/media/image/property/group-reduce.png")');
  		_gaq.push(['_trackEvent','Property','Group shown']);
			$('div#group-content').slideDown({easing: 'easeInOutExpo', complete: enableLegendFix});	
			$('div#expand-group').hover(function() {
				$(this).html('Show only the selected property');
			},
			function() {
				$(this).html('This property is part of a group, click to show only the selected property');
			})	
		},
		function() {
			$(this).html('Show all properties in this group');
			$(this).css('background-image','url("/media/image/property/group-expand.png")');
	  	_gaq.push(['_trackEvent','Property','Group hidden']);
			$('div#group-content').slideUp({easing: 'easeInOutExpo', complete: enableLegendFix});
			$('div#expand-group').hover(function() {
				$(this).html('Show all properties in this group');
			},
			function() {
				$(this).html('This property is part of a group, click to show all properties in the group');
			})
		})
	}
}

function videoTourSetup()
{
	$('div#expand-video-player').toggle(function() {
  	_gaq.push(['_trackEvent','Property','Video tour open']);
		$(this).css('background-image','url("/media/image/property/video-reduce.png")');
		$('div#property-video-player').slideDown({easing: 'easeInOutExpo'});	
	},
	function() {
		_gaq.push(['_trackEvent','Property','Video tour close']);
		$(this).css('background-image','url("/media/image/property/video-expand.png")');
		$('div#property-video-player').slideUp({easing: 'easeInOutExpo'});
	})
}

function mapSetup()
{
  // Add the google map
  var ctcPropMap = {
    zoom: propertyZoom,
    center: propertyLocation,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("property-map"), ctcPropMap);
	
  var image = new google.maps.MarkerImage('/media/image/property/mapicon.png',
      new google.maps.Size(23, 33),
      new google.maps.Point(0,0),
      new google.maps.Point(6, 30));
  var shadow = new google.maps.MarkerImage('/media/image/property/shadow.png',
      new google.maps.Size(40, 34),
      new google.maps.Point(0,0),
      new google.maps.Point(6, 31));
	
  var marker = new google.maps.Marker({
    position: propertyLocation,
    map: map,
		icon: image,
		shadow: shadow
  });
}

function shortlistSetup()
{
  // allow simple 1 click add/remove, including updating of the list in l/h column.  
  $("li#sl-add-current span").click(function() {
  	_gaq.push(['_trackEvent','Shortlist','Property added']);
    // setup link to add the current property to the shortlist
		$.post(
			"/lib/shortlist-actions.php",
			{ id: currentpid,
				func: 'add' },
			function(data) {
        $("ul#shortlist-list").html(data.list);
        $("span#header-sl-count").html(data.count);
			},
			"json"
		);
  });

  // allow simple 1 click add/remove, including updating of the list in l/h column.
  $("div.result-detail-button.shortlist.tba").live('click',function() {
      // actions: change text to spinner
      // check if this property should be added or linked to view
      // add/redirect
			// if just added, update text to show link to shortlist
	  	_gaq.push(['_trackEvent','Shortlist','Property added']);
			pid = this.id.split("_")[2];
			$.post(
				"/lib/shortlist-actions.php",
				{ id: pid,
					func: 'add' },
				function(data) {
					// replace the button with an added one
					$("div#sl_add_"+data.pid).replaceWith('<div class="result-detail-button shortlist" id="sl_view_'+data.pid+'"><a href="'+data.url+'"><img src="/media/image/search/add-to-shortlist.jpg" alt="View Shortlist" /><span class="span-shadow">View Shortlist</span><span>View Shortlist</span></a></div>');

          $("ul#shortlist-list").html(data.list);
          $("span#header-sl-count").html(data.count);
				},
				"json"
			);
  });
}

function importantInfoDD()
{
	// important info verification stuff
  $('input#info-understood').attr('checked', false);
  $('input#info-understood').click(function(){
		if($(this).is(':checked'))
    {
        $('img#info-confirm-img-disabled').fadeOut('fast');
        $('img#info-confirm-img').fadeIn('fast');
        $('a#confirm-info-entry-button').removeClass('disabled');
        iinfo_authd = 1;
      	$('a#confirm-info-entry-button').click(function() {
          closeConfirmDialog('booking-info-bar');
      	});
    } else {
        $('img#info-confirm-img').fadeOut('fast');
        $('img#info-confirm-img-disabled').fadeIn('fast');
        $('a#confirm-info-entry-button').addClass('disabled');
        $('a#confirm-info-entry-button').unbind('click'); 
        iinfo_authd = 0;
    }
  });
}

$(document).ready(function(){
  // define some vars
  checkedboxes = 0;
  servicedboxes = 0;
  laststartsecs = 0;
  lastendsecs = 0;
  currentmainimage = 0;
  reservation_authd = 0;
  proximity_authd = 0;

	// The christmas and new year authentication
	// if these are 0 here then the box will be displayed to the user for confirmation
  christmas_authd = 1;
  newyear_authd = 1;

	iinfo_authd = 0;
  maximages = parseInt($("span#totalimages").html());
  measured_offset = $("#avail-key-upper").offset().top;
  // $('div.avail-calendar-container input[type=checkbox]').uniform();
  
  month=new Array(12);
  month[0]="January";
  month[1]="February";
  month[2]="March";
  month[3]="April";
  month[4]="May";
  month[5]="June";
  month[6]="July";
  month[7]="August";
  month[8]="September";
  month[9]="October";
  month[10]="November";
  month[11]="December";

	weekday=new Array(7);
	weekday[0]="Sunday";
	weekday[1]="Monday";
	weekday[2]="Tuesday";
	weekday[3]="Wednesday";
	weekday[4]="Thursday";
	weekday[5]="Friday";
	weekday[6]="Saturday";
  
  // run startup functions
  calendarSetup();
  mapSetup();
  imageSetup();
  highslideSetup();
  shortlistSetup();

	$("div#selection-close-button").click(function() {
		closeDialog();
	});
	
	$("div#confirm-close-button").click(function() {
		closeConfirmDialog('booking-confirmation-bar');
		closeDialog();
	});
	
	$("div#prox-close-button").click(function() {
		closeConfirmDialog('booking-proximity-bar');
		closeDialog();
	});
	
	$("div#christmas-close-button").click(function() {
		closeConfirmDialog('booking-confirmation-bar');
		closeConfirmDialog('booking-christmas-bar');
		closeDialog();
	});
	
	$("div#newyear-close-button").click(function() {
		closeConfirmDialog('booking-newyear-bar');
		closeConfirmDialog('booking-christmas-bar');
		closeConfirmDialog('booking-confirmation-bar');
		closeDialog();
	}); // todo, sepearate the alert/confirm boxes so that when using the close button, only the appropriate check is removed
	
	$("div#info-close-button").click(function() {
		closeConfirmDialog('booking-newyear-bar');
		closeConfirmDialog('booking-christmas-bar');
		closeConfirmDialog('booking-confirmation-bar');
		closeConfirmDialog('booking-info-bar');
		closeDialog();
	});
	
	// reserved verification stuff
	$('input#reserve-verification').val('');
  $('input#reserve-verification').keyup(function() {
    var str = $('input#reserve-verification').val().toLowerCase();
    if(str == 'ctc') // this should be a proper check via ajax - tba
    {
        $('img#code-confirm-img-disabled').fadeOut('fast');
        $('img#code-confirm-img').fadeIn('fast');
        $('a#confirm-code-entry-button').removeClass('disabled');
        reservation_authd = 1;
        $('input#verification_code').val(str);
      	$('a#confirm-code-entry-button').click(function() {
          closeConfirmDialog('booking-confirmation-bar');
      	});
    } else {
        $('img#code-confirm-img').fadeOut('fast');
        $('img#code-confirm-img-disabled').fadeIn('fast');
        $('a#confirm-code-entry-button').addClass('disabled');
        $('a#confirm-code-entry-button').unbind('click'); 
        $('input#verification_code').val();
        reservation_authd = 0;       
    }
  });

	// proximity verification stuff
	$('input#prox-verification').val('');
  $('input#prox-verification').keyup(function() {
    var str = $('input#prox-verification').val().toLowerCase();
    if(str == 'ctc') // this should be a proper check via ajax - tba
    {
        $('img#prox-confirm-img-disabled').fadeOut('fast');
        $('img#prox-confirm-img').fadeIn('fast');
        $('a#confirm-prox-entry-button').removeClass('disabled');
        proximity_authd = 1;
        $('input#verification_code').val(str);
      	$('a#confirm-prox-entry-button').click(function() {
          closeConfirmDialog('booking-proximity-bar');
      	});
    } else {
        $('img#prox-confirm-img').fadeOut('fast');
        $('img#prox-confirm-img-disabled').fadeIn('fast');
        $('a#confirm-prox-entry-button').addClass('disabled');
        $('a#confirm-prox-entry-button').unbind('click'); 
        $('input#prox-verification').val();
        proximity_authd = 0;       
    }
  });
  
  // christmas verification stuff
  $('input#christmas-understood').attr('checked', false);
  $('input#christmas-understood').click(function(){
    if($(this).is(':checked'))
    {
      $('img#christmas-confirm-img-disabled').fadeOut('fast');
      $('img#christmas-confirm-img').fadeIn('fast');
      $('a#confirm-christmas-button').removeClass('disabled');
      christmas_authd = 1;
    	$('a#confirm-christmas-button').click(function() {
        closeConfirmDialog('booking-christmas-bar');
    	});
    } else {
      $('img#christmas-confirm-img').fadeOut('fast');
      $('img#christmas-confirm-img-disabled').fadeIn('fast');
      $('a#confirm-christmas-button').addClass('disabled');
      $('a#confirm-christmas-button').unbind('click'); 
      christmas_authd = 0;
    }
  });
  
  // new year verification stuff
  $('input#newyear-understood').attr('checked', false);
  $('input#newyear-understood').click(function(){
    if($(this).is(':checked'))
    {
      $('img#newyear-confirm-img-disabled').fadeOut('fast');
      $('img#newyear-confirm-img').fadeIn('fast');
      $('a#confirm-newyear-button').removeClass('disabled');
      newyear_authd = 1;
    	$('a#confirm-newyear-button').click(function() {
        closeConfirmDialog('booking-newyear-bar');
    	});
    } else {
      $('img#newyear-confirm-img').fadeOut('fast');
      $('img#newyear-confirm-img-disabled').fadeIn('fast');
      $('a#confirm-newyear-button').addClass('disabled');
      $('a#confirm-newyear-button').unbind('click'); 
      newyear_authd = 0;
    }
  });
  
  $("div#tabscroller").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
  $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
  //$("div#tabscroller").animate({"height": "625px"}, { queue:false, duration:500});
  $("#description-tab-switch").addClass('selected');
  $("#ataglance-tab-switch").addClass('selected');
  $("div#propertydescscroller").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
  $("div#property-mainimagescroller").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
  
  // Set all the tabs not in view to be 0 height
  $("#photoalbum-tab").addClass('noheight');
  $("#map-tab").addClass('noheight');
  $("#prices-tab").addClass('noheight');
  $("#propertyavailability").addClass('noheight');
  
  // when document ready, attach the onclick events to the main tab buttons
  $("#description-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Description']);
    // blow up the height of the div to specified height
    //$("div#tabscroller").animate({"height": "625px"}, { queue:false, duration:500});
    // switch to the description tab
    $("div#tabscroller").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    // switch to the property detail tab (not the availability)
    $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetTabHeights("#description-tab");
    // highlight the correct tab
    resetTabHighlight();
    $(this).addClass('selected');
	  setTimeout(function() { $("#property-print").fadeIn('fast'); }, 500);
})
  
  $("#album-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Photo album']);
    //$("div#tabscroller").animate({"height": "788px"}, { queue:false, duration:500});
    $("div#tabscroller").scrollTo(678,{ duration:500, axis:'x', easing:'easeInOutExpo'});
    $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetTabHeights("#photoalbum-tab");
    resetTabHighlight();
    $(this).addClass('selected');
  })
  
  $("#map-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Map']);
    //$("div#tabscroller").animate({"height": "500px"}, { queue:false, duration:500});
    $("div#tabscroller").scrollTo(1356,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetTabHeights("#map-tab");
    resetTabHighlight();
    $(this).addClass('selected');
  })
  
  $("#prices-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Prices']);
    //$("div#tabscroller").animate({"height": "1240px"}, { queue:false, duration:500});
    $("div#tabscroller").scrollTo(2034,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetTabHeights("#prices-tab");
    resetTabHighlight();
    $(this).addClass('selected');
  })
  
  $("#availability-tab-switch,#book-this-cottage").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Availability']);	
    //$("div#tabscroller").animate({"height": "200px"}, { queue:false, duration:500});
    //$("div#propertyviewer").animate({"height": "740px"}, { queue:false, duration:500});
    $("div.property-main-content").scrollTo(944,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    setTimeout('resetTabHeights("#propertyavailability")',500);
    resetTabHighlight();
    $("#availability-tab-switch").addClass('selected');
    $("#book-this-cottage").fadeOut('fast');
    $("#msg-choose-dates").fadeIn('fast');
	  setTimeout(function() { $("#availability-print").fadeIn('fast'); }, 500);
    enableLegendFix();
  })
  
  $("#ataglance-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','At a glance']);	
    $("div#propertydescscroller").scrollTo(0,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetSubTabHighlight();
    $(this).addClass('selected');
  })

  $("#details-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Details']);
    $("div#propertydescscroller").scrollTo(329,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetSubTabHighlight();
    $(this).addClass('selected');
  })
  
  $("#features-tab-switch").click(function(){
 		_gaq.push(['_trackEvent','Property','Tabs used','Features']);
    $("div#propertydescscroller").scrollTo(658,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetSubTabHighlight();
    $(this).addClass('selected');
  })

  $("#mainimageenlarge").click(function(){
    //$("div#tabscroller").animate({"height": "788px"}, { queue:false, duration:500});
    // resetTabHeights("#photoalbum-tab");
    // $("div#tabscroller").scrollTo(678,{ duration:500, axis:'x' });
    // $("div.property-main-content").scrollTo(0,{ duration:500, axis:'x' });
    // resetTabHighlight();
    // $("#album-tab-switch").addClass('selected');
		// open the highslide viewer from the photo album tab
		
		hs.expand(document.getElementById('largeimage_'+currentmainimage),{ slideshowGroup: 'mainimages', anchor: 'top right', targetX: 'expandtarget -558px', targetY: 'expandtarget 5px' });
  })
  
  $("#ataglance-readmore").click(function(){
    $("div#propertydescscroller").scrollTo(329,{ duration:500, axis:'x', easing:'easeInOutExpo' });
    resetSubTabHighlight();
    $("#details-tab-switch").addClass('selected');
  })
});

function ordi(n){
var s='th';
if(n===1 || n==21 || n==31) s='st';
if(n===2 || n==22) s='nd';
if(n===3 || n==23) s='rd';
return n+s;
}

