/**
 * Harbor Grand site-wide scripts
 */

/* Newsletter signup */
var NewsletterSignup = {
	/**
	 * The field settings
	 */
	fields : {
		fname : {
			id : 'CLFullName',
			def : 'full name'
		},
		email : {
			id : 'CLEmailAddress',
			def : 'email address'
		},
		captcha : {
			id : 'captcha-image',
			isShowing : false
		}
	},
	/**
	 * Function to handle revealing the captcha if it is hidden
	 */
	handleCaptcha : function () {
		/* See if the captcha is hidden */
		if (NewsletterSignup.fields.captcha.isShowing === true) {
			return;
		}
		
		/* Show the captcha */
		NewsletterSignup.fields.captcha.isShowing = true;
		jQuery('#' + NewsletterSignup.fields.captcha.id).show();
	},
	/**
	 * When the email field is blurred
	 */
	onEmailBlur : function () {
		jQuery(this).removeClass('active');
		if (jQuery(this).val() == '') {
			jQuery(this).val(NewsletterSignup.fields.email.def);
		}
	},
	/**
	 * When the email field is focused
	 */
	onEmailFocus : function () {
		jQuery(this).addClass('active');
		if (jQuery(this).val() == NewsletterSignup.fields.email.def) {
			jQuery(this).val('');
		}
		NewsletterSignup.handleCaptcha();
	},
	/**
	 * When the first name field is blurred
	 */
	onFnameBlur : function () {
		jQuery(this).removeClass('active');
		if (jQuery(this).val() == '') {
			jQuery(this).val(NewsletterSignup.fields.fname.def);
		}
	},
	/**
	 * When the first name is focused
	 */
	onFnameFocus : function () {
		jQuery(this).addClass('active');
		if (jQuery(this).val() == NewsletterSignup.fields.fname.def) {
			jQuery(this).val('');
		}
		NewsletterSignup.handleCaptcha();
	},
	/**
	 * Sets up the field listeners
	 */
	setup : function () {
		/* Listener links */
		jQuery('#' + NewsletterSignup.fields.fname.id).focus(NewsletterSignup.onFnameFocus);
		jQuery('#' + NewsletterSignup.fields.fname.id).blur(NewsletterSignup.onFnameBlur);
		jQuery('#' + NewsletterSignup.fields.email.id).focus(NewsletterSignup.onEmailFocus);
		jQuery('#' + NewsletterSignup.fields.email.id).blur(NewsletterSignup.onEmailBlur);
		
		/* Default form values */
		jQuery('#' + NewsletterSignup.fields.fname.id).val(NewsletterSignup.fields.fname.def);
		jQuery('#' + NewsletterSignup.fields.email.id).val(NewsletterSignup.fields.email.def);
		
		/* Hide the captcha field to start */
		jQuery('#' + NewsletterSignup.fields.captcha.id).hide();
		
	}
};


/**
 * A simple animated gallery object for the site header images
 * @param The options
 * 	- container : the containing element
 * 	- frequency : how often the animations happen
 * 	- speed : the animation speed
 */
function HeaderGallery (o) {
	/* Save the options */
	this.config = o;
	this.index = 0;
	this.items = null;
	
	/* Check for a valid config */
	if (!this.config || !this.config.container || !this.config.frequency || !this.config.speed) {
		throw('HeaderGallery.construct: The configuration passed was missing some vital information.');
	}
	
	/* Run the setup utility */
	this.setup();
}
/* Animates to the next image in the gallery */
HeaderGallery.prototype.doNext = function () {
	/* Update the z-index of the current element */
	this.items.eq(this.index).css('zIndex', 2);
	
	/* See if this is a loop */
	var nextImage = (this.items.length <= this.index + 1) ? 0 : this.index + 1;
	
	/* Position the next image under the current one */
	this.items.eq(nextImage).css({
		'zIndex' : 1,
		'display' : 'inline',
		'opacity' : (this.config.fadein) ? 0 : 1
	});
	if (this.config.fadein) {
		this.items.eq(nextImage).animate({opacity : 1}, this.config.speedFadeIn);
	}
	
	/* Fade out the current image */
	var _this = this;
	this.items.eq(this.index).fadeOut(this.config.speed, function () {
		_this.onAnimate();
	});
	this.index = nextImage;
}
/* Runs when the animation between images finishes */
HeaderGallery.prototype.onAnimate = function () {
	/* Start the timer */
	var _this = this;
	this.items.eq(this.index).animate({opacity : 1}, this.config.frequency, function () {
		_this.onTimer();
	});
}
/* Runs when the timer elapses */
HeaderGallery.prototype.onTimer = function () {
	/* Do the next image */
	this.doNext();
}
/* Sets up the gallery for animation */
HeaderGallery.prototype.setup = function () {
	/* Find all the images */
	this.items = this.config.container.children();
	
	/* See if we even have a gallery */
	if (!this.items || this.items.length <= 1) {
		return;
	}
	
	/* Init the z-indices */
	this.items.each(function (i) {
		jQuery(this).css({
			'zIndex' : (i == 0) ? 2 : 1,
			'display' : (i == 0) ? 'inline' : 'none',
			'position' : 'absolute'
		});
	});
	
	/* Start the timeout */
	this.onAnimate();
};


/**
 * Object containing the header gallery instances
 */
var Galleries = {
	/**
	 * The site heading gallery
	 */
	header : null,
	/**
	 * The homepage gallery
	 */
	home : null,
	/**
	 * Sets up the gallery items
	 */
	setup : function () {
		/* Start up the heading gal */
		Galleries.header = new HeaderGallery({
			container : jQuery('.page-header .header-slideshow'),
			speed : 4000,
			frequency : 5000
		});
		
		/*
		
		jQuery('.page-header .header-slideshow').galleria({
			width : 720,
			height : 220,
			showInfo : false,
			carousel : false
		});
		
		 */
		
		/* See if we have the homepage or not */
		if (jQuery('#homepage-announcements .announcement-gallery').size() > 0) {
			Galleries.home = new HeaderGallery({
				container : jQuery('#homepage-announcements .announcement-gallery'),
				speed : 3000,
				frequency : 5000
			});
		}
	}
};


/**
 * The page galleries
 */
var PageGallery = {
	/**
	 * Sets up the links to fancybox
	 */
	setup : function () {
		/* Apply the fancybox on to all gallery links */
		var elems = jQuery('div.page-gallery').find('a');
		elems.fancybox();
	}
};


/**
 * Booking and rates scripts
 */
var BookRates = {
	/**
	 * Handles the pciking of a date from one of the widgets
	 * @param String
	 * @param Object The instance of jquery containing the span tag representing the selected date
	 * @param Object The form fields to modify {day, month, year} 
	 */
	onCheckDate : function (date, textObject, formElements) {
		/* Update the date input fields */
		var dateMonthsShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
		formElements.day.val(date.selectedDay);
		formElements.month.val(dateMonthsShort[date.selectedMonth]);
		formElements.year.val(date.selectedYear);
		
		/* Update the notice text */
		var dateMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			dateText = dateMonths[date.selectedMonth] + ' ' + date.selectedDay + ', ' + date.selectedYear;
		textObject.text(dateText);
	},
	/**
	 * Runs when the form is reset
	 */
	onReset : function (form) {
		/* Clear the date notices */
		jQuery('#check-in-date').text('No date selected');
		jQuery('#check-out-date').text('No date selected');
		
		/* Call the setup again */
		BookRates.setup();
	},
	/**
	 * Runs before form submissions
	 */
	onSubmit : function (form) {
		
	},
	/**
	 * Sets up the calendar selection buttons
	 */
	setup : function () {
		/* See if the buttons are present */
		var button_in = jQuery('#check-in-pick'),
			button_out = jQuery('#check-out-pick'),
			button_in_dummy = jQuery('#check-in-dummy'),
			button_out_dummy = jQuery('#check-out-dummy');
		if (!button_in || !button_out) {
			return;
		}
		
		/* Attach the calendar */
		button_in.click(function () {
			button_in_dummy.datepicker('show');
		});
		button_in_dummy.datepicker({
			onSelect : function (dateText, inst) {
				/* Update the date values */
				BookRates.onCheckDate(inst, jQuery('#check-in-date'), {
					day : jQuery('input[name=inday]'),
					month : jQuery('input[name=inmonth]'),
					year : jQuery('input[name=inyear]')
				});
				
				/* Alter the min check out date */
				button_out_dummy.datepicker('option', 'minDate', new Date(parseInt(inst.selectedYear), parseInt(inst.selectedMonth), parseInt(inst.selectedDay) + 1));
				button_out_dummy.datepicker('enable');
			},
			duration : '',
			minDate : new Date(),
			numberOfMonths : 2,
			changeMonth : false,
			changeYear : false
		});
		button_out.click(function () {
			button_out_dummy.datepicker('show');
		});
		button_out_dummy.datepicker({
			altField : '#check-out-date',
			altFormat : 'DD, d MM, yy',
			onSelect : function (dateText, inst) {
				BookRates.onCheckDate(inst, jQuery('#check-out-date'), {
					day : jQuery('input[name=outday]'),
					month : jQuery('input[name=outmonth]'),
					year : jQuery('input[name=outyear]')
				});
			},
			duration : '',
			minDate : new Date(),
			numberOfMonths : 2,
			changeMonth : false,
			changeYear : false
		});
		button_out_dummy.datepicker('disable');
	}
}


/**
 * Email insert utility
 */
var Email = {
	/**
	 * Sets up all instances found
	 */
	setup : function () {
		/* Find the instances of the email insert */
		var instances = jQuery('span.insert-email');
		
		/* Loop through instances */
		instances.each(function (i) {
			/* Find the elements */
			var inst = instances.eq(i),
				user = inst.children('span.u').text(),
				domain = inst.children('span.d').text(),
				tld = inst.children('span.t').text();
			
			/* Form the link */
			if (!user || !domain || !tld) {
				return;
			}
			var eml = user + '@' + domain + '.' + tld,
				link = '<a href="mailto:' + eml + '?subject=Hello from harborgrand.com">' + eml + '</a>';
			inst.html(link);
		});
	}
};


/**
 * A privacy policy link hook
 */
var PrivacyPolicy = {
	/* The name of the class signifying the privacy policy links */
	className : 'link_privacy_policy',
	/* The pop up window information */
	winName : 'privacyPolicy',
	winHeight : 400,
	winWidth : 550,
	
	/**
	 * Runs when a privacy policy link is clicked
	 * @param Event
	 */
	onLinkClick : function (event) {
		/* Make sure we have a target */
		if (!event.target) {
			event.target = event.srcElement;
		}
		
		/* Pull out the href and start up a popup window */
		var href = event.target.href;
		window.open(href, PrivacyPolicy.winName, 'width='+PrivacyPolicy.winWidth+',height='+PrivacyPolicy.winHeight+',menubar=0,toolbar=0,location=0,status=0,resizable=1,scrollbars=1');
		
		/* Make sure the default behavior does not occur */
		return false;
	},
	/**
	 * Sets up the link
	 */
	setup : function () {
		/* Find the links on the page */
		jQuery('a.' + PrivacyPolicy.className).click(PrivacyPolicy.onLinkClick);
	}
};


/**
 * Catch any pages with a _feature target window
 */
var FeaturedLinks = {
	/* Target page name */
	pageName : '_feature',
	/* Window properties */
	winHeight : 600,
	winWidth : 900,
	
	/**
	 * Responds to the link being clicked on
	 */
	onLinkClick : function (event) {
		/* Calculate the position and open the window */
		window.open(event.currentTarget.href, FeaturedLinks.pageName, 'width=' + FeaturedLinks.winWidth + ',height=' + FeaturedLinks.winHeight + ',menubar=0,toolbar=0,location=0,status=0,resizable=1,scrollbars=1');
		
		/* Break normal link operation */
		return false;
	},
	/**
	 * Sets up the links
	 */
	setup : function () {
		/* Attach the links */
		jQuery('a[target=' + FeaturedLinks.pageName + ']').click(FeaturedLinks.onLinkClick);
	}
};


/* Hook page load */
jQuery.noConflict();
if (jQuery) {
	jQuery(function () {
		NewsletterSignup.setup();
		Galleries.setup();
		Email.setup();
		PageGallery.setup();
		BookRates.setup();
		PrivacyPolicy.setup();
		FeaturedLinks.setup();
	});
}

