window.glo = {};

window.montageConfig = {
	nonAvailIsClickable: true
};

window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}};

function trimZero( s ) {
	return s.replace( /^0(\d)\/0(\d)\/(\d+)/mg, '$1/$2/$3').replace( /^0/, '').replace( /(\d+)\/0(\d+)\/(\d+)/, '\$1/\$2/\$3'  )
	//return s.replace(/^0(\d)\/0(\d)\/\d{4}/
	//return s.replace(/^0/, '');
}

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months;
}

	$.fn.clickableCalendar = function( options ) {

		log('clickableCalendar invoked......')

		var context = this,
			opts = {
				arriveInput:false,
				departInput:false,
				pairs:false,
				callback:false,
				unitPage:false,
				preselect:false,
				generateSubmit:false
			},
			arrival = {},
			departure = {};

		window.arrival = arrival;
		window.departure = departure;
		window.opts = opts;
		window.context = context;

		if ( options ) {
			opts = $.extend( opts, options );
		}

		if ( opts.arriveInput.length == 1 && opts.departInput.length == 1 ) {
			pairs = $(opts.arriveInput).add( opts.departInput )

				if ( 
						opts.preselect && 
						$(opts.arriveInput).val() != '' && 
						$(opts.departInput).val() != '' &&
						$(opts.arriveInput).attr('format') &&
						$(opts.departInput).attr('format')
				   ) {

					var arriveDate = $.datepicker.parseDate( $(opts.arriveInput).attr('format'), $(opts.arriveInput).val() ),
						arriveFormatted = $.datepicker.formatDate('m/d/yy', arriveDate ),
						arriveCell = $(context).find('td[date="' + arriveFormatted + '"]'),
						arriveDayNum = $(arriveCell).length ? $(arriveCell).attr('day') : false,

						departDate = $.datepicker.parseDate( $(opts.departInput).attr('format'), $(opts.departInput).val() ),
						departFormatted = $.datepicker.formatDate('m/d/yy', departDate ),
						departCell = $(context).find('td[date="' + departFormatted + '"]'),
						departDayNum = $(departCell).length ? $(departCell).attr('day') : false;

					arrival.time = arriveDate.valueOf();
					arrival.lastEvent = 'preset';
					arrival.tableCell = arriveCell;
					arrival.dayNum = arriveDayNum;

					departure.time = departDate.valueOf()
						departure.lastEvent = 'preset';
					departure.tableCell = departCell;
					departure.dayNum = departDayNum;

					initialSelection()
						departureSelection()

				}
		}

		$(this).click(function(e) {
				var el = e.target;


				if ( $(el).is('span') ) {
					el = $(el).closest('td')
				} 

				window.el = el;

				var t = $(el).closest('div.table'), cal = t.closest('.calendar'), months = cal.data('months');
				window.t = t;

				// Make sure its selectable and available
				if ( !$(el).is('td.ava') || !$(el).attr('date') ) {
					return;
				}

				var ts = new Date( $(el).attr('date') ).valueOf()

				if ( departure.lastEvent && departure.lastEvent == 'invalidSelection' ) {
					if ( window.console ) console.log( 1 )

					if ( 
						t.closest('div.table').nextAll('div').length &&
						(el[0] ==  t.find('.ava:last')[0]) &&
						t[0] !== months.currentMonth
					) {
						$('.next-month').trigger( 'click' )
					}

					var dayNum = n($(el).attr('day'));

					if ( true || dayNum > arrival.dayNum ) { // BUG FIXED RECENTLY: the condition should always be assumed to be true, we should not need to do dayNum comparison.
						arrival.time = ts;
						arrival.lastEvent = 'click';
						arrival.tableCell = el;
						arrival.dayNum = dayNum;
						clearSelected()
						initialSelection()
						updateArrival()
						delete departure.lastEvent;
					}

				} else if ( !arrival.time && !departure.time ) {
					if ( window.console ) console.log( 2 )
					if ( window.console ) console.log( $(el).closest('div.table').nextAll('div').length )

					if ( 
						t.closest('div.table').nextAll('div').length && 
						(el[0] ==  t.find('.ava:last')[0]) &&
						t[0] !== months.currentMonth

					) {
						$('.next-month').trigger( 'click' )
					}

					arrival.time = ts;
					arrival.lastEvent = 'click';
					arrival.tableCell = el;
					arrival.dayNum = n($(el).attr('day'));

					initialSelection()
					updateArrival()

				} else if ( arrival.time && !departure.time && arrival.time != ts ) {
					if ( window.console ) console.log( 3 )

					departure.time = ts;
					departure.lastEvent = 'click';
					departure.tableCell = el;
					departure.dayNum = n($(el).attr('day'))

						fixOrdering()

						window.validDates = validDates;

						if ( validDates() ) {
								departureSelection()
								updateArrival()
								updateDeparture()

								if ( opts.generateSubmit ) {
									generateSubmit( opts.generateSubmit )
								}
						} else {
								delete departure.time
								delete departure.tableCell
								delete departure.dayNum
								departure.lastEvent = 'invalidSelection'
								$(el).trigger('click')
								if ( t.closest('div.table').nextAll('div').length && (el[0] ==  t.find('.ava:last')[0]) ) {
									$('.next-month').trigger( 'click' )
								}
						}

				} else if ( arrival.time && !departure.time && arrival.time == ts ) {
				} else if ( arrival.time && departure.time ) {

					if ( window.console ) console.log( 4 )
					if ( window.console ) console.log( $(el).closest('div.table').nextAll('div').length )

					if ( 
						t.closest('div.table').nextAll('div').length && 
						(el[0] ==  t.find('.ava:last')[0]) &&
						t[0] !== months.currentMonth
					) {
						$('.next-month').trigger( 'click' )
					}

						delete departure.time
						delete departure.tableCell
						delete departure.dayNum
						delete departure.lastEvent
						arrival.time = ts;
						arrival.lastEvent = 'click';
						arrival.tableCell = el;
						arrival.dayNum = n($(el).attr('day'));

						clearSelected()
						initialSelection()
						updateArrival()
						clearDeparture()
						hideSubmit( opts.generateSubmit )
				}

				if ( window.console ) console.log( [ arrival.lastEvent, departure.lastEvent ] )
		})

		var par, cell , startIndex, endIndex, diff, slices;

		function generateSubmit( el ) {
			log('generateSubmit invocation')
			window.god = el;
			//var form = $(context).siblings('form');
			if ( el.length && $(el).find('.check-rates').length == 0 ) {
				$('<input type="submit" value="Check Rates for Dates Selected" class="check-rates button-image">').appendTo( el )
			} else {
				$(el).find('.check-rates').show()
			}
		}

		function hideSubmit( el ) {

			if ( el.length ) {
				$(el).find('.check-rates').hide()
			}
		}

		function validDates() {
			par = $(arrival.tableCell).closest('.calendar'), cells = par.find('td'), startIndex = cells.index( arrival.tableCell ), endIndex = cells.index( departure.tableCell ), diff = endIndex - startIndex, slices = cells.slice( startIndex, endIndex );

			var ret = true;
			slices.each(function() {
				var td = $(this);
				if ( !$(td).is('td.ava') && !$(td).is('td.default') && !$(td).is('td.way-past') ) {
					ret = false;
					return false;
				}
			});

			return ret;

			for ( var startCell = n(arrival.dayNum); startCell < n(departure.dayNum); startCell++ ) {
				var td = $('td[day="' + startCell + '"]', context);
				if ( !$(td).is('td.ava') && !$(td).is('td.default') && !$(td).is('td.way-past') ) {
					return false;
				}
			}
			return true;
		}

		function fixOrdering() {
			var tempArrival = arrival, tempDeparture = departure;

			if ( arrival.time > departure.time ) {
			//if ( n(tempArrival.dayNum) > n(departure.dayNum) ) {
				arrival = tempDeparture;
				departure = tempArrival;
			}
		}

		function initialSelection() {
			$(arrival.tableCell).addClass('selected')
			$(context).parent().find('.arrival-span').prependTo(arrival.tableCell).css('display', 'block')
			$(arrival.tableCell).addClass('selected-starting');
		}

		function clearSelected() {
			$('td.selected,td.selected-starting,td.selected-ending', context).removeClass('selected').removeClass('selected-starting').removeClass('selected-ending')
			$('span.arrival-span,span.departure-span').hide();
		}

		function n( n ) {
			return parseInt( n, 10 )
		}

		function departureSelection() {

			log('new departure selekt')

			slices.each(function() {
				if ( $(this).is('.ava') ) {
					$(this).addClass('selected')
				}
			});

			/*
			for ( var startCell = n(arrival.dayNum); startCell < n(departure.dayNum); startCell++ ) {
				var td = $('td[day="' + startCell + '"]', context);
				if ( $(td).is('.ava') ) {


					$(td).addClass('selected')

				}
			}
			*/

			$(departure.tableCell).addClass('selected').addClass('selected-ending');

			//$('.departure-span').prependTo(departure.tableCell).css('display', 'block')
			$(context).parent().find('.departure-span').prependTo(departure.tableCell).css('display', 'block')

			//$('.arrival-span').prependTo(arrival.tableCell).css('display', 'block')
			$(context).parent().find('.arrival-span').prependTo(arrival.tableCell).css('display', 'block')
			$(arrival.tableCell).addClass('selected-starting');
		}

		function updateArrival() {
			if ( $(opts.arriveInput).length ) {
				$(opts.arriveInput).show();
				$(opts.arriveInput).val(
						$.datepicker.formatDate( $(opts.arriveInput).attr('format'), new Date( arrival.time ))
						)
			}
		}

		function updateDeparture() {
			if ( $(opts.departInput).length ) {
				$(opts.departInput).show();
				$(opts.departInput).val(
						$.datepicker.formatDate( $(opts.departInput).attr('format'), new Date( departure.time ))
						)
			}
		}

		function clearDeparture() {
			$(opts.departInput).val('')
			$(opts.departInput).hide();
		}

		function clearArrival() {
			$(opts.arriveInput).val('')
			$(opts.arriveInput).hide();
		}
	}

	function buildNextYear(currentYear){
		//arry of months
		var allMonths = [ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" ];
		var newYear = $('<ul/>').attr({id: "year-"+(currentYear+1), 'class': "clear-float active"});
		$.each(allMonths,function(index, value){
 			newYear.append('<li class="'+value+'-available available" rel="'+(index+1)+'-'+(currentYear+1)+'"><a href="#"><em class="alt">'+value+'</em></a></li>');
		});
		return newYear;
	}

$(function() {

	$.fn.tog = function( s ) {
		if ( $.browser.msie ) {
			return $(this).show();
		} else {
			return $(this).hide().fadeIn('slow')
		}
		//if ( s == 'on' ) {
	}

	$.fn.calendarToggle = function() {

		var context = this;

		$(this).each(function() {

				var datesSelected, p, months;;//, firstMonth, currentMonth, secondMonth, lastMon;

				//log('thingu')
				//log( $(this).find('div.table:not(.alt)').length )

				//var 
					datesSelected = $(this).find('td.selected')
					, p = this;

				//window.context = context;
				$(context).data('months', {});
				months = $(context).data('months');
				//window.mun = months;

				months.firstMonth = datesSelected.length ? $(datesSelected).eq(0).closest('.table')[0] : $('div.table:not(.alt)', this)[0];
				months.currentMonth = datesSelected.length ? $(datesSelected).eq(0).closest('.table')[0] : $('div.table:not(.alt)', this)[0];
				months.secondMonth = $(months.firstMonth).next().length ? $(months.firstMonth).next()[0] : false;
				months.lastMon = $('div.table:last', this).get(0);

				/*
					, firstMonth = currentMonth = datesSelected.length ? $(datesSelected).eq(0).closest('.table')[0] : $('div.table:not(.alt)', this)[0]
					, secondMonth = $(firstMonth).next().length ? $(firstMonth).next()[0] : false
					, lastMon = $('div.table:last', this).get(0);
					*/

				if ( months.currentMonth == months.lastMon ) {
				//if ( currentMonth == lastMon ) {
					months.secondMonth = months.currentMonth;
					//secondMonth = currentMonth;
					//currentMonth = $(currentMonth).prev()[0]
					months.currentMonth = $(months.currentMonth).prev()[0];

					months.firstMonth = months.currentMonth;
					//firstMonth = currentMonth
				} 

				$( months.firstMonth ).removeClass('alt').tog().prevAll().addClass('alt')

				//$(firstMonth).removeClass('alt').tog().prevAll().addClass('alt')

				if ( $(months.secondMonth) ) {
					$(months.secondMonth ).removeClass('alt').tog().nextAll().addClass('alt');
				//if ( secondMonth ) {
					//$(secondMonth).removeClass('alt').tog().nextAll().addClass('alt');
				}

				/*
				window.datesSelected = datesSelected;
				window.firstMonth = firstMonth;
				window.secondMonth = secondMonth;
				window.lastMon = lastMon;
				window.currentMonth = currentMonth;
				*/

				window.m = months;

				$('a.previous-month, a.next-month', this).click(function(e) {

					var ajaxing = false, scroller = $(this).closest('.calendar').siblings('#month-scroller');

					if ( window.console ) console.log (  'prev mon, next mon' )

						e.preventDefault()

						var isJan, isDec;

						//firstMonth = currentMonth = $('.table:not(.alt)', p)[0];
						months.secondMonth = $(months.currentMonth).next().length ? $(months.currentMonth).next()[0] : false;
						//secondMonth = $(currentMonth).next().length ? $(currentMonth).next()[0] : false;

						if ( $(this).is('.next-month') ) { // next
							isDec = $( months.secondMonth ).find('.month-december').length > 0;

							if ( isDec ) {
								scroller.find('.jump.next').trigger('click')
								log('month is december, so clicking on JUMP to next year')
								return false;
							}

							log('kk3232luger');
							if ( months.secondMonth != months.lastMon ) {
							//if ( secondMonth != lastMon ) {
								log('luger1')
								$( months.secondMonth ).next().removeClass('alt').tog()
								//$( secondMonth ).next().removeClass('alt').tog()
								$( months.currentMonth ).addClass('alt');
								months.currentMonth = months.secondMonth;
								months.secondMonth = $( months.secondMonth ).next()[0];
								setTimeout(function() {
									//if ( window.console ) console.log( $(months.currentMonth).text() )
								}, 5000 );
								if ( months.secondMonth == months.lastMon ) {
									//$('.next-month', p).css('visibility', 'hidden');
								}
							} else if ( months.secondMonth == months.lastMon ) {
								log('luger2')

								ajaxing = true;

								if ( !$(context).data('ajaxing') ) {

									$(context).data('ajaxing', true );

									grabMonths(

										//$(secondMonth).find('.ava:last').attr('date')
										$(months.secondMonth).find('td:not(.default):last').attr('date')
										
										, 5

										, function() {
											$( months.secondMonth ).next().removeClass('alt').tog()
											//$( secondMonth ).next().removeClass('alt');
											$( months.currentMonth ).addClass('alt');
											months.currentMonth = months.secondMonth;
											months.secondMonth = $( months.secondMonth ).next()[0];
											$(months.secondMonth).nextAll().addClass('alt');
											months.lastMon = $(months.secondMonth).parent().find('div:last')[0]

											if ( months.currentMonth != months.firstMonth ) {

												$('.previous-month', p).css('visibility', 'visible').removeClass('preload');

												/*
												$('.previous-month', p).animate({
													'background-position-x': -131+"px",
													'background-position-y': -168+"px"
													}, 2000, function() {
														$(this).removeClass("preload");
												});*/

											}

											$(context).data('ajaxing', false );

											var selector = $(months.currentMonth).find('.months th'), value, li;
											if ( selector.length ) {
												value = selector.attr('rel')//, year = value.split('-')[1], ul = $('ul[id="year-' + '2011' + '"]');
												window.value = value;
												var wrap = $(months.currentMonth).closest('.calendar-wrap');
												if ( wrap.length ) {
													// since #month-scroller was given an ID and not class names i have to makeup for multiple instances
													// dont have any time to redo it to use classes..
													li = $(months.currentMonth).closest('.calendar-wrap').find('#month-scroller li[rel="' + value + '"]' );
												} else {
													li = $('#month-scroller li[rel="' + value + '"]' );
												}
												li.trigger('click')
											}

										},

										context
									);
								}
							}

							if ( months.secondMonth !== months.lastMon ) {

									/*
									$('.previous-month', p).animate({
											'background-position-x': -131+"px",
											'background-position-y': -168+"px"
											}, 1000, function() {
											$(this).removeClass("preload");
											$('.previous-month').css('visibility', 'visible');
											});
									*/

									$('.previous-month', p).css('visibility', 'visible').removeClass('preload');
							}

						// previous month
						} else {

							if ( $(months.currentMonth).prev().length ) {

								isJan = $( months.currentMonth ).find('.month-january').length > 0;

								$(months.currentMonth).prev().removeClass('alt').tog()
								$( months.secondMonth ).addClass('alt');
								months.secondMonth = months.currentMonth;
								months.currentMonth = $(months.currentMonth).prev()[0];

								if ( $(months.currentMonth).prev().length == 0 ) {
									$('.previous-month', p).css('visibility', 'visible').removeClass('preload');

									/*
									$('.previous-month', p).animate({
										'background-position-x': -131+"px",
										'background-position-y': -168+"px"
										}, 2000, function() {
											$(this).removeClass("preload");
									});
									*/
								}


								if ( isJan ) {

									var ev = jQuery.Event('click')
										ev.curMonth = 'nov-available';

									log('month is january, so clicking on JUMP to next year')
									scroller.find('.jump.prev').trigger( ev )
								}

							}

							$('.next-month', p).css('visibility', 'visible');

							if ( months.currentMonth == months.firstMonth ) {
								$('.previous-month', p).css('visibility', 'hidden');
							}

							/*
							var ev = jQuery.Event('click')
								ev.thing = 'prev';

							scroller.find('ul.active li.available a').eq(0).trigger( ev )
							*/
							var tm = $( m.currentMonth ).find('th[rel]').attr('rel')

						}

						// trigger

						if ( !ajaxing && !isJan ) {
							var selector = $(months.currentMonth).find('.months th'), value, li;
							if ( selector.length ) {
								value = selector.attr('rel')//, year = value.split('-')[1], ul = $('ul[id="year-' + '2011' + '"]');
								window.value = value;
								var wrap = $(months.currentMonth).closest('.calendar-wrap');
								if ( wrap.length ) {
									// since #month-scroller was given an ID and not class names i have to makeup for multiple instances
									// dont have any time to redo it to use classes..
									li = $(months.currentMonth).closest('.calendar-wrap').find('#month-scroller li[rel="' + value + '"]' );
								} else {
									li = $('#month-scroller li[rel="' + value + '"]' );
								}
								window.li = li;
								li.trigger('click')
							}
						}
				});

				if ( $(months.currentMonth).prev().length ) {

					$('.previous-month', p).css('visibility', 'visible').removeClass('preload');

					/*
					$('.previous-month', p).animate({
						'background-position-x': -131+"px",
						'background-position-y': -168+"px"
						}, 2000, function() {
							$(this).removeClass("preload");
					});
					*/
				}

				if ( months.currentMonth == months.firstMonth ) {
					$('.previous-month', p).css('visibility', 'hidden');
				}

				if ( months.secondMonth == months.lastMon ) {
					//grabMonths( $(secondMonth).find('.ava:last').attr('date'));
					//$('.next-month', p).css('visibility', 'hidden');
				}

		});
	}

	$('div.calendar table td').live("mouseover", function() {
		$(this).addClass("hover");
	}).live("mouseout", function() {
		$(this).removeClass("hover");
	});

	$('#open-promo').each(function() {
		var h = $(this).html();
		$(this).data( 'html', h );
	});

	/*
	$('#reservations-console.beta #adult, #reservations-console.beta #child').change(function(e) {
		e.preventDefault();

		grabCalendar({adultskids:true});
	});
	*/

	var touched = false;

	$('a.clear-code').click(function(e) {
		var el = this;
		$('#open-promo').html( $('#open-promo').data('html') ).removeClass('applied')
		$('.table-container .promo').removeClass('promo')
		touched = false;
		// revert
		$('#check-loader').show();
		$(el).hide();

		if ( $('#promo-console').is(':visible') )
			$('#close-promo').trigger('click')

		checkDates(function() {
			$('#check-loader').hide();
			$('#calendar-wrap').hideIt();
			$('#promocode').val('')
		});
		return false;
	});

	//booking console
	function reformat( s ) {
		return s;
		//if ( window.console ) console.log( s )
		var temp = s.split('/');
		return temp[2] + '-' + temp[0] + '-' + temp[1];
	}

	function grabMonths( d, totalmonths, callback, context ) {

		log('grabMonths')

		$('#check-loader,#check-bg').show();

			if ( window.console ) console.log( d )

			d = new Date(d);
			//d.setMonth ( d.getMonth() + 1 )
			d.setDate ( d.getDate() + 1 )
			//d.setDate( 1 )

			window.d = d;

			var a = (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear();

			d.setMonth( d.getMonth() + totalmonths )

			var e = (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear();

			var query = 'arrive=' + a + '&depart=' + e;

			query+= '&months='+(totalmonths+1);

			if ( $('#promocode').val() ) {
				query+= '&promo=' + $('#promocode').val()
			}

			var request = $.ajax({
				url:'/direct/calendars.php',
				cache:false,
				data:query,
				dataType:'json',
				success:function( json ) {

					//$('#booking-console').addClass('open');
					//$('body').addClass('console-opened');

					window.json = json;

					if ( json.success ) {

						//if ( window.console ) console.log( request.getResponseHeader('Content-Length') );

						//$('#check-loader').hide();

						//$('#check-bg').hide();

						var container = $(context).find('.table-container');
						if ( !container.length ) {
							container = $(context).find('.table-container-perma');
						}
						var width = container.width();
						//var container = $('#calendar-wrap div.table-container'), width = container.width();
						//alert( container.css('width') )

						// chrome bug due to whitespace and appending/rendering/inline-block, etc.. just set an explicit width basically

						var html = $(json.html);

						html.slice(1).appendTo(container)

						//alert( container.css('width') )
						//if ( container.css('width') == 'auto' ) {
							container.css('width', width+'px');
						//}

						//$('#calendar-wrap').fadeIn('fast');

						if ( callback )
							callback();

						$('#check-loader').hide();
						$('#check-bg').show();

						$('.not-available').not('.past').addClass('ava');

						/*
						$('.table-container').empty();
						$('.table-container').clickableCalendar({
							arriveInput:$('.date-begin'),
							departInput:$('.date-end'),
							generateSubmit:$('#calendar-wrap .calendar-meta-info')
						});
						$('.calendar').calendarToggle()
						*/

					} else if ( json['status']) {

						log('ttt')

						glo.gettin = false;

						if ( json['status'] == 'no Success?' ) {
							/*
							$('#stay-date p').text('No dates available for ' + json.arrive + ' through ' + json.departure );
							$('#stay-date').show();
							*/
						} else {
							$('#stay-date p').text( json['status'] );
							$('#stay-date').show();
						}

						//alert('thing')
						$('#check-loader').hide();
						$('#check-bg').show();

						if ( json['status'] != 'no Success?' ) {
							$('#calendar-wrap').showIt()
						}

						$('#open-promo').html( $('#open-promo').data('html') ).removeClass('applied')

					}

				}
			})
	}

	function checkDates( callback ) {

		log('checkDates');

		/*
		$('.table-container .promo').removeClass('promo');
		$('.table-container .minstay').removeClass('minstay');
		*/

		var request, query = 'one=two', a = $('#arrive').val(), d = $('#depart').val(), ad = $('#adult').val(), c = $('#child').val();

		window.c = c;
		window.ad = ad;

		if ( $('#promocode').val().length ) {
			//query+= '&promo=' + $('#promocode').val();
		}

		if ( $('#groupcode').val().length ) {
			//query+= '&groupcode=' + $('#groupcode').val();
		}

		if ( a ) {
			query+= '&arrive=' + reformat(a)
		}

		if ( $('#depart').val().length ) {
			//query+= '&depart=' + reformat(d)
		}

		query+= '&depart=' + $('.table-container td:not(.default)').not('.way-past').slice(-1).attr('date')
		query+= '&arrive=' + $('.table-container td:not(.default)').not('.way-past').eq(0).attr('date')

		if ( ad ) {
			query+= '&adult=' + reformat(ad)
		}

		if ( c ) {
			query+= '&child=' + reformat(c)
		}

		query+= '&daycheck=true';

		window.request = request;

		request = $.ajax({
			url:'/direct/calendars.php',
			cache:false,
			data:query,
			dataType:'json',
			success:function( json ) {

				//$('#booking-console').addClass('open');

				window.json = json;

				if ( json.success ) {

					$('#stay-date').hide();

					if ( json.minstay ) {
						var days = json.minstay.split(','), d, formatted, a = [];

						for ( var i = 0, l = days.length; i<l; ++i ) {
							d = days[i].split('-')
							formatted = d[1] + '/' + d[2] + '/' + d[0];
							a.push( formatted )
						}

						/*
						$('.table-container .ava').each(function() {
							if ( $.inArray( $(this).attr('date'), a ) != -1 ) {
								$(this).addClass('promo');
							}
						});
						*/
						$('.table-container td:not(.past)').each(function() {
							if ( $.inArray( $(this).attr('date'), a ) != -1 ) {
								//$(this).addClass('promo');
								$(this).addClass('minstay')
								$(this).removeClass('not-available')
								$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-not-available/, 'day-\$1-minstay'));
							}
						});
					}

					if ( json.open ) {

						var days = json.open.split(','), d, formatted, a = [];

						for ( var i = 0, l = days.length; i<l; ++i ) {
							d = days[i].split('-')
							formatted = d[1] + '/' + d[2] + '/' + d[0];
							a.push( formatted )
						}

						/*
						$('.table-container .ava').each(function() {
							if ( $.inArray( $(this).attr('date'), a ) != -1 ) {
								$(this).addClass('promo');
							}
						});
						*/
						$('.table-container td').each(function() {
								$(this).addClass('adarq')
							if ( $.inArray( $(this).attr('date'), a ) != -1 ) {

								if ( !$(this).hasClass('past') ) {
									$(this).addClass('ava');

									if ( $(this).hasClass('not-available') ) {
										$(this).removeClass('not-available')
										$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-not-available/, 'day-\$1-ava'));
									}

									if ( $(this).hasClass('minstay') ) {
										$(this).removeClass('minstay')
										$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-minstay/, 'day-\$1-ava'));
									}
								}
							}
						});

					}

					if ( json.close ) {
						var days = json.close.split(','), d, formatted, c = [];

						for ( var i = 0, l = days.length; i<l; ++i ) {
							d = days[i].split('-')
							formatted = d[1] + '/' + d[2] + '/' + d[0];
							c.push( formatted )
						}

						window.c = c;

						$('.table-container .ava').each(function() {

							if ( $(this).hasClass('not-available') ) {
								//$(this).removeClass('ava');
							}

							if ( $.inArray( $(this).attr('date'), c ) != -1 && !$(this).hasClass('not-available') ) {
								$(this).removeClass('promo').removeClass('ava').addClass('not-available');

								if ( montageConfig.nonAvailIsClickable ) {
									$(this).addClass('ava')
								}

								$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-ava/, 'day-\$1-not-available'));
							}
						});

						$('.table-container .minstay').each(function() {
							if ( $.inArray( $(this).attr('date'), c ) != -1 ) {
								$(this).removeClass('minstay').removeClass('ava').addClass('not-available');

								if ( montageConfig.nonAvailIsClickable ) {
									$(this).addClass('ava')
								}

								$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-minstay/, 'day-\$1-not-available'));
							}
						});
					}

					if ( callback )
						callback({apply:true});


				} else if ( json['status']) {

					log('ttt2')

					$('#stay-date p').text( json['status'] );
					$('#stay-date').show();
					$('#check-loader').hide();
					$('#check-bg').show();

					callback();

				}

			}
		})
	}

	window.checkDates = checkDates;

	$.fn.notAvail = function() {
		log('notAvail!!')
		return this.each(function() {

			if ( $(this).hasClass('ava') ) {
				$(this).removeClass('ava')
				$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-ava/, 'day-\$1-not-available'));
			} 

			if ( $(this).hasClass('promo' ) ) {
				$(this).removeClass('promo')
				$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-promo/, 'day-\$1-not-available'));
			} 

			if ( $(this).hasClass('minstay' ) ) {
				log('minstay!@!@!')
				$(this).removeClass('minstay')
				$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-minstay/, 'day-\$1-not-available'));
			}

			if ( $(this).hasClass( 'past' ) ) {
				$(this).removeClass('promo').removeClass('minstay').removeClass('ava')
				$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-past/, 'day-\$1-not-available'));
			}

			$(this).addClass('not-available')

			if ( montageConfig.nonAvailIsClickable )
				$(this).addClass('ava');
		})
	}

	function checkPromos( callback ) {

			log('checkPromos invoked')

			var tt = $('.table-container .promo, .table-container .ava, .table-container .minstay').notAvail();
			window.tt = tt;
			//alert( tt.length )

			var request, query = 'one=two', a = $('#arrive').val(), d = $('#depart').val(), ad = $('#adult').val(), c = $('#child').val();

			window.c = c;
			window.ad = ad;

			if ( $('#promocode').val().length ) {
				query+= '&promo=' + $('#promocode').val();
			}

			if ( $('#groupcode').val().length ) {
				query+= '&groupcode=' + $('#groupcode').val();
			}

			query+= '&arrive=' + $('.table-container td:not(.default)').not('.way-past').eq(0).attr('date')
			query+= '&depart=' + $('.table-container td:not(.default)').not('.way-past').slice(-1).attr('date')

			/*
			if ( a ) {
				query+= '&arrival=' + reformat(a)
			}

			if ( $('#depart').val().length ) {
				query+= '&depart=' + reformat(d)
			}
			*/

			if ( ad ) {
				query+= '&adult=' + reformat(ad)
			}

			if ( c ) {
				query+= '&child=' + reformat(c)
			}

			query+= '&promocheck=true';

			window.request = request;

			request = $.ajax({
				url:'/direct/calendars.php',
				cache:false,
				data:query,
				dataType:'json',
				success:function( json ) {

					//$('#booking-console').addClass('open');

					window.json = json;

					if ( json.success ) {

						$('#stay-date').hide();

						if ( json.minstay ) {

							var days = json.minstay.split(','), d, formatted, a = [];

							for ( var i = 0, l = days.length; i<l; ++i ) {
								d = days[i].split('-')
								formatted = d[1] + '/' + d[2] + '/' + d[0];
								a.push( formatted )
							}

							$('.table-container td:not(.past)').each(function() {
								if ( $.inArray( $(this).attr('date'), a ) != -1 ) {

										$(this).addClass('minstay')
										$(this).addClass('promo')
										$(this).addClass('ava')

										if ( $(this).hasClass('not-available') ) {
											$(this).removeClass('not-available')
											$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-not-available/, 'day-\$1-minstay'));
										} 

										if ( $(this).hasClass('ava') ) {
											//$(this).removeClass('ava')
											$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-ava/, 'day-\$1-minstay'));
										}
									//$(this).addClass('promo');
								}
							});
						}

						if ( json.open ) {

							var days = json.open.split(','), d, formatted, a = [];

							for ( var i = 0, l = days.length; i<l; ++i ) {
								d = days[i].split('-')
								formatted = d[1] + '/' + d[2] + '/' + d[0];
								a.push( formatted )
							}

							/*
							$('.table-container .ava').each(function() {
								if ( $.inArray( $(this).attr('date'), a ) != -1 ) {
									$(this).addClass('promo');
								}
							});
							$('.table-container .ava:not(.past)').each(function() {
								if ( $.inArray( $(this).attr('date'), a ) != -1 ) {
										$(this).addClass('promo');
								}
							});
							*/

							$('.table-container td:not(.past)').each(function() {
								if ( $.inArray( $(this).attr('date'), a ) != -1 ) {

										$(this).addClass('promo')
										$(this).addClass('ava')

										if ( $(this).hasClass('not-available') ) {
											$(this).removeClass('not-available')
											$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-not-available/, 'day-\$1-ava'));
										} 

										if ( $(this).hasClass('ava') ) {
											//$(this).removeClass('ava')
											$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-ava/, 'day-\$1-ava'));
										}

										if ( $(this).hasClass('minstay') ) {
											$(this).removeClass('minstay');
											$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-minstay/, 'day-\$1-ava'));
										}
									//$(this).addClass('promo');
								}
							});

						}

						if (json.close ) {
							var days = json.close.split(','), d, formatted, c = [];

							for ( var i = 0, l = days.length; i<l; ++i ) {
								d = days[i].split('-')
								formatted = d[1] + '/' + d[2] + '/' + d[0];
								c.push( formatted )
							}

							window.c = c;

							$('.table-container .ava:not(.past)').each(function() {
								if ( $.inArray( $(this).attr('date'), c ) != -1 ) {
									$(this).removeClass('promo').removeClass('ava').addClass('not-available');

									if ( montageConfig.nonAvailIsClickable ) {
										$(this).addClass('ava')
									}

									$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-ava/, 'day-\$1-not-available'));
								}
							});

							$('.table-container .minstay:not(.past)').each(function() {
								if ( $.inArray( $(this).attr('date'), c ) != -1 ) {
									$(this).removeClass('minstay').removeClass('ava').removeClass('promo').addClass('not-available');

									if ( montageConfig.nonAvailIsClickable ) {
										$(this).addClass('ava')
									}

									$(this).attr('class', $(this).attr('class').replace(/day-(\d+)-minstay/, 'day-\$1-not-available'));
								}
							});
						}

						if ( callback )
							callback({apply:true});


					var selectd = $('td.selected')

					if ( selectd.eq(0).is('.not-available') ) {
						selectd.eq(0).removeClass('selected').removeClass('selected-starting')
						$('#arrive').val('')
						selectd.eq(0).find('.arrival-span').appendTo('.calendar').hide();
					}

					if ( selectd.slice(-1).is('.not-available') ) {
						selectd.slice(1).removeClass('selected').removeClass('selected-starting').removeClass('selected-ending')
						selectd.slice(-1).find('.departure-span').appendTo('.calendar').hide();
						$('#depart').val('')
					}


					} else if ( json['status']) {

						log('ttt3')

						//alert( $('.table-container .minstay').length )

						log('tyranosaurus rex')

						var par = $('#stay-date p');
						$(par).text( json['status'] );
						if ( $(par).text().indexOf('Invalid Promo') !== -1 ) {
							var a = $('<a/>').addClass('clear-invoker').text(' Clear Promo / Group Code').attr('href', '#')
							$(par).append( a )
						}

						$('#stay-date').show();
						$('#check-loader').hide();
						$('#check-bg').show();
						$('#calendar-wrap').showIt();

						var selectd = $('td.selected')

						if ( selectd.eq(0).is('.not-available') ) {
							selectd.eq(0).removeClass('selected').removeClass('selected-starting')
							$('#arrive').val('')
							selectd.eq(0).find('.arrival-span').appendTo('.calendar').hide();
						}

						if ( selectd.slice(-1).is('.not-available') ) {
							selectd.slice(1).removeClass('selected').removeClass('selected-starting').removeClass('selected-ending')
							selectd.slice(-1).find('.departure-span').appendTo('.calendar').hide();
							$('#depart').val('')
						}

						callback();

					}

				}
			})
	}

	function grabCalendar( o, callback, interior ) {

		log('grabCalendar')

		if ( !o ) o = {};

		if ( window.console )
			console.log( o.code ? 'one' : 'two' )

		if ( o.adultskids ) {
			$('#check-loader').show();
		}

		var context = o.context || document.body;

		if ( true ) {
		//if ( $('#calendar-wrap .table').length === 0 ) {

			if ( $('#calendar-wrap .table').length === 0 && !o.code ) {
				//$('#check-bg').wrap('<div/>').parent().appendTo('#content').find('#check-bg').show();
				//$("#calendar-wrap").fadeIn('fast');
				$('#calendar-wrap').show('slide', {}, 500, function(){});
				$('body').addClass('console-opened');
				//$('#check-loader').appendTo('#content').show();
			}

			var request, query = 'one=two', a = $('#arrive', context).val(), d = $('#depart', context).val(), ad = $('#adult', context).val(), c = $('#child', context).val();

			if ( $('#promocode').val().length ) {
				query+= '&promo=' + $('#promocode').val();
			}

			if ( o.promo ) {
				query+= '&promo=' + o.promo;
			}

			if ( a.length ) {
				query+= '&arrive=' + reformat(a)
			}

			if ( ad ) {
				query+= '&adult=' + reformat(ad)
			}

			if ( c ) {
				query+= '&child=' + reformat(c)
			}

			if ( $('#depart').val().length ) {
				query+= '&depart=' + reformat(d)
			}

			window.request = request;

			request = $.ajax({
				url:'/direct/calendars.php',
				cache:false,
				data:query+'&baz=bar',
				dataType:'json',
				success:function( json ) {

					//$('#booking-console').addClass('open');

					window.json = json;

					if ( json.success ) {
						
						var par = o.el ? o.el : $('.table-container');

						//if ( window.console ) console.log( request.getResponseHeader('Content-Length') );

						//$('#check-loader').hide();

						$(par).empty();
						$( json.html ).appendTo(par)
						//$('#calendar-wrap').show();

						$(par).clickableCalendar({
							arriveInput:$('.date-begin', context),
							departInput:$('.date-end', context),
							generateSubmit:$('.calendar-meta-info', context)
						});

						$('.calendar', context).each(function() {
							if ( !$(this).data('calendered') ) {
								$(this).calendarToggle();
								$(this).data('calendered', 1);
							}
						});

						if ( callback )
							callback();
						//$('.calendar').calendarToggle()

						if ( !interior ) // dont mess with masthead on special offers content invocations
							$('#check-bg').show();

						if ( o.adultskids ) {
							$('#check-loader').hide();
						}
					}

				}
			})
		}
	}

	var calendared = false, happening = false;
	log('happening iz ' + happening );
	//log('once or twice??')

	$('div#booking-console #reservations-console.beta :input, div#booking-console #reservations-console.beta #open-promo, div#booking-console #reservations-console.beta .field :label').click( function() {

		if ( $('body').hasClass('console-opened') ) return;

		log('happening var is ' + happening );

		if ( !happening ) {
			happening = true;
			log( 'happening is ' + happening );
		} else {
			return false;
		}

		log('click 9000!!')

		if ( $('#calendar-wrap .table').length == 0 ) {
			grabCalendar();
		} else {

			log('last')

			$('#home-masthead embed, #home-masthead object').hide();
			$('#home-masthead .alt').css('position', 'static')

			$('#check-bg').show();

			/*
			$("#calendar-wrap").fadeIn('slow', function() {
				alert('fadeIn')
				$('a.next-month').animate({
					'background-position-x': -806+"px",
					'background-position-y': -168+"px"
					}, 2000, function() {
						$(this).removeClass("preload");
				});
			});
			*/

				$('#calendar-wrap').show('slide', {
						orientation:'vertical',
						direction: 'down'
					}, 1000, function() {

					happening = false;

					$('a.next-month').animate({
						'background-position-x': -806+"px",
						'background-position-y': -168+"px"
						}, 2000, function() {
							$(this).removeClass("preload");
					});
				});

			
			$('body').addClass('console-opened');

			if ( !calendared ) {


				$('.table-container').clickableCalendar({
					arriveInput:$('.date-begin'),
					departInput:$('.date-end'),
					generateSubmit:$('#calendar-wrap .calendar-meta-info')
				});

				$('.calendar').calendarToggle()
				calendared = true;

							if ( $('#arrive').val().length == 10 && $('#depart').val().length == 10 ) {
								var a = $('[date="' + trimZero($('#arrive').val()) + '"]'), b = $('[date="' + trimZero($('#depart').val()) + '"]');

								if ( a.length && b.length && a.is('.ava') && b.is('.ava') ) {
									a.trigger( 'click' )
									b.trigger( 'click' )
								}
							}

			}

		}

	});

	glo.gettin = false;
	
	//Month scroller
	//Toggle the next year
	$('a.jump.next').click(function(e){

		log('jump next and gettin is ' + glo.gettin );

		if ( glo.gettin )
			return false;

		e.preventDefault();

		var parentScroll = $(this).parent('#month-scroller');
		var activeYear = $('ul.active',parentScroll);
		var activeYearDate = parseInt(activeYear.attr("id").split('-')[1]);
		if(activeYear.next().length){
			activeYear.removeClass('active').hide();
			activeYear.next().addClass('active').show();
		}else{
			activeYear.hide().removeClass('active');
			$('#month-container',parentScroll).append(buildNextYear(activeYearDate));			
			activeYear.next().show();
		};
		//$('#month-container ul:visible').attr('id',"year-"+(activeYearDate+1));
		log('montage1');
		if ( $(this).find('span').length ) {
			$('span',this).html(activeYearDate+2);
		} else {
			$(this).html(activeYearDate+2);
		}
		log('montage2' + activeYearDate);
		if(!$('a.jump.prev span',parentScroll).length){
			if($(parentScroll).hasClass('mini')){
				$('a.jump.prev',parentScroll).html(activeYearDate).removeClass('inactive');
			} else {
				$('a.jump.prev',parentScroll).html('Jump To <span>'+(activeYearDate)+'</span></a>').removeClass('inactive');
			}
		} else {
			$('a.jump.prev span',parentScroll).html(activeYearDate);
		};

		var ev = jQuery.Event('click')
		ev.thing = 'next';

		$(parentScroll).find('ul.active li.available a').eq(0).trigger( ev )
	});

	//Toggle previous year
	$('a.jump.prev').click(function(e){

		if ( glo.gettin )
			return false;

		e.preventDefault();

		window.baa = e;

		var parentScroll = $(this).parent('#month-scroller')
		//var cal = parentScroll.siblings('.calendar'), months = cal.data('months');

		var activeYear = $('ul.active',parentScroll);
		if(activeYear.prev().length){
			activeYear.removeClass('active').hide();
			activeYear.prev().addClass('active').show();
		};
		var activeYearDate = parseInt($('ul.active',parentScroll).attr("id").split('-')[1]);
		$('a.jump.next span',parentScroll).html(activeYearDate+1);
		if($('ul.active',parentScroll).hasClass("current-year")){
			$('a.jump.prev',parentScroll).addClass("inactive").html('<em class="alt">No previous year</em>');
		}else{
			$('a.jump.prev span',parentScroll).html(activeYearDate-1);
		};

		var ev = jQuery.Event('click')
		ev.thing = 'prev';

		if ( !e.curMonth ) {
			$(parentScroll).find('ul.active li.available a').eq(0).trigger( ev )
		} else {
			ev.thing = 'next';
			//ev.special = true;
			$(parentScroll).find('ul.active li.' + e.curMonth + '.available a').trigger( ev )
			/*
			setTimeout(function() {
			}, 5000 );
			*/
		}
	});

	$('#month-container li.unavailable a').live('click', function(e) {
		e.preventDefault();
	});

	$('.clear-invoker').live('click', function(e) {e.preventDefault();
		$('.clear-code').trigger('click');
	});
	
	//When clicking on months on the scroller...
	$('#month-container li.available').live('click', function(e) {

		window.stupid = e;

		log('gettin is ' + glo.gettin );

		if ( $(this).is(':last-child') ) {
			$(this).prev().find('a').trigger('click')
			return false;
		}

		if ( glo.gettin ) return

		glo.gettin = true;

		e.preventDefault();
		if ($(this).parents('#calendar-wrap').length) { var context = $(this).parents('#calendar-wrap') };
		if ($(this).parents('.calendar-wrap').length) { var context = $(this).parents('.calendar-wrap') };
		var selectedMonth = ($(this).attr('rel'));

		log( selectedMonth );

		var m = $('.calendar', context).data('months');
		var l = $('.current_month[rel="'+selectedMonth+'"]',context).parents('div.table');
			window.l = l;

		// if there are more months, aka this aint the last month

		if ( l.next().length ) {
			log('if');
			var selectedMonthCal = $('.current_month[rel="'+selectedMonth+'"]',context).parents('div.table');
			$('.calendar .table:visible',context).addClass('alt');
			selectedMonthCal.removeClass('alt');
			selectedMonthCal.next().removeClass('alt');

						log('STING')
						m.currentMonth = selectedMonthCal[0];
						m.secondMonth = selectedMonthCal.nextAll('.table')[0];
						m.lastMon = $(m.secondMonth).parent().find('div:last')[0]

						if ( e.thing && e.thing == 'prev' ) {
							$('.next-month', context).css('visibility', 'visible');
						}

						if ( m.currentMonth == m.firstMonth ) {
							$(context).find('.jump.prev').addClass('inactive')
							$('.previous-month', context).css('visibility', 'hidden');
						}

						if ( m.secondMonth !== m.lastMon && m.currentMonth != m.firstMonth )
							$('.previous-month', context).css('visibility', 'visible').removeClass('preload');

						//if ( e.thing == 'next' ) {

								/* $('.previous-month', context).animate({ 'background-position-x': -131+"px", 'background-position-y': -168+"px" }, 2000, function() { $(this).removeClass("preload"); }); */

						glo.gettin = false;

		} else {
			log('else');
				var lastMonthDate = $('.calendar .table:last',context).find('th.current_month').attr('rel').split("-");
				var selectedMonthDate = selectedMonth.split("-");
				var numberOfMonths = ((parseInt(selectedMonthDate[1]) - parseInt(lastMonthDate[1])) * 12) - parseInt(lastMonthDate[0]) + parseInt(selectedMonthDate[0]) + 6;
				window.m = m;

				if(context.parents('.package-wrapper').length){	
					$('<img class="ugh" src="/images/check-avail/ajax-loader.gif">').appendTo( $('.table-container',context) )
				}

				grabMonths(

					$('.calendar .table:last',context).find('td:not(.default):last').attr('date')
					
					, numberOfMonths

					, function() {
						var selectedMonthCal = $('.current_month[rel="'+selectedMonth+'"]',context).parents('div.table');
						$('.calendar .table:visible',context).addClass('alt');
						selectedMonthCal.removeClass('alt');

						log('HOGAN');
						m.currentMonth = selectedMonthCal[0];
						m.secondMonth = selectedMonthCal.nextAll('.table')[0];
						m.lastMon = $(m.secondMonth).parent().find('div:last')[0]

						selectedMonthCal.nextAll('.table').eq(0).removeClass('alt');
						$('.ugh').remove();

						if ( e.thing == 'prev' ) {
							$('.next-month', context).css('visibility', 'visible');
							if ( m.currentMonth == m.firstMonth ) {
								$('.previous-month', context).css('visibility', 'hidden');
							}
						}

						if ( e.thing == 'next' ) {
							if ( m.secondMonth !== m.lastMon )
								$('.previous-month', context).css('visibility', 'visible').removeClass('preload');

								/* $('.previous-month', context).animate({ 'background-position-x': -131+"px", 'background-position-y': -168+"px" }, 2000, function() { $(this).removeClass("preload"); }); */
						}

						glo.gettin = false;

					},

					context
				);	
		};
		
		//When clicking on a month on the scroller, remove the currently highlighted ones and highlight the click one and its next sibling.
		$('#month-container li',context).each(function(){
			$(this).removeClass("current");
		});
		if($(this).hasClass('dec-available')){
			$(this).addClass('current');
			$('a.jump.next',context).click();
			$('ul.active .jan-available',context).addClass('current');
		}else{
			$(this).addClass("current");
			$(this).next().addClass("current");
		}
		
	});
	

	$('.close-thing').click(function(e) {
		e.preventDefault();
		$('#home-masthead embed, #home-masthead object').show();
		$('#home-masthead .alt').css('position', 'absolute')
		$('#check-bg').hide();
		$('body').removeClass('console-opened')
		$('#calendar-wrap').hide();
		$('#stay-date').hide();

		$('#promo-console').hide();

		if ( $('#calendar-wrap').css('z-index') == 'auto' ) {
			$('#calendar-wrap').css('z-index', $('#calendar-wrap').data('z'))
		}

		//$('#close-promo').trigger('click')
	});

	$.fn.showIt = function() {
		//this.css('z-index', 'auto');
		if ( $.browser.msie ) {
			//$(w).css('z-index', '-1');
			$(this).css('z-index', '1');
		} else {
			$(this).css('z-index', 'auto');
		}
	}

	$.fn.hideIt = function() {
		if ( $(this).data('z') ) {
			$(this).css('z-index', $(this).data('z') );
		} else {
			$(this).css('z-index', '101')
		}
	}

	//Documentation located in special.docs.js
	//Sifr
	//$('div#subnav h3').sifr({ strSWF: '/flash/hoefler-text-italic.swf', strColor: '#361b0a', strWmode: 'transparent', strFlashVars: 'textalign=center&' },{ expressInstall: true });


	$('div#subnav h3').sifr({ strSWF: '/flash/hoefler-text-italic.swf', strColor: '#1B263D', strWmode: 'transparent', strFlashVars: 'textalign=center&' },{ expressInstall: true });
	//$('div#content h1').sifr({ strSWF: '/flash/hoefler-text.swf', strColor: '#fffaed', strWmode: 'transparent', strCase: 'upper', strFlashVars: 'letterSpacing=4&' },{ expressInstall: true });
	$('div#content-item h3').sifr({ strSWF: '/flash/hoefler-text.swf', strColor: '#fffaed', strWmode: 'transparent', strCase: 'upper', strFlashVars: 'letterSpacing=2&' },{ expressInstall: true });
	$('body.home div#content div#home-content h3').sifr({ strSWF: '/flash/hoefler-text.swf', strColor: '#fffaed', strWmode: 'transparent', strCase: 'upper', strFlashVars: 'letterSpacing=2&h=14&' },{ expressInstall: true });
	$('div#weather-wrapper h4').sifr({ strSWF: '/flash/hoefler-text-italic.swf', strColor: '#ab9886', strWmode: 'transparent', strCase: 'upper' },{ expressInstall: true });
	$('div#weather-wrapper h5').sifr({ strSWF: '/flash/hoefler-text-italic.swf', strColor: '#fffaed', strWmode: 'transparent', strCase: 'upper' },{ expressInstall: true });


	// Flash Mastheads

	$("#home-masthead").flash({src:"/flash/home-masthead.swf",width:1380,height:482,wmode:"transparent",quality:"high"},{version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.xmlPath = '/flash/xml/home-masthead.xml';
				$(this).html($.fn.flash.transform(htmlOptions));
		});


	// Meeting Map
	$("div#meeting-map").flash(
		{src:"/flash/meeting-map.swf",
		 width:644,
		 height:453,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.xmlPath = '/flash/xml/meeting-map.xml';
				$(this).html($.fn.flash.transform(htmlOptions));
		});


	// Resort Map
	$("div#resort-map").flash(
		{src:"/flash/resort-map.swf",
		 width:644,
		 height:453,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.xmlPath = '/flash/xml/resort-map.xml';
				$(this).html($.fn.flash.transform(htmlOptions));
		});

	var navid = $('ul#nav-primary').find('.current').attr("id");
	var secnavid = $('#'+navid).find('.current').attr("id");
	
	var utilitynavid = $('ul#nav-utility').find('.current').attr("id");
	var utilitysecnavid = $('ul#nav-utility-press').find('.current').attr("id");
	
	
	if (navid != undefined)
		navid = navid.substring(8);
	else
		navid = 'overview';
		
	if (secnavid != undefined)
		secnavid = secnavid.substring(10);
	else
		secnavid = 'main';
	/*This part is ghetto- i know. dont hate
	var prisecnavid= navid+'-'+secnavid;
	switch (prisecnavid) {
		//case 'aboutresidences-main':
		case 'aboutresidences-features':
		case 'aboutresidences-amenities':
			prisecnavid ='settagline';
		break;
		default:
		}
	*/
	
	//alert(navid);
	//alert(secnavid);
	//alert(utilitynavid);
	//alert(utilitysecnavid);

	// expanding the ghetto
	if (secnavid =="virtual-concierge2") {
		navid = "activities";
	}
	
	switch (utilitynavid) {
		case 'utility-press':
			navid = "pressroom";
		break;
		case 'utility-careers':
			navid = "careers";
		break;
		case 'utility-contact':
			navid = "contactus";
		break;
	}
	
	if ((window.location.pathname == "/site-map.php") || (window.location.pathname == "/privacy-policy.php")) {
		navid = "contactus";
	}
	if (utilitysecnavid == "utility-press-awards") {
		navid = "awards";
	}
	
	$("#masthead").flash(
		{src:"/flash/interior-masthead.swf",
		 width:960,
		 height:332,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.primary = navid;
				htmlOptions.flashvars.secondary = secnavid;
				if (prisecnavid=='settagline') //if the tagline is specific for a page set this flashVars to true
					htmlOptions.flashvars.special = true;
				htmlOptions.flashvars.assetsFolder = '/flash/assets/';
				$(this).html($.fn.flash.transform(htmlOptions));
		});


	// Flash Email Signup
	
	$("div#flash-email-signup").each(function(){
		var cookieval = $.cookie("flashcheck");
		var flashopen = true;
		if ( cookieval == "flashopened" ) {
			flashopen = false;
		}
		$(this).flash(
			{src:"/flash/email-form.swf",
			 width:228,
			 height:327,
			 name:"homeMasthead",
			 id:"homeMasthead",
			 wmode:"transparent",
			 quality:"high"},
			 {version:"9"},
				function(htmlOptions) { //Use this to specify a query string, take out if not needed.
					htmlOptions.flashvars.openOnLoad = flashopen;
					$(this).html($.fn.flash.transform(htmlOptions));
			});
		$.cookie("flashcheck", "flashopened", { expires: 7 });
	});


	var navid = $('ul#nav-primary').find('.current').attr("id");
	var secnavid = $('#'+navid).find('.current').attr("id");
	
	//alert(secnavid);
	
	if (navid != undefined)
		navid = navid.substring(8);
	else
		navid = 'destination';
		
	if (secnavid != undefined)
		secnavid = secnavid.substring(10);
	else
		secnavid = 'main';
	//alert(secnavid);

	//This part is ghetto- i know. dont hate
	var prisecnavid= navid+'-'+secnavid;

	//alert(prisecnavid);

//Dropdown Nav
	if(BROWSER=='msie6') {
		$('#nav-primary li').hover(
			function() { $(this).addClass('over'); },
			function() { $(this).removeClass('over'); }
		)
	}
	
	// JQModal 
	var openFn=function(hash){
		hash.w.show();
		$('#dialog').css({left:($(window).width()-$('#dialog').width())/2,top:$(window).scrollTop()+10});
	};
	var openFn2=function(hash){
		hash.w.show();
		$('#dialog-residences').css({left:($(window).width()-$('#dialog-residences').width())/2,top:$(window).scrollTop()+10});
	};
	
	var openFnMap=function(hash){
		hash.w.show();
		$('#map-modal').css({left:($(window).width()-$('#map-modal').width())/2,top:$(window).scrollTop()+10});
	};
	
	var hideFn=function(hash){
		hash.w.hide()
		hash.o.remove();
	};
	/*$("#msnmap").each(function() {
		$('#map-jqmodal').jqm({trigger:'#msnmap', onShow: openFn, onHide: hideFn});
	});*/
	
	$('#dialog').jqm({ajax:'/includes/photo-gallery.php', onShow: openFn, onHide: hideFn, target:'div#photo-content'});

	$('#map-modal').jqm({ajax:'/includes/map.php', trigger: 'a#map-link', onShow: openFnMap, onHide: hideFn, target:'div#map-content'});

	// Close Button Highlighting. IE doesn't support :hover. Surprise?
	if($.browser.msie) {
		$('div.jqmAlert .jqmClose')
		.hover(
		function(){ $(this).addClass('jqmCloseHover'); }, 
		function(){ $(this).removeClass('jqmCloseHover'); });
	}

	$('.toggle-promo').click(function(e){

		var w = $('#calendar-wrap');

		if ( w.length ) {

			if ( $(this).is('#close-promo') ) {

				var els = $('#promo-console .field input');

				els.each(function() {
					if ( $(this).data('val' ) ) {
						$(this).val( $(this).data('val' ) )
					}
				});
			}

			if ( $(this).is('#open-promo') ) {

				var els = $('#promo-console .field input');

				els.each(function() {
					$(this).data('val', this.value );
				});

			}

			var z = w.css('z-index');

			if ( z != 'auto' && z != '-1' && z != '1' ) {
				$(w).data('z', $(w).css('z-index'));

				$(w).showIt();

				if ( $('body.home').length == 0 )
					$('#masthead').css('position', 'static')

			} else {
				$(w).css('z-index', $(w).data('z'));

				/*
				if ( $('body.home').length == 0 )
					$('#masthead').css('position', 'relative')
				 */
			}

			if ( $(this).is('#open-promo') ) {
				$(w).showIt();
			}

		}

		// apply this ONLY to the index-new page.. 
		if ( $('.console-opened').length ) {

			if ( $(this).is('#done-promo') ) {
				if ( $('#groupcode').val() || $('#promocode').val() || $('#iata-number').val() ) {
					touched = true;
					
					if ($('#groupcode').val())
						code_used = $('#groupcode').val();
					else if ($('#promocode').val())
						code_used = $('#promocode').val();
					else
						code_used = $('#iata-number').val();						
						
				} else {

					$('#open-promo').html( $('#open-promo').data('html') ).removeClass('applied')
					$('.table-container .promo').removeClass('promo')
					touched = false;
					// revert
					$('#check-loader').show();
					checkDates(function() {
						$('#check-loader').hide();
					});
				}

				if ( touched ) {
					//grabCalendar({ code: true });
					$('#check-loader,#check-bg').show();

					checkPromos( function( optional ) {

						if ( optional && optional.apply ) {
							$('#open-promo')
								.html('Code <span>'+ code_used +'</span><br/>Applied')
								.addClass('applied')
						}
						$('#check-loader').hide();
						$('.clear-code').show();
						//$('#check-bg').hide();
					});
				}
			}
		}

		e.preventDefault();

		if ( w.length ) {

			$('#promo-console').toggle('slow',function(){
				if($(this).is(':visible')) {
					$('#group-code').focus();
				}
				else {
					$('.submit').focus();
				}
			});

		} else {

			$('#promo-console').toggle(0,function(){
				if($(this).is(':visible')) {
					$('#group-code').focus();
				}
				else {
					$('.submit').focus();
				}
			});

		}

		if ( $('.console-opened').length == 0  ) {

			if (BROWSER=='msie6') $('select#child').toggle();
			if (BROWSER=='msie6') $('select#adults').toggle();
			if ($('#group-code').val() || $('#promo-code').val() || $('#iata-number').val()) {
				$('#complete-promo').show();
			}
			else {
				$('#complete-promo').hide();
			}
		}

	});


	$('.exec-team-long').hide();
	$('.exec-team').each(function(){
		var pTag = $('h4',this).next();
		if (pTag.html() == '') { pTag.hide(); }
		if ($('.exec-team-long',this).html() != '') {
			var toggleLink = $('<a/>').attr('href','#').text('Read More').toggle(function() {
					var el = $(this);
					el.html('Hide Details').parent().addClass('active').parent().find('.exec-team-long').slideDown('slow');
					return false;								   
				},function() { 
					var el = $(this);
					el.html('Read More').parent().removeClass('active').parent().find('.exec-team-long').slideUp('slow');
					//$('.exec-team-long').slideUp('slow');
					return false;								   
				});
			$('.exec-content',this).append(toggleLink);
		}
	});

	$('.person-extra').hide();
	$('a.person-toggle').toggle(function() {
		var el = $(this);
		el.html('Hide Details').parent().addClass('active').parent().find('.person-extra').slideDown('slow');
		return false;								   
	},function() { 
		var el = $(this);
		el.html('Read More');
		$('.person-extra').hide();
		return false;								   
	});
	
	/////////////////////////////////////////////////
	$('.directions').hide();
	$('.location').each(function(){
		var pTag = $('p',this).next();
		if (pTag.html() == '') { pTag.hide(); }
		if ($('.directions',this).html() != '') {
			var toggleLink = $('<a class="view-directions"/>').attr('href','#').text('View directions').toggle(function() {
					var el = $(this);
					el.html('Hide directions').parent().addClass('active').parent().find('.directions').slideDown('slow');
					return false;								   
				},function() { 
					var el = $(this);
					el.html('View directions');
					$('.directions').slideUp('slow');
					return false;								   
				});
			$('p.airport',this).append(toggleLink);
		}
	});
	
	/////////////////////////////////////////////////
	$(".activity").each(function(){
		$('p.activity-description').hide();
		var x = $(this);
      $("a.show-activity",x).toggle(function(){
           $("p.activity-description",x).slideDown();
           $(this).addClass("active");
      }, function() {
           $("p.activity-description",x).slideUp();
           $(this).removeClass("active");
      });
	});


// Ride the carousel...
	$('#homecarousel').after('<div id="control-links">').cycle({ 
		fx:     'fade', 
		speed:  800, 
		timeout: 0, 
		next: '.next-link',
		pager:  '#control-links' 
	});
	

	$(".press-release-div").each(function(){
        
      var x = $(this);
	  $(".articles-row:odd",x).addClass("press-odd");
      $(".articles").hide();
      $(".releases-toggle-div",x).toggle(function(){
           $(".articles",x).slideDown();
           $(this).addClass("active").html("<em class='alt'>Hide Articles</em>");
      }, function() {
           $(".articles",x).slideUp().hide();
           $(this).removeClass("active").html("<em class='alt'>Show Articles</em>");
      });
	});
	
	$(".press-release-table").each(function(){
      var x = $(this);
      $(".releases-toggle",x).toggle(function(){
           $(".articles",x).slideDown();
           $(this).addClass("active");
			  $(this).html("<em class='alt'>Hide Releases</em>");
      }, function() {
           $(".articles",x).slideUp();
           $(this).removeClass("active");
			  $(this).html("<em class='alt'>Show Releases</em>");
      });
	});


	
	
});

function mycarousel_initCallback(carousel) {
	var jcsize = parseInt($("#control-links li").size());
	//$('ul.jcarousel-list li:eq('+jcsize+')').find('.next').hide();
	//alert(jcsize);
	jQuery('#control-links a').bind('click', function() {
		var cindex = $(this).parent().attr("id");
		cindex = cindex.substring(1);
        carousel.scroll(jQuery.jcarousel.intval( cindex ));
		$("#control-links a img").attr("src","/images/layout/control1.png");
		$(this).children("img").attr("src","/images/layout/control2.png");
        return false;
    });
	
	jQuery('.next-link').bind('click', function() {
		var cindex = $(this).parent().parent().parent().attr('jcarouselindex');
		//cindex = cindex.substring(5);
		cindex = parseInt(cindex) + 1;
		$("#control-links a img").attr("src","/images/layout/control1.png");
		$("#control-links").find("li#c"+cindex+" a").children("img").attr("src","/images/layout/control2.png");
		//alert(cindex +"+"+ jcsize);
		if (cindex == (jcsize+1)) {
			carousel.scroll(1);
			$("#control-links").find("li#c1 a").children("img").attr("src","/images/layout/control2.png");
		} else {
        	carousel.next();
		}
        return false;
    });
	
};

