/*

	[ site.js ]

*/

var Site = {

	start: function(){

		if (!Site.fontAvailable('AvantGarde Bk BT'))
		{
			Cufon.replace('h1',			{ fontSize: '36px', fontFamily: 'AvantGarde Bk BT' });
			Cufon.replace('.block a',		{ fontSize: '28px', fontFamily: 'AvantGarde Bk BT' });
			Cufon.replace('ul#navigation li a',	{ fontSize: '16px', fontFamily: 'AvantGarde Md BT' });
			Cufon.replace('h2',			{ fontFamily: 'AvantGarde Md BT' });
			Cufon.replace('h3',			{ fontFamily: 'AvantGarde Md BT' });
		}


		/* Text Variables */
		txtLocalisation2 = 'Localisation';
		txtLocalisation = '[+] Localisation';
		txtDetails = '[+] D&eacute;tails';
		txtReduire = '[&minus;] R&eacute;duire';


		if ( $('#slideshow').length ) Site.home();
		if ( $('.offer').length ) Site.offers();
		if ( $('.job-block').length ) Site.postulate();
		if ( $('#googleMap').length ) Site.gMap();
		if ( $('form').length ) Site.formValidation();


		/* Detect if IE6 or older to launch PNG transparency support */
		var oldBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");

		if (!oldBrowser) {
			/* If Element HR is found, replace it with a DIV.hr for presentation in all browsers */
			$('hr:not(.spacer, .more)').replaceWith('<div class="hr"></div>');
		}

		if (oldBrowser) {
			$('.block a, .fade, .overlay, div.item').ifixpng();
		}

		/* Open external links in new windows */
		$('a[rel="external"]').attr({
			target: "_blank",
			title: "Lien s'ouvrant dans une nouvelle fenêtre"
		});

	},

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

	home: function(){

		$.getScript('assets/scripts/jquery.slideviewer.js', function(){
			$('#slideshow').slideView();
			setTimeout("nextImg()", 5000);
		});

	},

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

	postulate: function(){

		/* Post selection form */
		$('.job-block').hide();

		/* If browser's JavaScript is deactivated or not supported, do not display dynamic elements */
		$('.job-block .js').removeClass('js').addClass('accordion');

		/* Job offer hiding/revealing mechanism */
		$('.job-block .entry').hide();

		$('.job-block .accordion').toggle(
			function(){
				var e = $(this).parent().parent().children('.entry');
				$(this).html(txtReduire);
				$(e).slideDown();
			},
			function(){
				var e = $(this).parent().parent().children('.entry');
				$(this).html(txtDetails);
				$(e).slideUp('fast');
			}
		);

		$('select#job').change(function(){
			$('select option:selected').each(function(){
				var v = $(this).val();

				if ( $('.job-block .entry:visible').length ) $('.job-block .entry').slideUp('fast');

				if (v == '-')
					$('.job-block').slideUp();
				else {
					if ( $('div.job-block:visible').length ) {
						$('div.job-block:visible').slideUp(function(){
							$('div.job-block[id="job-'+v+'"]').slideDown();
						});
					} else $('div.job-block[id="job-'+v+'"]').slideDown();
				}
			});
		}).change();

	},

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

	offers: function(){

		/* If browser's JavaScript is deactivated or not supported, do not display dynamic elements */
		$('.offer .js').removeClass('js').addClass('accordion');

		/* Job offer hiding/revealing mechanism */
		$('.offer .entry').hide();

		$('.offer .accordion').toggle(
			function(){
				var e = $(this).parent().parent().children('.entry');
				$(this).html(txtReduire);
				$(e).slideDown();
			},
			function(){
				var e = $(this).parent().parent().children('.entry');
				$(this).html(txtDetails);
				$(e).slideUp('fast');
			}
		);

		var offset = $('.highlight').offset();
		$('.highlight .accordion').click().animate({ scrollTop: offset.top }, 500);
		$('html,body').animate({ scrollTop: offset.top }, 500);

	},

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

	gMap: function(){

		gMap = '#googleMap';
		mManager = 0;
		prevMarker = new Array();

		$(gMap).jmap('init');

		function jmapIt(location,addr) {
			z = 0;

			if (mManager) {
				while(prevMarker.length > 0) {
					$(gMap).jmap('RemoveMarker', prevMarker[z]);
					prevMarker.shift()
				}
			}

			$(gMap).jmap('SearchAddress',
			{
				'query': addr,
				'returnType': 'getLocations'
			}, function(result, options) {

				var valid = Mapifies.SearchCode(result.Status.code);

				if (valid.success) {
					$.each(result.Placemark, function(i, point) {
						$(gMap).jmap('AddMarker', {
							'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
							'pointHTML': '<strong>'+ location +'</strong><p>'+ point.address +'</p>'
						}, function(marker, options) {
							$(gMap).jmap('MoveTo', {
								'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]],
								'mapZoom': 10 // 15
							});

							prevMarker[z] = marker;
							z++;

							mManager = 1;
						});
					});
				} else alert(valid.message);
			});
		}

		/* If browser's JavaScript is deactivated or not supported, anchor link points to GoogleMaps */
		$('.options').addClass('accordion');

		/* Map hiding/revealing mechanism */
		$('.local .accordion').click(function(){
			var d = $(this).parent().children('.title').attr('data');
			var t = $(this).parent().children('.title').text();

			jmapIt(t,d);

			return false;
		});

	},

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

/* fontAvailable jQuery Plugin, v1.0
 *
 * Created by Howard Rauscher
 * Modified by Chauncey McAskill
 * Licensed under the MIT License
 */
	fontAvailable: function(fontName){

		var element, width;

		// prepare element, and append to DOM
		element = $(document.createElement('span'))
			.css('visibility', 'hidden')
			.html('abcdefghijklmnopqrstuvwxyz')
			.appendTo(document.body);

		// get the width of element after applying a fake font
		width = element
			.css('font-family', '__FAKEFONT__')
			.width();

		element.css('font-family', fontName);

		return (width !== element.width());

	},

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

	formValidation: function(){

		$.getScript('assets/scripts/jquery.validate.js', function(){

			$.validator.setDefaults({
				//submitHandler: function() { alert('Submitted!'); },
				onfocusout: false
			});

			$('form#contact').validate({
				rules: {
					subject: 'required',
					message: 'required',
					email: {
						required: true,
						email: true
					}
				},
				messages: {
					subject: 'Ce champ est obligatoire.',
					message: 'Ce champ est obligatoire.',
					email: {
						required: 'Ce champ est obligatoire.',
						email: "S'il vous pla&icirc;t entrer un courriel valide."
					}
				}
			});

			$('form#postulate').validate({
				rules: {
					first_name: 'required',
					last_name: 'required',
					telephone: {
						required: true,
						phone: true
					},
					email: {
						required: true,
						email: true
					},
					cv: {
						required: true,
						accept: 'doc|docx|txt|rtf|pdf'
					}
				},
				messages: {
					first_name: 'Ce champ est obligatoire.',
					last_name: 'Ce champ est obligatoire.',
					telephone: {
						required: 'Ce champ est obligatoire.',
						phone: "S'il vous pla&icirc;t sp&eacute;cifier un num&eacute;ro de t&eacute;l&eacute;phone valide (ex. 1 (789)-555-1234)."
					},
					email: {
						required: 'Ce champ est obligatoire.',
						email: "S'il vous pla&icirc;t entrer un courriel valide."
					},
					required: 'Ce champ est obligatoire.',
					cv: "S'il vous pla&icirc;t s&eacute;lectionnez un document (doc, docx, txt, rtf, pdf)."
				}
			});


		});

	}

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

}

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

   /* 1.0. Slideviewer Automation ############# */

	var img = 0;

	function nextImg()
	{
		var slides = $('#slideshow ul').find('li').length;
		$('div#stripTransmitter0 a:eq('+img+')').click();
		img = (img > slides) ? 0 : img + 1;
		setTimeout("nextImg()", 5000);
	}

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

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

(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'assets/images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

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

	Site.start();
});

/* Code is poetry */
