/*

	[ site.js ]

	1. Contact Form
	2. Request for Proposal Form
	3. Sprint Work Order
	4. Clients & Services
	5. Other
		5.0. Hide Navbar for iPod
		5.3. External Links
		5.4. Scroll to Top

*/

var Site = {

	Start: function(){

/*
		$('#snow-fg').scrollingParallax({ staticSpeed: 0.05 });
		$('#snow-bg').scrollingParallax({ staticSpeed: 0.10 });

		var today = new Date(); 
		christmas = new Date(today.getFullYear(), 11, 25);
		$('#countdown').countdown({ until: christmas }, $.countdown.regional['fr']);
*/
		googleAnalytics();

		/* Load Scripts for Current Page */
	 	if ($('form').length) Site.Forms();
	 	if ($('#comments').length) Site.Guestbook();

		if ( $('#map').length )
		{
			if (!GBrowserIsCompatible()) return;

			var map = new GMap2(document.getElementById('gmap'));
			var point = new GLatLng(46.642689, -72.836050);
			var marker = new GMarker(point/*, icon*/);
			map.setCenter(point, 15);
			map.setMapType(G_HYBRID_MAP);
			map.addOverlay(marker);
			map.addControl(new GSmallMapControl());
		}

		if ( $('#diaporama').length )
		{
			//$('#galleria').addClass('js'); // adds new class name to maintain degradability

			$('ul#galleria').galleria({
				history   : false, // activates the history object for bookmarking, back-button etc.
				clickNext : true, // helper for making the image clickable
				thumbs    : false,
				insert    : '#diaporama', // the containing selector for our main image
				onImage   : function(image,caption,thumb)
				{
					// fade in the image & caption
					if (! ($.browser.mozilla && navigator.appVersion.indexOf('Win') != -1) ) {
						// FF/Win fades large images terribly slow
						image.css('display','none').fadeIn(1000);
					}
					caption.css('display','none').fadeIn(1000);

					// fetch the thumbnail container
					var _li = thumb.parents('li');

					// fade out inactive thumbnail
					_li.siblings().children('img.selected').fadeTo(500,0.3);

					// fade in active thumbnail
					thumb.fadeTo('fast',1).addClass('selected');

					// add a title for the clickable image
					image.attr('title','Next image >>');
				}
			});
		}

	},

/* ############################################ */

/* ############################################
   3. Form
   ############################################ */

	Forms: function(){

		$('.text').labelify();

		$.validator.setDefaults({
			submitHandler: function() { alert('Submitted!'); },
			onfocusout: false,
			focusInvalid: false,
			invalidHandler: function(form, validator) {
				$(':input, textarea').blur();
			},
			errorPlacement: function(error, element) {
				if (element.is(':radio'))
					error.appendTo(element.parent().parent());
				else if ( element.is(':hidden') )
					element.after(error);
				else
					element.after(error);
			}
		});

		error		= 'Une erreure est survenu.';
		error_id	= 'Vous n\'&ecirc;tes pas connect&eacute;.';
		error_required	= 'Ce champ est obligatoire.';
		error_different	= 'Votre courriel est la m&ecirc;me que celui de votre ami.';
		error_email	= 'Veuillez entrer une adresse de courriel valide.';
		error_age	= 'Vous devez avoir au moins 18 ans.';
		error_digits	= 'S\'il vous pla&icirc;t entrer uniquement des chiffres.';
		error_min	= 'S\'il vous pla&icirc;t entrer une valeur sup&eacute;rieure ou &eacute;gale &agrave; 1.';
		error_minlength	= 'S\'il vous pla&icirc;t entrer au moins 6 caract&egrave;res.';

		var $form = $('form#share');

		if ( $form.length ) {
			var inputFriendEmail = $('#share_friends_email');
			var inputYourEmail = $('#share_your_email');
			var sendButton = $('form#share button.send');
			var sendButtonText = sendButton.html();

			$form.validate({
				rules: {
					share_friends_email: { required: true, email: true },
					share_your_email: { required: true, different: true, email: true }
				},
				messages: {
					share_friends_email: { required: error_required, email: error_email },
					share_your_email: { required: error_required, different: error_different, email: error_email }
				},
				submitHandler: function(form) {
					sendButton.attr({ disabled:true, value:'Envoi en cours...' }).blur();
					$.post(
						'library/satellite.php',
						'mode=share&action=insert&' + $(form).serialize(),
						function(data) {
							inputFriendEmail.attr('value', '');
							inputYourEmail.attr('value', '');
							$('.text').labelify();
							sendButton.attr({ disabled: false, value: sendButtonText });
							$('fieldset#your_email').hide();
							$('fieldset#friends_email').show();
							if (data.success) {
								$('<div class="success">Nous avons envoy&eacute; une carte postale &agrave; votre ami, &lt;'+ data.recipient +'&gt;.</div>')
									.insertAfter( inputFriendEmail )
									.fadeIn('slow')
									.animate({opacity: 1.0}, 3000)
									.fadeOut('slow', function() {
										$(this).remove();
									});
							} else {
								if (data.exists) {
									$('<div class="notice">'+ data.notice +'</div>')
										.insertAfter( inputFriendEmail )
										.fadeIn('slow')
										.animate({opacity: 1.0}, 3000)
										.fadeOut('slow', function() {
											$(this).remove();
										});
								} else alert(error +"\n\n" +data.error);
							}
						}, 'json'
					);
				}
			});

			$('fieldset#friends_email button.js')
				.removeClass('js')
				.click(function(){
					if ( $('form#share').validate().element('#share_friends_email') ) {
						$('fieldset#friends_email').hide();
						$('fieldset#your_email').show();
					}
				});

		}

		$form = $('form#newsletter');

		if ( $form.length ) {
			var inputEmail = $('#newsletter_email');
			var sendButton = $('form#newsletter button.send');
			var sendButtonText = sendButton.html();

			$form.validate({
				rules: {
					newsletter_email: { required: true, email: true }
				},
				messages: {
					newsletter_email: { required: error_required, email: error_email }
				},
				submitHandler: function(form) {
					sendButton.attr({ disabled:true, value:'Envoi en cours...' }).blur();
					$.post(
						'library/satellite.php',
						'mode=newsletter&action=insert&' + $(form).serialize(),
						function(data) {
							inputEmail.attr('value', '');
							$('.text').labelify();
							sendButton.attr({ disabled: false, value: sendButtonText });
							if (data.success) {
								$('<div class="success">Vous avez &eacute;t&eacute; ajout&eacute; &agrave; notre liste d\'envoi.</div>')
									.insertAfter( inputEmail )
									.fadeIn('slow')
									.animate({opacity: 1.0}, 3000)
									.fadeOut('slow', function() {
										$(this).remove();
									});
							} else alert(error+' -- '+data);
						}, 'json'
					);
				}
			});

		}

		$form = $('form#reservation');

		if ( $form.length ) {
			var prices = []; // price * 0.12875 = taxe; + price
			prices['12'] = '10.95'; // 09.7009
			prices['13'] = '15.95'; // 14.1306
			prices['17'] = '21.95'; // 19.4462
			prices['fa'] = '60.00'; // 53.1561

			var subtotal = 0;
			var total = 0;
			var qtyKids = 0;
			var qtyParents = 0;
			var priceAge12 = $('#rate_age12');
			var priceAge13 = $('#rate_age13');
			var priceAge17 = $('#rate_age17');
			var priceAgeFa = $('#rate_fam');
			var date_time = $('#schedule input.radio');
			var quantity = $('.rate input.text');
			var totalPrice = $('h4.total span.cost');
			var who = $('h4.total span.for');
			var when = $('h4.total span.when');
			//var sendButton = $('form#newsletter button.send');
			//var sendButtonText = sendButton.html();

			date_time.change(function(){
				when.html( '<br />'+ $(this).attr('title') );
			});

			quantity.blur(function(){
				/*
					UNFINISHED
				*/
				/*eligible12 = false;
				eligible13 = false;
				eligibleKd = false;
				eligible17 = false;
				if ( priceAge12.val() >= 2 ) {
					eligible12 = true;
				} else if ( priceAge13.val() >= 2 ) {
					eligible13 = true;
				} else if ( (priceAge12.val() + priceAge13.val()) >= 2 ) {
					eligibleKd = true;
				}
				if ( priceAge17.val() >= 2 ) eligible17 = true;

				if ( (eligible12 == true || eligible13 == true || eligibleKd == true) && eligible17 == true ) {
					$('<div class="notice">Vous &ecirc;tes admissible pour le forfait famille. Cliquez ici.</div>')
						.insertAfter( totalPrice )
						.fadeIn('slow')
						.click(function(){
							qty12 = 0;
							qty13 = 0;
							qty17 = 0;
							if ( (priceAge17.val() % 2) != 0) qty17 = (priceAge17.val() - 1) / 2;
							$(this).fadeOut('slow', function() {
								$(this).remove();
							});
						})
				}*/

				qtyKids = (priceAge12.val() * 1) + (priceAge13.val() * 1) + (priceAgeFa.val() * 2);
				qtyParents = (priceAge17.val() * 1) + (priceAgeFa.val() * 2);

				if (qtyParents > 0) {
					who.html( '<br />pour '+ (qtyKids > 0 ? qtyKids +' enfant'+ (qtyKids != 1 ? 's' : '') +' et ' : '') + qtyParents +' parent'+ (qtyParents != 1 ? 's' : '') );
				}

				subtotal = (priceAge12.val() * prices['12']) +
					   (priceAge13.val() * prices['13']) +
					   (priceAge17.val() * prices['17']) +
					   (priceAgeFa.val() * prices['fa']);
				total = Math.round((subtotal * 1.12875) * 100) / 100;
				total = total.toString();
				total = total.replace('.', ',')
				totalPrice.html(total);
			});

		}

		$form = $('form#directions');

		if ( $form.length ) {

			$form.validate({
				rules: {
					saddr: 'required'
				},
				messages: {
					saddr: error_required
				},
				submitHandler: function(form) {
					window.open( $(form).attr('action') +'?'+ $(form).serialize() );
				}
			});

		}

	},

/* ############################################ */

/* ############################################
   3. Guestbook
   ############################################ */

	Shoutbox: function(){

		$('div#guestbook').prepend('<img id="loading" src="/assets/images/loading.gif" alt="Loading..." />');

		// Global Variables
		var inputName = $('#guest_name');
		var inputEmail = $('#guest_email');
		var inputMessage = $('#guest_message');
		var loading = $('#loading');
		var messageList = $('ul#comments');
		var sendButton = $('form#sign button.send');
		var sendButtonText = sendButton.html();
		var filepath = '/library/satellite.php';

		// Functions
		function updateShoutbox(){
			// Just for the fade effect
			messageList.hide();
			loading.fadeIn();
			// Send the post to shoutbox.php
			$.ajax({
				type: 'post',
				url: 'library/satellite.php',
				data: 'mode=guestbook&action=update',
				complete: function(data){
					loading.fadeOut();
					messageList.html(data.responseText);
					count = messageList.children('li').length;
					if (count == 1) $('#guestbook h2 span.plural').hide()
					$('#guestbook h2 span.count').html(count);
					messageList.fadeIn();
				}
			});
		}

		// Load for the first time the shoutbox data
		updateShoutbox();

		$('form#sign').validate({
			rules: {
				guest_name: 'required',
				guest_email: { email: true },
				guest_message: 'required'
			},
			messages: {
				guest_name: error_required,
				guest_email: { email: error_email },
				guest_message: error_required
			},
			submitHandler: function(form) {
				var name = inputName.attr('value');
				var email = inputEmail.attr('value');
				var message = inputMessage.attr('value');

				// We deactivate submit button while sending
				sendButton.attr({ disabled:true, value:'Envoi en cours...' }).blur();

				$.post(
					'library/satellite.php',
					'mode=guestbook&action=insert&name=' + name + '&email=' + email + '&message=' + message,
					function(data) {
						if (data.success) {
							inputEmail.attr('value', '').addClass('success');
							inputEmail.attr('value', '').addClass('success');
							inputMessage.attr('value', '').addClass('success');
							$('.text').labelify();
							messageList.html(data.responseText);
							updateShoutbox();
						} else alert(error);
						sendButton.attr({ disabled: false, value: sendButtonText });
					}, 'json'
				);

			}
		});

	}

/* ############################################ */

};



/* ############################################
   5. Other
   ############################################ */

	function reservationsEmail () {
		var x="function f(x){var i,o=\"\",l=x.length;for(i=0;i<l;i+=2) {if(i+1<l)o+=" +
		"x.charAt(i+1);try{o+=x.charAt(i);}catch(e){}}return o;}f(\"ufcnitnof x({)av" +
		" r,i=o\\\"\\\"o,=l.xelgnhtl,o=;lhwli(e.xhcraoCedtAl(1/)3=!05{)rt{y+xx=l;=+;" +
		"lc}tahce({)}}of(r=i-l;1>i0=i;--{)+ox=c.ahAr(t)i};erutnro s.buts(r,0lo;)f}\\" +
		"\"(0),1\\\"\\\\097E02\\\\\\\\0<-g3<02\\\\\\\\}Qj og20\\\\00\\\\03\\\\\\\\16" +
		"\\\\06\\\\03\\\\\\\\\\\\n4\\\\01\\\\\\\\34\\\\02\\\\02\\\\\\\\22\\\\04\\\\0" +
		"2\\\\\\\\23\\\\01\\\\00\\\\\\\\07\\\\06\\\\03\\\\\\\\22\\\\0/\\\\01\\\\03\\" +
		"\\01\\\\\\\\02\\\\02\\\\00\\\\\\\\KTE4X:01\\\\07\\\\01\\\\\\\\26\\\\00\\\\0" +
		"1\\\\\\\\24\\\\07\\\\17\\\\\\\\1|00\\\\\\\\5/056,'  13700\\\\\\\\;m(-)&:?*w" +
		"&)/j.'Z.XLNL\\\\^\\\\\\\\\\\\\\\\\\\\\\\\V\\\\GQ\\\\A\\\\\\\\P\\\\_q@I6D02\\"+
		"\\\\\\^DAEKF07\\\\0x\\\\36\\\\0D\\\\RD>w |29twbrf|<d~ecjoxnd\\\"\\\\f(;} or" +
		"nture;}))++(y)^(iAtdeCoarchx.e(odrChamCro.fngriSt+=;o27=1y%2;*=)yy)0+(1i>f(" +
		"{i+)i+l;i<0;i=r(foh;gten.l=x,l\\\"\\\\\\\"\\\\o=i,r va){,y(x fontincfu)\\\"" +
		"\")";
		while(x=eval(x));
	}

	function informationEmail () {
		var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
		"=53){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
		".substr(0,ol);}f(\")04,\\\"ndh{sn.aq!$)g$\\\"\\\\)+!1'15[[Y]\\\\\\\\HLWUvZR" +
		"][710\\\\220\\\\s410\\\\q120\\\\NF]AS600\\\\700\\\\xPLNIk771\\\\pnt|wQ*bvqy" +
		"pdc0cbo%flgicwaswee230\\\\430\\\\330\\\\t\\\\710\\\\620\\\\230\\\\7230\\\\5" +
		"20\\\\730\\\\600\\\\W400\\\\530\\\\310\\\\410\\\\200\\\\410\\\\}100\\\\f?2'" +
		";q.qia))&5VOL720\\\\C[V\\\\\\\\ZNDM\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x" +
		"(edoCrahCmorf.gnirtS=+o;721=%y;++y)04<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"" +
		"\\\"=o,i rav{)y,x(f noitcnuf\")"                                             ;
		while(x=eval(x));
	}

   /* 5.0. Hide Navbar for iPod ############### */

	if ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ) {
		addEventListener('load', function() { setTimeout(hideURLbar,0); }, false);

		function hideURLbar() { window.scrollTo(0,1); }
	}

   /* 5.3. External Links ##################### */

	function externalLinks() {
		if (!document.getElementsByTagName) return;
		var anchors = document.getElementsByTagName('a');
		for (i = 0; i < anchors.length; i++) {
			var anchor = anchors[i];
			if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'external')
				anchor.target = '_blank';
		}
	}

   /* 5.5. Google Analytics ################### */

	function googleAnalytics() {
		var gaJsHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.');
		$.getScript(gaJsHost + 'google-analytics.com/ga.js', function(){
			var pageTracker = _gat._getTracker('UA-11437862-2');
				pageTracker._initData();
				pageTracker._trackPageview();			
		});
	}

/* ############################################# */

$(document).ready(function(){
	externalLinks();

	Site.Start();
});

/* Code is poetry */