$(function() {

	var searchField = $('#search'), searchValue = $(searchField).val();
	searchField.focus(function() {
	    if ( this.value == searchValue ) {
		$(this).val('');
	    }
	    $(this).blur(function() {
		if ( this.value == '' || this.value == searchValue ) {
		    $(this).val('');
		}
	    });
	});

	var IE6 = ($.browser.msie && $.browser.version=='6.0')?true:false;

	$('#site-search').clearField();	
	
	$('#signup-tall').flash(
		{src:"/flash/email-form-vertical.swf",
		 width:217,
		 height:255,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"
	});
	$('#signup-tall-open').flash(
		{src:"/flash/email-form-vertical.swf",
		 width:217,
		 height:255,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.stayOpen = "true";
				$(this).html($.fn.flash.transform(htmlOptions));
		}
	);
    
	$('#signup-tall-open2').flash(
		{src:"/flash/email-form-vertical-2.swf",
		 width:217,
		 height:255,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.stayOpen = "true";
				$(this).html($.fn.flash.transform(htmlOptions));
		}
	);

	$('#signup-wide').flash(
		{src:"flash/email-form-horizontal.swf",
		 width:650,
		 height:55,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"
	});
	$('#signup-wide-open').flash(
		{src:"flash/email-form-horizontal.swf",
		 width:650,
		 height:55,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.stayOpen = "true";
				$(this).html($.fn.flash.transform(htmlOptions));
		}
	);

	
	$('.home #masthead').flash(
		{src:"flash/homepage.swf",
		 width:650,
		 height:336,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"
	});
	
	$('#flash-photo-gallery').flash(
		{src:"flash/photo_gallery.swf",
		 width:466,
		 height:416,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.configFile = "flash/xml/gallery_config.xml";
				htmlOptions.flashvars.xmlFile = "flash/xml/images.xml";
				$(this).html($.fn.flash.transform(htmlOptions));
		}
	);
	
	$('#flash-wedding-photo-gallery').flash(
		{src:"flash/weddings-photo-gallery.swf",
		 width:600,
		 height:420,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.xmlFile = "flash/xml/weddings_images.xml";
				$(this).html($.fn.flash.transform(htmlOptions));
		}
	);
	
	$('#flash-movie-gallery').flash(
		{src:"flash/SouthShore.swf",
		 width:466,
		 height:367,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"
	});
	
	$('.golf-vid').each(function() {
		var id = $(this).attr('id');
		$(this).flash({src:"flash/"+id+".swf",
			 width:388,
			 height:328,
			 wmode:"transparent",
			 quality:"high"},
			 {version:"8"
		});
	});
	
	$('.inset-flash').each(function() {
		var id = $(this).attr('id');
		$(this).flash({src:"flash/"+id+".swf",
			 width:205,
			 height:206,
			 wmode:"transparent",
			 quality:"high"},
			 {version:"8"
		});
	});
//RFP form to show other fields that are extra
	$("ul.checkboxgroup li.add-info").hide();
		$("ul.checkboxgroup input").click(function() {
			// if the input has a class of other, show it's "other" field
			if ($(this).is(".add-info")){
				$(this).parent().next().show();
				$(this).parent().next().find("label").addClass("required");
				$(this).parent().next().find("input").addClass("required");
				// if it's a checkbox, remove the "other" field when it is unchecked
				if (!this.checked) {
					$(this).parent().next().hide();
					$(this).parent().next().find("label").removeClass("required");
					$(this).parent().next().find("input").removeClass("required");
				}
			}
		});
/*-----------*/

	
	$('#trip-planner-console .count span').checkNum();
	
	$('#planner-summary').click(function() { 		
		if($('#planner-details').is(':hidden')) {
			$('#planner-details').slideDown(600);
			$('a', this).css('background-position', 'right bottom'); 
		} else {
			$('#planner-details').slideUp(600); 
			$('a', this).css('background-position', 'right top');
		}
		return false;
	});
	
	$('.planner-add').click(function() {
		var tmp = $(this).attr('id').split('-');
		var section = tmp[0];
		var id = tmp[1];
		var op = (section=='accommodations')?"add":"addact";
		var moved = false;
		var href = $(this).attr('rel');

		$.post("ajax.php", {op: op, id: id}, function(data) {
			if(data!='added') {
				if($.fn.getScroll()>Number($('#content')[0].offsetTop+$('#trip-planner-console').height())) {
					moved = true;
					if($.browser.msie&&$.browser.version=='6.0')
						$('#trip-planner-console').css({position: 'absolute', top: $.fn.getScroll()-350+"px", right: "21px"});
					else
						$('#trip-planner-console').css({position: 'fixed', top: '20px', right: $('#wrapper')[0].offsetLeft+33+"px"});
				}
				
				$('#planner-details').slideDown(600, function() {
					var total = Number($('#planner-summary .count span').html())+1;
					var count = Number($('#tp-'+section+' .count span', this).html())+1;
					
					$('a', '#planner-summary').css('background-position', 'right bottom');
					$('#planner-summary .count').show().children('span').html(total)
					$('#tp-'+section+' .count', this).show().children('span').html(count);			
					
					$('#tp-'+section, this).effect('highlight',{color: '#EEB211'}, 3000, function() { 
						$('a', '#planner-summary').css('background-position', 'right top');																			   
						$('#planner-details').slideUp(600, function() {
							if(moved)
								$('#trip-planner-console').fadeTo("slow", .01, function() { $(this).removeAttr('style'); });
						});
					});
				});	
			} else {
				var c = confirm("This item is already in your Trip Planner, would you like to view it now?");	
				if(c)
					window.location = href;
			}
		});
		return false;
	});
	
	$('#delete-profile').click(function() {
		var del = confirm('Are you sure you want to delete your profile?');		
		if(del)
			window.location="trip-planner-profile-edit.php?op=del";
	});
	
	$('.remove-planner').click(function() {
		var tmp = $(this).attr('id').split('-');
		var section = tmp[0];
		var id = tmp[1];
		var el = $(this).parents('.item');
		var total = Number($('#planner-summary .count span').html())-1;
		var count = Number($('#tp-'+section+' .count span').html())-1;
		var op = (section=='accommodations')?"off":"rmact";
		
		$('#planner-summary .count span').html(total?total:'0')
		$('#tp-'+section+' .count span').html(count?count:'0');	
		
		$('#trip-planner-console .count span').checkNum();
		$.post("ajax.php", {op: op, id: id}, function() { el.fadeOut("slow"); });
		return false;
	});
	
	$('#offers-inner').each(function() {
		var obj = $(this),
		    count = $(this).children().length,
		    p = $(this).parent();

		if(count) {
			$(this).children().eq(0).addClass('current').siblings().hide();
			
			$('<a href="#" class="next-btn"><img src="/images/home/next.gif"></a>').prependTo(p);
			$('<a href="#" class="prev-btn"><img src="/images/home/prev.gif"></a>').prependTo(p);

			$('#offers .prev-btn, #offers .next-btn').click(function() {
				var next = $(this).is('.next-btn');
				var temp = $(this);
				temp.show();

				if ( next ) {
				    if($('.current', obj).is(':last-child')) {
					    $('.current', obj).fadeOut("slow", function() {
						    $(this).removeClass('current');
					    }).siblings('.offer:eq(0)').fadeIn(1500, function() { 
						    $(this).addClass('current');
						    temp.fadeIn('fast');
					    });
				    } else {
					    $('.current', obj).fadeOut("slow", function() {
						    $(this).removeClass('current');
					    }).next('.offer').fadeIn(1500, function() { 
						    $(this).addClass('current');
						    temp.fadeIn('fast');
					    });
				    }
				} else {
				    if($('.current', obj).is(':first-child')) {
					    $('.current', obj).fadeOut("slow", function() {
						    $(this).removeClass('current');
					    }).siblings('.offer:eq(' + count-1 + ')').fadeIn(1500, function() { 
						    $(this).addClass('current');
						    temp.fadeIn('fast');
					    });
				    } else {
					    $('.current', obj).fadeOut("slow", function() {
						    $(this).removeClass('current');
					    }).prev('.offer').fadeIn(1500, function() { 
						    $(this).addClass('current');
						    temp.fadeIn('fast');
					    });
				    }
				}

				return false;
			})
		}
	});

	// Fix to not have sIFR on landing pages.
    $('#content h1').each(function(){
        if($(this).parent().hasClass('no-sifr')){
        }else{
            $(this).sifr({ strSWF: '/fonts/bernhard-modern.swf', strWmode: 'transparent', strColor: '#0f5187'},{ expressInstall: true });        
        }    
    });
    //$('#content h1').sifr({ strSWF: '/fonts/bernhard-modern.swf', strWmode: 'transparent', strColor: '#0f5187'},{ expressInstall: true });   
	$('.checkout h2').sifr({ strSWF: '/fonts/bernhard-modern.swf', strWmode: 'transparent', strColor: '#000000'},{ expressInstall: true });	   
	$('#co-steps li:not(".current, .past")').sifr({ strSWF: '/fonts/bernhard-modern.swf', strWmode: 'transparent', strColor: '#7fa2bf', intPadding: [0, 2, 0, 2], strFlashVars: 'textalign=center&'},{ expressInstall: true });	   
	$('#co-steps .current, #co-steps .past').sifr({ strSWF: '/fonts/bernhard-modern.swf', strWmode: 'transparent', strColor: '#00467f', intPadding: [0, 2, 0, 2], strFlashVars: 'textalign=center&'},{ expressInstall: true });	   

	/*
	$('#offers .current h5').sifr({ strSWF: '/fonts/bernhard-mod-bt.swf', strWmode: 'transparent', strColor: '#054673'},{ expressInstall: true });	   
	*/
	
	$('#res-console').each(function() {		
		$('.adv-search-link').toggle(function() { 
			$(this).html('Simple Search').parents('form').children('.adv-search').slideDown("fast");
			$(this).parents('form').find('.adv-toggle').val(1)
			return false;
		}, function() {
			$(this).html('Advanced Search').parents('form').children('.adv-search').slideUp("fast");
			$(this).parents('form').find('.adv-toggle').val(0)
			return false;
		});
		
		$('#res-tabs li', this).click(function() {
			if($(this).is('#console-homes')) {
				$('#homes-form').show().prev().hide();
			} else {
				$('#villas-form').show().next().hide();
			}
			$(this).addClass('current').siblings().removeClass('current');
			return false;
		});
	});
	
	/*$('#unit-search a').click(function() {
		if($('#villas-homes').val()==1)
			$('#console-home').slideDown("fast");
		else
			$('#console-villa').slideDown("fast");
		$('#adv-search-link').hide();
		$('#adv-toggle').val(1);							   
	});*/

    
    // Villas & Homes search console view and location filtering
    
    $('.filter-dropdowns').each(function() {
        $(this).change(function(){
            var id = $(this).val();
            var type = 'villa';
            if($(this).attr('name').substr(0,4)=='home'){
                type = 'home';   
            }
            var action = 'getlocations';
            if($(this).attr('name')=='neighborhood' || $(this).attr('name')=='home-neighborhood'){
                action = 'getviews';       
            }
            
            $.get("ajax-update-dropdowns.php", { action: action, id: id, type:type }, function(data){
                var pieces = data.split('|');
                var field = pieces[0];
                var options = pieces[1];
                var current = $('#'+field).val();
                $('#'+field).html(options);
                $('#'+field+' option[value='+current+']').attr('selected','selected');
                //$('#'+field).removeOption(/./);
            });

            
        });    
    }); 
    
	 // Villas & Homes search main form view and location filtering
	$('.rental-search-dropdowns').each(function() {
        $(this).change(function(){
            var id = $(this).val();
            var type = 'villa';
            if($(this).attr('name').substr(0,4)=='home'){
                type = 'home';   
            }
            var action = 'getlocations';
            if($(this).attr('name')=='neighborhood' || $(this).attr('name')=='home-neighborhood'){
                action = 'getviews';       
            }
            
            $.get("ajax-update-dropdowns.php", { action: action, id: id, type:type }, function(data){
                var pieces = data.split('|');
                var field = pieces[0];
                var options = pieces[1];
                var current = $('.check-availability-form #'+field).val();
                $('.check-availability-form #'+field).html(options);
                $('.check-availability-form #'+field+' option[value='+current+']').attr('selected','selected');
                //$('#'+field).removeOption(/./);
            });

            
        });    
    }); 
	
	$('.activity-console').each(function() {
		var basic = $('#activity-basic', this);
		$('#console-nojs', this).hide();
		basic.show();
		
		$('.activity-form', this).submit(function() {
			if(!formError) {
				if($('#continue-form').val()) {
					$(':input', basic).removeAttr('disabled');
					return true;
				}				
				$(':input:not(.submit)', basic).attr('disabled', 'disabled');
				if($.browser.msie)
					$('#content h1:first.sIFR-flash').css('visibility', 'hidden');
				$('#table-wrapper').loadTable();
				$('#activity-advanced').slideDown("fast", function() { 
					$('#act-submit').hide(); 
					$('#reset').show();
				});

				$('#continue-form').val(true);
				return false;
			}
		});
		
		$('#faux-select').click(function() {
			var sel = $(this);
			if($.browser.safari) $('#console-course-select').css('top', '-38px');
			if($('#console-course-select').is(':visible')) {
				sel.css('background-position', 'right top');
				$('#console-course-select').hide();			
			} else {
				sel.css('background-position', 'right bottom');
				$('#console-course-select').show(.01,function() {
					$('body').bind('click', function(e) {
						if(!$(e.target).is('#console-course-select') && !$(e.target).parents().is('#console-course-select')) {
							sel.css('background-position', 'right top');
							$('#console-course-select').hide();
							$('body').unbind('click');
						}
					});
				});						  
			}	
			
			$('input', '#console-course-select').click(function() {
				var count = 0;
				$('#console-course-select input:checked').each(function(i) { count = i+1; });
				sel.text(count>0?count+' Course(s) Selected':'Select Course(s)');
			});
		});
		
		
		
		$('#reset').click(function() {
			$(this).hide();
			$(':input', basic).removeAttr('disabled');
			$('#continue-form').val('');
			$(':checkbox', basic).removeAttr('checked');
			$(':input:not(.submit)', basic).val('');
			$('#faux-select').text('Select Course(s)');
			$('#arrive', basic).val('mm/dd/yyyy');
			if($.browser.msie)
				$('#content h1:first.sIFR-flash').css('visibility', 'visible');
			$('#act-submit').show();
			$('#activity-advanced').hide();
			return false;						   
		});
	});
		
	/*$('#days-check').each(function() {
		$('#table-wrapper').html('');
		$('#days', this).change(function() {
			if($(this).val()=='')
				$('#table-wrapper').html('');
			else if($('#arrive', '#days-check').val()!='mm/dd/yyyy' && $('#arrive', '#days-check').val()!='')
				$('#table-wrapper').loadTable();
			else {
				$(this).val('');
				alert('Please select and arrival date first');
			}
		});
	});*/
	
	$('.activity-results').controlActResults();
	
	$('a', '#course-overview').click(function() {
		$(this).addClass('current');	
		$('a', '#course-map-nav').removeClass('current');
	});
	$('a', '#course-map-nav').each(function(i) {
		$(this).click(function() {
			$('a', '#course-overview').removeClass('current');
			$(this).addClass('current').parents('li').siblings().find('a').removeClass('current');
			$('#course-hole-wrapper').animate({"top": -(i*473)+'px'}, "slow");
			return false;
		});
	});
	
	$(".show-tip").each(function() {
		if($(this).parents().is('form') && IE6) {
			$(this).hover(function() { $(this).parents('form').find('select').css('visibility', 'hidden'); },
						  function() { $(this).parents('form').find('select').css('visibility', 'visible'); });
		}
		$(this).tooltip({
			track: true,
			delay: 0,
			showURL: false,
			fixPNG: true,
			showBody: " | ",
			top: -120,
			left: 5,
			extraClass: 'bubble'
		});
	});
	
	$('#same_address').click(function() {
		$('#hidden-block input').each(function() {
			var id = $(this).attr('id');
			var val = $(this).val();
			$('#billing_'+id).val(val);
			if($('#billing_state').val()=='--')
				$('#billing_state').trigger('change');
		});
	});
		
	$('#unit-gallery').each(function() {
		var obj = $(this);
		var index = 0;
		var count = $('#img a', obj).length;
		$('.img-move', obj).click(function() {
			if($(this).is('#img-last'))
				index--;
			else
				index++;
			
			if(index<0) index = count-1;
			if(index==count) index = 0;
		
			var newImg = $('#img a:eq('+index+')', obj).attr('href');
			$('#img a:eq('+index+')', obj).addClass('current-image').show().siblings().removeClass('current-image').hide();
			$('#count').html((index+1)+' of '+count);
			$('#zoom a', obj).attr('href', newImg);
			return false;
		});
									 
	});
	
	$('.co-book-activity').click(function() { 
		$(this).parents('.item').animate({height: 'hide'},'slow');
		$('.item-add', $(this).parents('.body')).slideDown("slow");
		return false;
	});
	
	$('.co-cancel').click(function() {
		var form = $(this).parents('form');
		form.parents('.item').animate({height: 'hide'},'slow', function() {
			form.coFormClear();
		});
		$('.item-new', $(this).parents('.body')).slideDown("slow");
		return false;
	});
	
	/*$('.item .inline-activity-form').submit(function() {
		if(!formError) {
			$(this).parents('.item-search').animate({height: 'hide'},'slow');
			$(this).parents('.item').find('.item-results').load('includes/golf-search-results.php', function() {
				$('.activity-results').controlActResults();
				$('.co-edit', this).click(function() {
					$(this).parents('.item-body').children('.item-results').slideUp("slow", function() {
						$(this).html('');																						  
					});
					$(this).parents('.item-body').children('.item-search').slideDown("slow");
				});
				$('.co-cancel', this).click(function() {
					var b = $(this).parents('.body');
					$('.item-add', b).hide();
					$('.item-new', b).slideDown("slow");
					$('.item-search', b).show().children('form').coFormClear();
					$('.item-results', b).html('');
				});
			}).animate({height: 'show'},'slow');
		}
		return false;
	});*/
	
	$('#photo_select').change(function() {
		$('#press-photo-wrapper').load('includes/press-photo-gallery.php', {photo_select: $(this).val()}, function() {
			$('.zoom-in').fancybox();
		});					   
	}).next().hide();
	
	$('#forgot-password a').click(function() {
		if($('form', '#forgot-password').is(':hidden')) {
			$('.planner-login').hide();
			$('form', '#forgot-password').show();
		} else {
			$('.planner-login').show(); 
			$('form', '#forgot-password').hide();
		}
		return false;
	});
	
	$('.month a').click(function() {
		$('.current', '.month').removeClass('current');							 
		$(this).parent().addClass('current');
		var vars = getQuery(this.href);
		var img = $('<img/>').attr('src', 'images/ajax-loader.gif')
							.css({position: 'absolute', top: 25+'%', left: 43+'%'});
		
		$('#week-wrapper').ajaxStart(function() { $('#week-wrapper').append(img); });
		
		$.get("includes/show-week.php", {year: vars['year'], month: vars['month'], week: vars['week']}, function(data) {
			$('#week-wrapper').remove();
			$(data).insertAfter($('#scroll-event'));
			startWeek();	
			if(vars['week']==1) {
				var clickday = $('#weeks .day-num:contains(1)');
				$.each(clickday, function() {
					if($(this).text().length==1)
						$(this).parent().find('a').trigger("click");
				});
			}
			else 
				$('#weeks > div:eq(0) a').trigger("click");
		});
		return false;
	});
	
	//Shows and hides disclaimer info for photo submission
	$('.terms').hide();
	$('.toggle-terms').toggle(function(){ 
		$(this).parents('li').children('.terms').show();
		return false;
	},function(){ 
		$(this).parents('li').children('.terms').hide();
		return false;
	});
	
	$(':input.reset').click(function() { $(this).parents('form').resetForm(); return false; });
	$('#event-form').each(function() { startWeek(); });
	
	$('#unit-rates-link a').click(function() {
		if(!$('#unit-rates > div:eq(0)').hasClass('rates-interior')) {
			var rel = this.rel;
			var img = $('<img/>').attr('src', 'images/ajax-loader.gif')
				.css({position: 'absolute', top: 25+'%', left: 43+'%'});
				
			$.ajax({
				type: "POST",
				url: "hilton-head-unit-check.php",
				data: "ID="+rel,
				beforeSend: function() {
					$('#unit-rates').append(img).append("<h3>Checking unit availability...</h3>");	
				},
				success: function(data) {
					pageTracker._trackPageview("/hilton-head-unit-check.php?ID="+rel);
					$('#unit-rates').html(data);
					$('#scroll-cal').scrollable({dist: 203}).pickDates();
					$('#unit-rates-form').click(function() {
						var firstDay = $('#arrive', this).val();
						var s = $('td', '#months-wrapper').index($('td.selected:first')[0]);
						var e = $('td', '#months-wrapper').index($('td.selected:last')[0]);
						if(!formError) {
							var days = $.ajax({
								type: "POST",
								url: 'ajax.php',
								data: 'op=minstay&date='+firstDay+'&diff='+(e-s),
								async: false
							}).responseText;
							
							if(days>0) {
								alert('There is a minimum '+days+' night stay for this property during this time.  Please extend your stay.');
								return false;
							}
						}
					});
				}
			});
		}
		return false;
	});
		
	$('.tabbed').tabbed();
	$('.zoom-in').fancybox();
	
	$('.zoom-in-fake').each(function() {
		$(this).click(function() {
	   		$('.current-image').trigger('click');
	   		return false;
		});
	});
	
	$('#scroll-event').scrollable({moveNum: 3, mover: '#months', moved: '.month'});
	
	$.fn.extend({
		loadTable: function() {
			this.load("includes/activity-form-table.php", { arrive: $('#arrive').val(), days: $('#days').val() });
		}
	});
	
	
	$("form#reservation-request select#accommodation_type").change( function () {
																			  
			$.get('includes/neighborhood.php', {cat_id:$(this).val()},function(data) { 
				$('form#reservation-request #neighborhood').html(data);
			});																		  
		});

	// Blog Form Help
	$('div.form-help').hide();
	$('a.help-link').toggle( function() {
		$(this).parents('div.field').children('div.form-help').show();
		return false;
	},function(){ 
	  $(this).parents('div.field').children('div.form-help').hide();
	  return false;
	});
	//social media sharing
	$('.share-link').bind('click',function() {
		$('.share-panel').hide();
		$(this).parents('.rss-item').find('.share-panel').css('display','inline');
		return false;
	});
	$('.share-close').click(function(){
		$(this).parents('.rss-item').find('.share-panel').slideUp('fast');
		return false;
	});
	//{Popup windows for the webcam
	$('.popup').click( function () {
		var popupLink = $(this).attr('href');		
		//window.open( $(this).attr('href') );
		window.open( popupLink, 'popup', 'width=920,height=780, scrollbars=yes');
		return false;
	});

	$('div.post-comments a').click(function(){ 
		if ($(this).parent().parent().parent().hasClass('blog-perma') ) {
			if (  $(this).parent().hasClass('hide-btn') ) {
				$('form#blog-comment').hide();
			} else {
				$(this).parent().addClass('hide-btn');
				$('form#blog-comment').show();
			}
			return false;	
		}
		
	});

});

(function($){ 
	
	$.fn.pickDates = function() {
		return this.each(function() {
			var tables = $('#months-wrapper', this);
			var arrive = true;
			var sIndex, sDate, tmpIndex;
			
			$('td:not(.past, .na, .empty)', tables).click(function() {

				if(arrive) {
					sIndex = $('td', tables).index($(this)[0]);
					sDate = createDate(this);
					
					tables.find('.selected').removeClass('selected');
					$(this).addClass('selected');
					$('#arrive').val(sDate);
					$('#depart').val('');
					
					arrive = !arrive;
				} else {
					var dIndex = $('td', tables).index($(this)[0]);
					var bool = true;
					tmpIndex = sIndex;
					
					if(sIndex!=dIndex) {
						if(dIndex<sIndex) {
							var lower = true;
							sIndex = dIndex;
							dIndex = tmpIndex;
						}
						
						for(var x=sIndex; x<dIndex; x++) {
							if($('td:eq('+x+')', tables).hasClass('na')) {
								bool = false;	
								break;
							}
						}
						if(bool) {
							var dDate = createDate(this);
							
							for(x+1; x>sIndex; x--)
								$('td:eq('+x+'):not(.empty)', tables).addClass('selected');
							$(this).addClass('selected');
							
							if(lower) {
								$('#arrive').val(dDate);
								$('#depart').val(sDate);
							} else
								$('#depart').val(dDate);	
							
							arrive = !arrive;
						} else {
							alert("This date range already contains a reservation.  Please try again.");
							sIndex = tmpIndex;
						}
					} else {
						$('#arrive').val('');
						$(this).removeClass('selected');
						arrive = !arrive;	
					}
				}
			}).css('cursor', 'pointer');
		});
	};
	
	function createDate(obj) {
		var tmpDate = $(obj).parents('.cal-month').attr('id').split('-');
		var tmpNum = $(obj).html();
		
		var nDate = new Date(tmpDate[2]+"/"+tmpDate[1]+"/"+tmpNum);
		nDate = formatDate(nDate, "MM/dd/yyyy" );
		
		return nDate;
	}
	
	$.fn.resetForm = function() {
		return this.each(function() {
			$(':input', this).not(':checkbox, :radio, :submit, :reset').val('');
			$(':checkbox, :radio', this).removeAttr('checked');
			$(':input.date', this).val('mm/dd/yyyy');
		});
	};
	
	$.fn.checkNum = function() {
		return this.each(function() {
			if(Number($(this).html())<1)
				$(this).parent().hide();		
		});
	};
	
	$.fn.getScroll = function() {
		  var yScroll = 0;
		  if( typeof( window.pageYOffset ) == 'number' )
			yScroll = window.pageYOffset;
		  else if( document.body && document.body.scrollTop )
			yScroll = document.body.scrollTop;
		  else if( document.documentElement && document.documentElement.scrollTop)
			yScroll = document.documentElement.scrollTop;
			
		  return yScroll;
	};
		  
	$.fn.controlActResults = function() {
		return this.each(function() {
			var results = $(this);
			var cartFee = parseFloat($('.extra-cost td', results).text().replace(/\$/ig, ""));
			var players = parseFloat($('.summary-players td', results).text());
			
			$('input', results).click(function() {
				var row = $(this).parents('tr');
				var place = $('.result-place', row).text()||'--';
				var time = $('.result-time', row).text()||'--';
				var fee = parseFloat($('.result-cost', row).text().replace(/\$/ig, ""))||0;
				
				$('.summary-place td', results).text(place);
				$('.summary-time td', results).text(time);
				$('.summary-cost span', results).text(fee-cartFee>0?fee-cartFee:0);
				$('.activity-total span', results).text(fee*players);
				
				row.addClass('checked').siblings().removeClass('checked');										
			});	
		});
	};
	
	$.fn.coFormClear = function() {
		return this.each(function() {
			this.trigger('reset');
			$('#days', this).trigger('change');	
			$('.validation-error', this).remove();
		});
	};
	
	$.fn.tabbed = function() {
		return this.each(function() {
			var hash = null;
			if(window.location.hash)
				hash = window.location.hash;
			
			$('> ul:eq(0) a', this).click(function() {
				$(this).parent().addClass('current').siblings().removeClass('current');
				$( $(this).attr('href') ).show().siblings('div').hide();
				return false;
			});
			
			if(hash!=null) {
				$('> ul:eq(0) '+hash+'-link', this).addClass('current').children('a').trigger('click');
			} else
				$('> ul:eq(0) li:eq(0)', this).addClass('current').children('a').trigger('click');
		});	
	};
	
	var count = 0;
	$.fn.scrollable = function(options) {
		var defaults = {
			dir		: 'h',
			dist	: null,
			speed	: 'slow',
			mover	: '#months-wrapper',
			moved	: '.cal-month',
			moveNum	: 1,
			display	: 3
		}
		var opts = $.extend(defaults, options);
		return this.each(function(){
			var obj = $(this);
			if(opts.dist==null) {
				if(opts.dir=='v')
					opts.dist = getDimensions(opts.moved, 'h');
				else
					opts.dist = getDimensions(opts.moved, 'w');
			}
			$('.scroll-controls', obj).each(function() {
				var total = $(opts.moved).length-opts.display;
				testPos(total, obj);
				$('.scroll,', this).click(function() {
					if($(this).hasClass('next')) {
						opts.move = '-';
						count+=opts.moveNum;
					}
					else {
						opts.move = '+';
						count-=opts.moveNum;
					}
					testPos(total, obj);
					$(opts.mover, obj).getAnimate(opts);
					return false;
				});
			});
		});
		
		function getDimensions(el, string) {
			if(string=='h')
				return $(el).width()+parseInt($(el).css('margin-top'))+parseInt($(el).css('margin-bottom'))+parseInt($(el).css('border-top-width'))+parseInt($(el).css('border-bottom-width'));
			else
				return $(el).width()+parseInt($(el).css('margin-left'))+parseInt($(el).css('margin-right'))+parseInt($(el).css('border-left-width'))+parseInt($(el).css('border-right-width'));
		}
	};
	
/*	$.fn.moveCal = function() {
		return this.each(function() {
			var arrive = $('#arrive', this).val();
			var date = arrive.split('/');
			var owsid = $('#owsid', this).val();
			var id = $('#unit-id', this).val();
			var days = $('#days', this).val();
			if($('.cal-month').index($('#cal-'+date[0]+'-'+date[2]))!=-1) {
				
				$('#rates-wrapper').load('hilton-head-unit-check.php?ID='+id+' #rates-loader',
				{arrive: arrive, days: days, ID: id, owsid: owsid},
				function() {
					$('#scroll-cal').scrollable({dist: 203});
					count = $('.cal-month').index($('#cal-'+date[0]+'-'+date[2]));
					var total = $('.cal-month').length-4;
					if(count!=-1) {
						var opts = {
							dir		: 'h',
							move	: '-',
							dist	: 203,
							speed	: 'slow',
							func 	: ''
						};
						var moved = opts.dist*count;
						opts.moveNum = moved/opts.dist;
						testPos(total, $('#scroll-cal'));
						
						if(!$('.cal-month:eq('+count+')').isAvailable())
							opts.func = function() { alert("This range is not available, please try again"); $('#rates-submit').attr('disabled', 'disabled').css({opacity: .5, filter: 'alpha(opacity=30)'}); };
						else
							$('#rates-submit').removeAttr('disabled').css({opacity: 1, filter: 'alpha(opacity=100)'});
						$('#months-wrapper').getAnimate(opts);
					}
				});
			} else
				alert("Date out of range, please try again.");
		});
	};

	$.fn.isAvailable = function() {
		var bool = true;
		$('.selected', '#months-wrapper').each(function() {
			if($(this).hasClass('na'))
				bool = false;
		});
		return bool;
	} */	
	
	function testPos(total, obj) {
		if(count==0) {
			$('.prev', obj).css('visibility', 'hidden');
			$('.next', obj).css('visibility', 'visible');
		}
		else if(count>=total) {
			$('.next', obj).css('visibility', 'hidden');
			$('.prev', obj).css('visibility', 'visible');
		}
		else
			$('.scroll', obj).css('visibility', 'visible');
	}
		
	$.fn.getAnimate = function(opts) {
		switch(opts.dir) {
			case 'h':
				this.animate({left: opts.move+"="+(opts.dist*opts.moveNum)+"px"}, opts.speed, opts.func);
				break;
			case 'v':
				this.animate({top: opts.move+"="+(opts.dist*opts.moveNum)+"px"}, opts.speed, opts.func);
				break;
		}
	};

	$.fn.clearField = function(settings) {		
		settings = jQuery.extend({
			blurClass: 'clearFieldBlurred',
			activeClass: 'clearFieldActive',
			attribute: 'rel',
			value: ''
		}, settings);
		return $(this).each(function() {			
			var el = $(this);
			settings.value = el.val();
			if(el.attr(settings.attribute) == undefined) {
				el.attr(settings.attribute, el.val()).addClass(settings.blurClass);
			} else {
				settings.value = el.attr(settings.attribute);
			}
			el.focus(function() {
				if(el.val() == el.attr(settings.attribute)) {
					el.val('').removeClass(settings.blurClass).addClass(settings.activeClass);
				}
			});
			el.blur(function() {
				if(el.val() == '') {
					el.val(el.attr(settings.attribute)).removeClass(settings.activeClass).addClass(settings.blurClass);
				}
			});
		});
	};

})(jQuery);

function startWeek() {
	$('a', '.day-link').click(function() {
		$('.current', '#weeks').removeClass('current');							 
		$(this).parents('.day').addClass('current');
		var vars = getQuery(this.href);
		$.get("includes/show-day.php", {year: vars['year'], month: vars['month'], week: vars['week'], day: vars['day']}, function(data) {
			$('#events-wrapper').remove();
			$(data).insertAfter($('#week-wrapper'));																									 
		});
		return false;
	});	
	
	/*$('a', '.week-arrow').click(function() {
		var vars = getQuery(this.href);
		$.get("includes/show-week.php", {year: vars['year'], month: vars['month'], week: vars['week']}, function(data) {
			$('#week-wrapper').remove();
			$(data).insertAfter($('#scroll-event'));
			startWeek();			
		});
		

		
		return false;
	});	*/
}

function getQuery(lnk) {
	var vals = lnk.split("?");
	var qString = vals[1].split("&");
	var keys = new Array();
	$(qString).each(function(i) {
		var pair = qString[i].split("=");
		keys[pair[0]] = pair[1];
	});
	return keys;
}

/*function moveRateCal(cal) {
	$(cal).moveCal();
}*/
  
