/*

	[ site.js ]

	1. Initial Construct
		1.0. Font Replacement
		1.1. IE6 Alpha Transparency
		1.2. Form Validation Statement
		1.3. Custom Scrollbars
		1.4. Carousel
		1.5. Image Cropping
	2. Form Validation
		2.0. Comments
		2.1. Newsletter
		2.2. Team Signup
		2.3. Sponsorship
	3. Carousel
	4. Functions
		4.0. Google Analytics
		4.1. Spamless Email
		4.2. External Links
		4.3. Multiply String

*/

var Site = {

/* ###############################################
   1. Initial Construct
   ############################################### */

	start: function(){

		/* If Element HR is found, wrap a DIV.hr for presentation in all browsers */
	 	$('hr').each(function(){
	 		$$ = $(this);
	 		$$.wrap('<div class="hr'+($$.attr('class').length ? ' '+$$.attr('class') : '') +'"></div>')
	 	});

		$('#candidates_list form select').bind('change', function(e) {
			$('#candidates_list form').submit();
		});

		//showPage('about_fr.php', '', 2000, 300);

   /* 1.0. Font Replacement ###################### */

		Cufon.set('fontFamily', 'Futura Condensed');
		Cufon('#header form label')('form button')
		('#header form p.signup')('#header form p.error')('a.button')('p#population')('input.button')('#header p.loggedin')('#winner h1')
		('#header ul#navigation li a', { hover: true });

		Cufon.set('fontFamily', 'Futura ExtraBold');
		Cufon('h1:not(#rules h1)', { hover: true })('h2')
		('.post-head h2', { textShadow: '#B9A03B 1px 2px' })
		('.comments-head h2', { textShadow: '#B9A03B 1px 2px' })
		('.odd .post-head h2', { textShadow: '#D24383 1px 2px' })
		('#utilities #hoosts')('#utilities strong.hoosts');

   /* 1.1. IE6 Alpha Transparency ################ */

		/* For IE6 or older, PNG transparency support */
		$('.stamp, .candidate .overlay, .candidate .overlay img').ifixpng();


   /* 1.2. Form Validation Statement ############# */

		if ( $('form').length ) Site.formValidation();


   /* 1.3. Custom Scrollbars ##################### */

		$('.scroll-pane').jScrollPane({ showArrows:true, scrollbarWidth: 13, scrollbarMargin: 20 });


   /* 1.4. Carousel ############################## */

		if ( $('#candidates_box').length ) Site.buildCarousel();


   /* 1.5. Image Cropping ######################## */

		$('#cropbox').Jcrop({
			onChange:	showCoords,
			onSelect:	showCoords,
			bgColor:	'black',
			bgOpacity:	0.4,
			setSelect:	[ 0, 0, 190, 190 ],
			aspectRatio:	1,
			boxWidth:	422,
			boxHeight:	600

		});

		function showCoords(c) {
			$('#x').val(c.x);
			$('#y').val(c.y);
			$('#x2').val(c.x2);
			$('#y2').val(c.y2);
			$('#w').val(c.w);
			$('#h').val(c.h);
		};
	},

/* ###############################################
   2. Form Validation
   ############################################### */

	formValidation: function(){

		$.validator.setDefaults({
			//submitHandler: function() { alert("submitted!"); },
			onfocusout: false,
			errorPlacement: function(error, element) {
				if (element.is(':radio'))
					error.appendTo(element.parent().parent());
				else if ( element.is(':hidden') )
					element.after(error);
				else
					error.appendTo(element.parent());
			}
		});

		image_formats	= '*.jpg, *.jpeg, *.gif, *.png';
		video_formats	= '*.mov, *.avi, *.wmv, *.mkv, *.mpg, *.mpeg, *.mp4, *.m4v, *.3gp, *.flv, *.swf';

		if (lang == 'en') {
			error_id	= 'You are not connected.';
			error_required	= 'This field is required.';
			error_update = 'To become an Ambassador you have to upload a video or write a story';
			error_email	= 'Please enter a valid e-mail.';
			error_age	= 'You must be 18 years or older.';
			error_digits	= 'Please enter only digits.';
			error_min	= 'Please enter a value greater than or equal to 1.';
			error_minlength	= 'S\'il vous pla&icirc;t entrer au moins 6 caract&egrave;res.';
			error_photo	= 'Please submit a valid format of your photo ('+image_formats+')';
			error_video	= 'Please submit a valid format of your video ('+video_formats+')';
		} else {
			error_id	= 'Vous n\'&ecirc;tes pas connect&eacute;.';
			error_required	= 'Ce champ est obligatoire.';
			error_update = 'Pour devenir ambassadeur vous devez t&eacute;l&eacute;charger un vid&eacute;o OU &eacute;crire une anecdote';
			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.';
			error_photo	= 'Veuillez SVP entrer une photo d\'un format valide ('+image_formats+')';
			error_video	= 'Veuillez SVP entrer une vid&eacute;o d\'un format valide ('+video_formats+')';
		}

/* 2.0. Sign In ############################### */

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

		if ( $form.length ) {
			$form.validate({
				rules: {
					email: { required: true, email: true },
					password: 'required'
				},
				messages: {
					email: { required: error_required, email: error_email },
					comment: error_required
				},
				errorPlacement: function(error, element) {}
			});
		} /* form#signin */

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

		if ( $form.length ) {
			$form.validate({
				rules: {
					email: { required: true, email: true }
				},
				messages: {
					email: { required: error_required, email: error_email }
				},
				errorPlacement: function(error, element) {}
			});
		} /* form#lostpass */


		// Code to toggle between a video and a written anecdote
		var p_lost = $('p.lostpass');
		var p_login = $('p.remembered');
		var lostpass = $('form#lostpass');
		var signin = $('form#signin');
		p_lost.click(function() {
			signin.hide();
			lostpass.show();
		});
		p_login.click(function() {
			lostpass.hide();
			signin.show();
		});

/* 2.0. Comments ############################## */

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

		if ( $form.length ) {
			$form.validate({
				rules: { comment: 'required' },
				messages: { comment: error_required }
			});
		} /* form#comment */


/* 2.0. Give Hoosts ########################### */

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

		if ( $form.length ) {
			$form.validate({
				rules: { qty_hoosts: { required: true, digits: true, min: 1 } },
				messages: { qty_hoosts: { required: error_required, digits: error_digits, min: error_min } }
			});

		} /* form#give_hoosts */


/* 2.0. Share w/ Friend ####################### */

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

		if ( $form.length ) {
			$form.validate({
				rules: { email: { required: true, email: true } },
				messages: { email: { required: error_required, email: error_email } }
			});

		} /* form#share_friend */


/* 2.1. Newsletter ############################ */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					name: 'required',
					email: { required: true, email: true }
				},
				messages: {
					name: error_required,
					email: { required: error_required, email: error_email }
				}
			});

		} /* form#newsletter */


/* 2.2. Ambassador Application ################ */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					id: 'required',
					age: {
						required: true,
						digits: true,
						min: 18
					},
					city: 'required',
					traveler: 'required',
					last_visited_country: 'required',
					photo: {
						required: true,
						accept: 'png|jpe?g|gif'
					},
					copyright: 'required'
				},
				messages: {
					id: error_id,
					age: {
						required: error_required,
						digits: error_digits,
						min: error_age
					},
					city: error_required,
					traveler: error_required,
					last_visited_country: error_required,
					photo: {
						required: error_required,
						accept: error_photo
					},
					copyright: error_required
				}
			});

		} /* form#ambassador */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					photo: {
						required: true,
						accept: 'png|jpe?g|gif'
					}
				},
				messages: {
					photo: {
						required: error_required,
						accept: error_photo
					}
				}
			});

		} /* form#form_video */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					file: {
						required: true,
						accept: 'mov|avi|wmv|mpg|mpeg|mp4|m4v'
					}
				},
				messages: {
					file: {
						required: error_update,
						accept: error_video
					}
				}
			});

		} /* form#form_video */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					story: 'required'
				},
				messages: {
					story: error_required
				}
			});

		} /* form#form_video */

		// Code to toggle between a video and a written anecdote
		var anecdote_s = $('p#anecdote_story');
		var anecdote_v = $('p#anecdote_video');
		var story = $('div#form_story');
		var video = $('div#form_video');
		anecdote_s.click(function() {
			video.hide();
			story.show();
		});
		anecdote_v.click(function() {
			story.hide();
			video.show();
		});


/* 2.2. Citizen Application ################### */

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

		if ( $form.length ) {

			$form.validate({
				rules: {
					firstname: 'required',
					lastname: 'required',
					email: {
						required: true,
						email: true
					},
					password: {
						required: true,
						minlength: 6
					},
					hicmember: 'required',
					hicid: {
						required: 'input#y:checked',
						minlength: 6
					}
				},
				messages: {
					firstname: error_required,
					lastname: error_required,
					email: {
						required: error_required,
						email: error_email
					},
					password: {
						required: error_required,
						minlength: error_minlength
					},
					hicid: {
						required: error_required,
						minlength: error_minlength
					}
				}
			});

			// Code to hide HIC Member ID, disable for demo
			var hicmember = $('input[name="hicmember"]');
			var initial = hicmember.filter(':checked').val();

			$('div#hic-y').toggle(initial == 1);
			$('div#hic-n').toggle(initial == 0);

			hicmember.click(function() {
				$('div#hic-y').toggle($(this).val() == 1);
				$('div#hic-n').toggle($(this).val() == 0);
			});

		} /* form#citizen */

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

	},

/* ###############################################
   3. Carousel Call
   ############################################### */

	buildCarousel: function(){

		var once = true;
		var itemList;
		var ordered = '';

		function loadCarouselItems(carousel, reset)
		{
			$.get(
				'php/carousel.php',
				{
					sort: ordered,
					lang: lang,
					t: new Date().getTime() // Ensure reload in IE
				},
				function(json) {
					itemList = json;
					if (reset) carousel.reset();

					if (once) {
						once = false;
						$('#candidates_box').jcarousel({
							wrap: 'circular',
							initCallback: initCarousel,
							//itemLoadCallback: loadCarouselItems,
							itemVisibleInCallback: { onBeforeAnimation: itemVisibleInCarousel },
							itemVisibleOutCallback: { onAfterAnimation: itemVisibleOutCarousel }
						});
					}
				},
				'json'
			);
		};

		function initCarousel(carousel, state)
		{
			// Do nothing of state is 'reset'
			if (state == 'reset') return;
			$('form select', carousel.container).bind('change', function(e) {
				ordered = $('select#order', carousel.container).val();
				loadCarouselItems(carousel, true);
				return false;
			}).change();
		};

		function itemVisibleInCarousel(carousel, item, i, state, evt)
		{
			// The index() method calculates the index from a
			// given index who is out of the actual item range.
			var idx = carousel.index(i, itemList.length);
			carousel.add(i, getItemHTML(itemList[idx - 1]));
		};

		function itemVisibleOutCarousel(carousel, item, i, state, evt)
		{
			carousel.remove(i);
		};

		function getItemHTML(item)
		{
			var line = 18;

			var type = item.type.substring(0, 18);
			if (type.length < line) type += ' '+'&lt;'.x(line - type.length);

			var city = item.city.substring(0, 18);
			if (city.length < line) city += ' '+'&lt;'.x(line - city.length);

			var last_visit = item.last_visit.substring(0, 18);
			if (last_visit.length < line) last_visit += ' '+'&lt;'.x(line - last_visit.length);

			if (lang == 'en') last_visit = '<small>Last country visited</small><br />'+last_visit; else last_visit = '<small>Dernier pays visit&eacute;</small><br />'+last_visit;

			if (item.firstname.length < line) item.firstname += ' '+'&lt;'.x(line - item.firstname.length);
			if (item.lastname.length < line)  item.lastname  += ' '+'&lt;'.x(line - item.lastname.length);
			return '<div class="avatar"><a href="'+item.url+'"><img src="'+item.avatar+'" height="84" width="84" alt="" /></a></div>\n<div class="meta"><p class="name">'+item.firstname+'<br />'+item.lastname+'</p>\n<p>'+last_visit+'</p></div>\n<a class="overlay" href="'+item.url+'">&nbsp;</a>\n';
		};

		loadCarouselItems();

	}

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

};

/* ###############################################
   4. Functions
   ############################################### */

   /* 4.0. 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-1837138-37'); // Insert GA Code
				pageTracker._initData();
				pageTracker._trackPageview();
		});
	}

   /* 4.1. Spamless Email ######################## */


	function noSpam(user) {
		var mail = 'mailto:' + user + '@hoosteland.com';
		window.location.href = mail;
	}

   /* 4.2. 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';
		}
	}

   /* 4.3. Multiply String ####################### */

	String.prototype.x = function(x){
		if (arguments.length == 0) return this;
		if (x <= 0) return this;
		var out = '';
		for (i = 0; i < x; i++) {
			out += this;
		}
		return out;
	}

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

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

	Site.start();
});

/* Code is poetry */