/**
 * Common Javascript File
 *
 * Include any site wide javascript methods or functionality within
 * this file. This includes things such as menu's , tell a friend links,
 * bookmark page & google map stuff.
 *
 * @copyright  2010 Graphics Online
 * @author     $Author: gockwell $$
 * @version    $Id: common.js 42 2010-09-02 01:56:47Z gockwell $
 * @since      $Date: 2010-09-02 11:56:47 +1000 (Thu, 02 Sep 2010) $
 */

/**
 * Obtaining the "GET" URL parameters
 * 
 * The params are put into a property called params in the location object
 * http://example.com/?key=value
 * location.params.key = value
 */

location.params = new Object();

// check if there are actually GET params present
if (location.search != "") {

	// substring from the first character so we don't get the question mark itself in the string
	url_params_string = location.search.substring(1);

	// split the params into an array (array looks like ["param1=a", "param2=b"])
	url_params_array = url_params_string.split("&");

	// split each param into it's key/value pair and put it into an object
	
	for (i in url_params_array) {
		param = url_params_array[i];			// current param string in loop
		key = param.split("=")[0];				// getting the pieces
		value = param.split("=")[1];
		location.params[key] = value;			// putting the data into the object
	}
}
 
/**
 * Global Onload Method
 * currently this sets up the tell a friend popup in a lightbox as well as sets up the bookmark site link.
 */
$(function()
{
	// prompt for selection on "storage sizes" page if none is made when page is submitted
	$('#quote-form-sizes').submit(
		function()
		{
			// if no radio is selected
			if ($('#quote-form-sizes input:radio:checked').val() == undefined){
				// add a message, but only if the message isn't already present
				if ($('#quote-form-sizes input:image').next('div').length == 0) {
					$('#quote-form-sizes input:image').after('<div class="a-right">Please select a storage size</div>');
				}
				// dont submit the form yet
				return false;
			};
		}
	);

	jQuery.validator.addMethod(
		'phoneAust',
		function(phone_number, element)
		{
			phone_number = phone_number.replace(/[^\d]/g, '');
			return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)$/);
		},
		'Invalid phone number (include area code)'
	);

	/**
	 * Return true, if the value is a valid date, also making this formal check dd/mm/yyyy.
	 *
	 * @example jQuery.validator.methods.date("01/01/1900")
	 * @result true
	 *
	 * @example jQuery.validator.methods.date("01/13/1990")
	 * @result false
	 *
	 * @example jQuery.validator.methods.date("01.01.1900")
	 * @result false
	 *
	 * @example <input name="pippo" class="{dateITA:true}" />
	 * @desc Declares an optional input element whose value must be a valid date.
	 *
	 * @name jQuery.validator.methods.dateITA
	 * @type Boolean
	 * @cat Plugins/Validate/Methods
	 */
	jQuery.validator.addMethod(
		"dateITA",
		function(value, element) {
			var check = false;
			var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
			if( re.test(value)){
				var adata = value.split('/');
				var gg = parseInt(adata[0],10);
				var mm = parseInt(adata[1],10);
				var aaaa = parseInt(adata[2],10);
				var xdata = new Date(aaaa,mm-1,gg);
				if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
					check = true;
				else
					check = false;
			} else
				check = false;
			return this.optional(element) || check;
		}, 
		"Please enter a correct date"
	);
	
	// "Get a Quote" page
	if ($('FORM#quote-form').length === 1) {

		/**
		 * Setting the storage size option if it has already been set
		 * from the "storage sizes" form, which is passed as a GET param
		 */
		// if there's a value for the "size" GET param
		if (location.params.size != undefined) {
			// automatically choose the correct item
			$("select[name=StorageSize]")[0].selectedIndex = location.params.size;
		}
		
		$('FORM#quote-form').validate({
			rules: {
				FirstName: { required: true, minlength: 2 },
				LastName: { required: true, minlength: 2 },
				Email: { required: true, email: true },
				PhoneNumber: { required: true, phoneAust: true },
				StorageSize: { required: true },
				StorageDate: { required: true, dateITA: true },
				StorageLength: { required: true },
				Message: { required: true }
			}
		});
	}
	$('#StorageDate').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd/m/yy',
		showOtherMonths: true
	});

	/** Add custom site wide onload functionality here */
	
	// flyout menu (superfish & supersubs) '
	// i've applyed this menu to the top-menu
	if ($('ul.sf-menu').length) {
		$('ul.sf-menu').supersubs({ 
            	minWidth:    8,   // minimum width of sub-menus in em units 
            	maxWidth:    27,   // maximum width of sub-menus in em units 
            	extraWidth:  1  
        	}).superfish({
        		delay:       200,                            // one second delay on mouseout
        		speed: 		'fast', 						 // speed up the menu eh :)
            	animation:   {opacity:'show',height:'show'}  // fade-in and slide-down animation 
		});
	}
	
	
	// im going to auto fancybox any links with rel=fancybox for ease of use.
	if ($('a[rel=fancybox]')) {
		$('a[rel=fancybox]').fancybox({
			centerOnScroll		: true,
			transitionIn		: 'elastic',
			transitionOut		: 'elastic',
			titlePosition		: 'over'
		})
	}
	
	// attach fancybox to the send to friend link in the footer if both exist
	if ($.fancybox && $('#tellAFriend').length >= 1) {
		$('#tellAFriend').fancybox({
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'		: false,
			'width'				: 450,
			'height'			: 410,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'type'				: 'iframe'
		});
	}
	
	// attach a fancybox to our google map link , also apply a tipsy to the link itself.
	if ($.fancybox && $('#gmap, #gmap2').length >= 1) {
		$('#gmap, #gmap2').fancybox({
                'autoScale'             : false,
                'scrolling'             : 'no',
                'centerOnScroll'        : true,
                'overlayOpacity'        : 0.5,
                'overlayColor'          : '#000',
                'showNavArrows'         : false,
                'width'                 : 640,
                'height'                : 480,
                'transitionIn'          : 'elastic',
                'transitionOut'         : 'elastic',
                'type'                  : 'iframe'
        });

		$('#gmap-div').tipsy({
			gravity: 'n', fade: true
		});
	}
	
	
	// attach jquery bookmark plugin to the bookmark site link.
	if ($('#bookmarkSite').length >= 1) {
		$('#bookmarkSite').jFav();
	}
	
	
	// attach any form validation here
	
	// validate the contact us form.
	if ($('FORM#contact-form').length === 1) {
		$('FORM#contact-form').validate({
			rules: {
				Name: { required: true, minlength: 2 },
				Email: { required: true, email: true },
				Enquiry: { required: true },
				_captcha_code: { required: true, minlength: 5 }
			}
		});
	}
	
	
	// set our subscribe form on blur and focus events here - also attach validateSubscribeForm method to on submit..
	// @todo Fix this up so its alot nicers.
	if ($('FORM#subscribe-form INPUT[name=email]').length && $('FORM#subscribe-form INPUT[name=name]').length) {
		$('FORM#subscribe-form INPUT[name=email]').focus(function() { if ($(this).val() == 'Email Address') { $(this).val(''); } }).blur(function() { if ($(this).val() == '') { $(this).val('Email Address'); } });
		$('FORM#subscribe-form INPUT[name=name]').focus(function() { if ($(this).val() == 'Full Name') { $(this).val(''); } }).blur(function() { if ($(this).val() == '') { $(this).val('Full Name'); } });
		$('FORM#subscribe-form input[name=email]').tipsy({  gravity: 'e', trigger: 'manual', fade: true });
		$('FORM#subscribe-form input[name=name]').tipsy({  gravity: 'e', trigger: 'manual', fade: true });
		$('FORM#subscribe-form').submit(validateSubscribeForm);
	}
	
	if ($('FORM#search-form INPUT[name=search_text]').length) {
		$('FORM#search-form INPUT[name=search_text]').focus(function() { if ($(this).val() == 'Search') { $(this).val(''); } }).blur(function() { if ($(this).val() == '') { $(this).val('Search'); } });
	}
	
	
});




/**
 * Shonky validate the subscribe form, needs to be cleaned up.
 * 
 * @todo , integrate floating validation errors into jquery.validate
 * @return bool
 */
function validateSubscribeForm() {

	var email = $('FORM#subscribe-form input[name=email]');
	var name = $('FORM#subscribe-form input[name=name]');
	var focus = null;

	if (name.val() == 'Full Name') {
		name.attr('title', 'Name is a required field');
		name.tipsy('show');
		setTimeout("$('FORM#subscribe-form input[name=name]').tipsy('hide');", 2000);
		focus = (focus != null) ? focus : name;
	}
	
	if (email.val() == 'Email Address') {
		email.attr('title', 'Email Address is a required field');
		$('FORM#subscribe-form input[name=email]').tipsy('show');
		setTimeout("$('FORM#subscribe-form input[name=email]').tipsy('hide');", 2100);
		focus = (focus != null) ? focus : email;
	} else if (email.val().indexOf('@') === -1 || email.val().indexOf('.') === -1) {
		email.attr('title', 'Email Address must be valid.');
		$('FORM#subscribe-form input[name=email]').tipsy('show');
		setTimeout("$('FORM#subscribe-form input[name=email]').tipsy('hide');", 2100);
		focus = (focus != null) ? focus : email;
	}

	if (focus !== null) {
		focus.select();
		focus.focus();
		return false;
	}

	return true;
}




/**
 * This is a jquery plugin that I use to preload a bunch of images, its easy to use, just call 
 * 
 * $.preLoadImages("image1.jpg", "image2.jpg")
 * 
 */
(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);	
		}
	};
})(jQuery);
