/* global js */	

function global()
{
	var bodyBkg = new Image();
	$(bodyBkg).attr('src','/img/bkgnd-full-elcap-1600x1050.jpg').load( function()
		{
			$('#contentbk').fadeTo(50,0.80);
			$('body').attr('class', function() { return this.className.replace(/ low/gi, ''); });
		});
		
	setNavUI();
	setVBoxes();
	//setResn();  // temporarily disable ajax form on the home page
	
	if ($('#reservationsPanel').length > 0) { setResForm(); }
}

function setResn()
{
	$(document).bind('showform.resn', function()
	{
		$('#content').css('float', function()
		{
			$('#header').after('<div class="rightResn" />').after('<div class="shadowResn" />').animate( { 'left' : '-500px' } , 1500);
			$('.shadowResn').fadeTo(100,0.50).css('display', function()
			{
				$('.rightResn').fadeTo(100,0.95).animate( { 'left' : '-500px' } , 1000 , function() 
				{
					$('.shadowResn').css('background-position', ( $(this).offset().left  - 70 ) + 'px 18px').click( function()
					{
						$(document).trigger('hideform.resn');
					});
					$(this).html('<p class="resn-heading">Reservations Request Form</p><p class="close"><a href="#">close this</a></p><iframe frameborder="no" scrolling="no" height="1600px" width="100%" src="http://www.aboutyosemite.com/reservations/?r=3"></iframe>');
					$('p.close',this).click( function()
					{
						$(document).trigger('hideform.resn');
					});
				});
				return 'block';
			});
			return 'left';
		}).animate( { 'left' : '-500px' } , 1500);
		return false;
	});
	
	$(document).bind('hideform.resn', function()
	{
		$('.rightResn').remove();
		$('.shadowResn').remove();
		$('#header').animate( { 'left' : '0px' } , 1500);
		$('#content').animate( { 'left' : '0px' } , 1500).css('float', 'none');
		$('.vbox-container > div').trigger('leftcomplete.vbox');		
	});
	
	$('#reservations-cta a').click( function ()
	{
		$(document).trigger('showform.resn');
		return false;
	});
	$('#reservations-cta').click( function ()
	{
		$('a', this).click();
	});
}

function setVBoxes()
{
	if (!$('.vbox-container').length)
		return false;

	$.fn.vboxes = function ()
	{
		return this.each(function()
			{	
				var cont = $('> div', this),
				slide = $('> ul', cont),
				items = $('> li',slide),
				itemXDim = $(items).filter(':first').outerWidth(),
				contXDim = $(cont).innerWidth(),
				isPaused = false,
				linksInit = false;
				
				function gup( u, n )
				{
				  n = n.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
				  var regexS = "[\\?&]"+n+"=([^&#]*)";
				  var regex = new RegExp( regexS );
				  var results = regex.exec( u );
				  if( results == null )
					return "";
				  else
					return results[1];
				}

				$(slide).css('width', $(items).length * itemXDim );
									
				$(this).bind('start.vbox leftcomplete.vbox', function() {
					if (isPaused) { return false; }
					 $('> ul', cont).animate( { 'left' : - itemXDim } , 4000, function () { 
						$(this).css('left', function()
						{
							$('li:first', this).clone().appendTo( this );
							$('li:first', this).remove();
							return 0;
						});
						$(cont).trigger('leftcomplete.vbox');
					});
				} );
				
				$(this).bind('rightcomplete.vbox', function() {
					if (isPaused) { return false; }
					slide = $('> ul', cont);
					$(slide).css('left', function ()
					{
						$('li:last', this).clone().prependTo( this );
						$('li:last', this).remove();
						return parseInt($(this).css('left')) - itemXDim;
					});
					$(slide).animate( { left : 0 } , 4000 , function () { 
						$(cont).trigger('rightcomplete.vbox'); 
					});
				} );
				
				$(this).bind('seek.vbox', function(e,a,b) {
					if (b == 0) { return false; }
					var pos = parseInt(b / itemXDim);
					if (a)
					{	// move left
						for (var ct = 1; ct <= pos; ct++)
						{
							slide = $('> ul', cont);
							$(slide).css('left', function() {
								$('li:first', this).clone().appendTo( slide );
								$('li:first', this).remove();
								return parseInt($(this).css('left')) + itemXDim;
							});						
						}
						$(slide).animate( { left : 0 } , 1000);
					}
					else
					{	// move right
						var len = $(items).length;
						for (var ct = 0; ct < pos; ct++)
						{
							slide = $('> ul', cont);
							$(slide).css('left', function()
							{
								$('li:nth-child(' + len + ')', this).clone().prependTo(slide);
								$('li:nth-child(' + (len + 1) + ')', this).remove();
								return parseInt($(this).css('left')) - itemXDim;
							});
						}
						$(slide).animate( { left : 0 } , 1000 );
					}
				} );
				
				$(this).bind('stop.vbox', function()
				{
					$('> ul:animated', cont).stop();
					$('> ul', cont).animate( { left : 0 } , 250 );
					return true;
				});
				
				$(this).bind('makeactive.vbox', function(e,a)
				{
					pos = $(this).offset();
					yc = gup( $(a).attr('href') , 'v');
					$("<div>&nbsp;</div>").attr('id', 'activeVboxShadow').appendTo( $('body') ).css('display', function ()
					{
						$(this).fadeTo(10,0.30);
						return 'block';
					});
					$("<div></div>").attr('id','activeVbox').appendTo( $('body') ).delay(1000).css( { 'top' :  (pos.top + 73) + 'px' , 'left' : (pos.left  + itemXDim * 3 + 90)  + 'px' , 'width' : '0' , 'height' : '0'  } ).animate(
					{ 'top' :  (pos.top - 45)  + 'px' , 'left' : (pos.left  + itemXDim * 3 - 80) + 'px' , 'width' : '340px' , 'height' : '240px' } , 500 , function()
					{
						$('#activeVbox').append('<p class="close"><a href="#">close this</a></p><div id="swfMovie"></div>');
						swfobject.embedSWF("http://www.youtube.com/v/" + yc + "&hl=en_US&fs=1&rel=0&autoplay=1", "swfMovie", "340", "240", "9.0.115", "expressInstall.swf");
						$('.close a',this).click( function()
						{
							$(cont).trigger('remove.vbox');
						});
						$('#activeVboxShadow').click( function()
						{
							$(cont).trigger('remove.vbox');
						});
					});
				});
				
				$(this).bind('remove.vbox', function(e)
				{
					pos = $(cont).offset();
					$('#activeVbox').animate( { 'top' :  (pos.top + 17) + 'px' , 'left' : (pos.left  + itemXDim * 3 + 17)   + 'px' , 'width' : '150px' , 'height' : '115px' } , 250 , function()
					{
						$('#activeVboxShadow').remove();
						swfobject.removeSWF("swfMovie");
						$(this).remove();
						isPaused = false;
						$(cont).trigger('leftcomplete.vbox');
					})
				}
				)
				
				$(this).bind('initlinks.vbox', function(e) 
				{
					$('li a', e.target).hover( function(e)
					{
						$(this).prepend('<img id="playButton" src="/img/play-button.png" />').find('img:last').fadeTo(50,0.6);
						$('#playButton', this).css( {'position' : 'absolute', 'top' : '15px', 'left' : '15px' });
					}, function()
					{
						$('#playButton', this).remove();
						$('img', this).fadeTo(50,1.0);
					});
					$('li a', e.target).click( function(e)
					{
						var cp = parseInt( $(this).parent().position().left - itemXDim * 3 );
						var dir = (cp > 0);
						var pos = Math.abs(cp);
						$(cont).trigger('seek.vbox', [dir , pos]);
						$(cont).trigger('makeactive.vbox', [e.currentTarget]);
						return false;
					});
					linksInit = true
				});
				
				$(this).bind('killlinks.vbox', function(){
					$('img#playButton').remove();
					$(this).unbind('li a', 'mouseover mouseout click');
					linksInit = false;
				});
				
				$(cont).bind('mouseover.vbox', function(event){
					if (!isPaused)
					{
						if (!linksInit)
						{
							$(cont).trigger('initlinks.vbox');
						}
						$(cont).trigger('stop.vbox');
						isPaused = true;
						// $(this).bind('mouseout.vbox', function(event)
						// {
							// if ( $(event.relatedTarget).closest('div') == $(cont) || !isPaused ) { return false; }
							// isPaused = false;
							// $(cont).trigger('killlinks.vbox');
							// $(cont).trigger('leftcomplete.vbox');			
						// });
					}
				});
				
				$(cont).trigger('start.vbox');
			});
			
	}		
	
	$('.vbox-wrap').vboxes();
}

function setNavUI()
{
	$('#header .topNav li').each( function() {
		$(this).hover(function() 
		{
			$(this).addClass('expand-link').addClass('selected').animate( { padding: '12px 16px 16px' } , 250).prev('li').addClass('selected').animate( 
				{ 'top' : (parseFloat($(this).css('top')) - 4) + 'px' , 'left' : (parseFloat($(this).css('left')) - 4) , 'padding' : '16px 18px' } , 275 , function() { $(this).fadeTo(100, 0.14); });
		},
		function()
		{
			$(this).animate( { padding: '4px 8px 8px' } , 100).removeClass('selected').prev('li').removeClass('selected').animate( 
				{ 'top' : (parseFloat($(this).css('top')) - 2) + 'px' , 'left' : (parseFloat($(this).css('left')) - 2) , 'padding' : '4px 8px 8px' } , 80 , function() { $(this).fadeTo(100, 0.22); });
		}).click(function()
		{
			document.location.href = $(this).find('a').attr('href');
			return false;
		});
		$(this).clone().attr( { 'id' : $(this).attr('id') + '-shadow', 'class' : 'shadow' }).css(
			{ 'top' : (parseFloat($(this).css('top')) - 2) + 'px' , 'left' : (parseFloat($(this).css('left')) - 2) + 'px' , 'background-position' : $(this).css('background-position') }
		).hover(function() { $(this).next().mouseover(); }, function() { $(this).next().mouseout(); } ).click( function() { $(this).next().click(); return true; }).fadeTo(1,0.22).insertBefore(this).find('a').css('font-size', function() {  return $(this).closest('li').next().find('a').css('font-size'); });
	});
}

function setResForm()
{
	/* load validation script and set validation rules */
	$.getScript("http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js", function()
	{
		/* set validation on form */
		$.validator.addMethod("phoneUS", function(phone_number, element) 
		{
			phone_number = phone_number.replace(/\s+/g, ""); 
			return this.optional(element) || phone_number.length > 9 &&
			phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
		}, "Please provide a valid phone number with area code");
		$.validator.addMethod("remarks", function(remarks, element) 
		{
			url_clear = (remarks.match(/[A-Za-z0-9-:\.\/]+\.[A-Za-z]{2,4}/) == null);
			if (!url_clear)
			{
				$(element).val(remarks.replace(/[A-Za-z0-9-:\.\/]+\.[A-Za-z]{2,4}/, ' '));
			}
			return url_clear;
		}, "This section is for questions and comments only. No website addresses, please.");
		$("form").validate({
		   rules: {
			 name: "required",
			 email: {
			   required: true,
			   email: true
			 },
			 phone : {
				required : false,
				phoneUS : true
			 },
			 remarks : {
				required : false,
				remarks : true
			 }
		   },
		   messages: {
			 name: "Please specify your name",
			 email: {
			   required: "We need your email address to contact you",
			   email: "Your email address must be in the format of name@domain.com"
			 }
		   }
		});
	});
	/* set stay dates fields */
	if ( $('ul#stayDate').length > 0)
	{
		var d = new Date();
		if (!$("select[name='arriveMonth'] option[selected]").length)
		{
			$("select[name='arriveMonth'] option[value='" + (d.getMonth() +1) + "']").attr('selected', 'selected');
		}
		if (!$("select[name='arriveDay'] option[selected]").length)
		{
			$("select[name='arriveDay'] option[value='" + (d.getDate() +1) + "']").attr('selected', 'selected');
		}			
		$('ul#stayDate').append( $('<li />').css('width', function () { $('ul#stayDate li').hide(); return '100%'; } ).append( $('<div />').attr('id','datepicker') )  );
		$('#datepicker').datepicker({
			numberOfMonths: 2,
			showButtonPanel: false,
			dateFormat: 'yy-m-d',
			onSelect : function (dateText, inst)
			{
				 var dp = dateText.split("-");
				 $("select[name='arriveYear'] option[selected]").attr('selected', '');
				 $("select[name='arriveYear'] option[value=" + dp[0] + "]").attr('selected', 'selected');
				 $("select[name='arriveMonth'] option[selected]").attr('selected', '');
				 $("select[name='arriveMonth'] option[value=" + dp[1] + "]").attr('selected', 'selected');
				 $("select[name='arriveDay'] option[selected]").attr('selected', '');
				 $("select[name='arriveDay'] option[value=" + dp[2] + "]").attr('selected', 'selected');
			}
		});
		var curdate = $("select[name='arriveYear']").val() + '-' +
					$("select[name='arriveMonth']").val()  + '-' +
					$("select[name='arriveDay']").val();
		$('#datepicker').datepicker("setDate",curdate);
	}
	/* set optional dates field */
	$('a#infoonly').click( function()
	{
		$toollink = $(this).fadeOut(500);
		if ( $(this).attr('href') == '#infoonly')
		{	
			$('#stayDate').fadeOut(1000).prev('h2').fadeOut(1000);
			$('#nightCount').fadeOut(1000).prev('h2').fadeOut(1000, function()
			{
				$toollink.attr('href', '#seenights').html('I want to specify a date and length of stay').fadeIn(1000);
			});
		}
		else if ( $(this).attr('href') == '#seenights')
		{
			$('#stayDate').fadeIn(500).prev('h2').fadeIn(500);
			$('#nightCount').fadeIn(500).prev('h2').fadeIn(500, function()
			{
				$toollink.attr('href', '#infoonly').html('Not sure about when you&rsquo;d like to stay, or just have a question about the selected property?').fadeIn(500);
			});
		}
		return false;				
	});
	/* set field watermarks */
	$("#phonefield").each( function ()
	{
		if ($(this).val() != '') { return false; }
		$(this).fadeTo(1, 0.5).addClass('wm').val('Your phone number (optional)').focus( function () { if ($(this).val() == 'Your phone number (optional)') { $(this).fadeTo(1,1).removeClass('wm').val(''); } } ).blur( function () {  if ($(this).val() == '') { $(this).fadeTo(1, 0.5).addClass('wm').val('Your phone number (optional)');  } });
	});
	var add_sel = false;
	$("#mailingAddress li").each( function() {
		if ($('input', this).val() == '') 
		{
			$('input', this).val( $('label', this).html() + ' (optional)').addClass('wm').fadeTo(1, 0.5).focus( function() { if ( $(this).hasClass('wm') ) { $("#mailingAddress li input").fadeTo(1, 1); $(this).val('').removeClass('wm'); } } ).blur( function() { if ($(this).val() == '') { $(this).addClass('wm').val( $(this).prev().html() + ' (optional)' ); } if ($('#mailingAddress li input.wm').length == 4)  $("#mailingAddress li input").fadeTo(1, 0.5); });
		} else { add_sel = true; }
		$('label', this).hide();
	});
	if (add_sel) { $("#mailingAddress li input").fadeTo(1,1); }
	$("form#resform").submit( function() 
	{
		$('input.wm', this).val('');
	});
	/* set property fields */
	if ( $("input[name='property']:checked").length == 0 )
	{
		$("input[name='property']:eq(0)").attr('checked','checked');
	}
	/* limit guest count to four */
	$("input[name='property']:checked").closest('div.propertyPanel').attr('class', 'propertyPanel selectedPropertyPanel');
	$("input[name='property']").change( function() { $('div.selectedPropertyPanel').attr('class', 'propertyPanel'); $(this).closest('div.propertyPanel').attr('class', 'propertyPanel selectedPropertyPanel'); if ($("input[name='property']:checked").val() == '2')
	{
		$('select[name=adults] option:gt(3)').remove();
	}} );
	$('div.propertyPanel').click( function() {  $(this).find("input[name='property']").attr('checked', 'checked').change();  } );
}

if (google)
{
	google.load("jquery", "1.4.2");
	google.load("jqueryui", "1.8.1");
	google.load("swfobject", "2.2");
	google.setOnLoadCallback(global);
}