/**
* main script file
* @author		mac@zestedegenie.com
* @creationDate 2011-01-04
* @editDate		2011-01-07
*/


/**
 * open links with rel='external' in new tabs
 * @author http://www.456bereastreet.com/archive/200610/opening_new_windows_with_javascript_version_12/
 */
var JSTarget={init:function(att,val,warning){if(document.getElementById&&document.createElement&&document.appendChild){var strAtt=((typeof att==='undefined')||(att===null))?'class':att;var strVal=((typeof val==='undefined')||(val===null))?'non-html':val;var strWarning=((typeof warning==='undefined')||(warning===null))?' (opens in a new window)':warning;var oWarning;var arrLinks=document.getElementsByTagName('a');var oLink;var oRegExp=new RegExp("(^|\\s)"+strVal+"(\\s|$)");for(var i=0;i<arrLinks.length;i++){oLink=arrLinks[i];if((strAtt=='class')&&(oRegExp.test(oLink.className))||(oRegExp.test(oLink.getAttribute(strAtt)))){oWarning=document.createElement("em");oWarning.appendChild(document.createTextNode(strWarning));oLink.appendChild(oWarning);oLink.onclick=JSTarget.openWin;}oWarning=null;}}},openWin:function(e){var event=(!e)?window.event:e;if(event.shiftKey||event.altKey||event.ctrlKey||event.metaKey){return true;}else{var oWin=window.open(this.getAttribute('href'),'_blank');if(oWin){if(oWin.focus){oWin.focus();}return false;}oWin=null;return true;}},addEvent:function(obj,type,fn){if(obj.addEventListener){obj.addEventListener(type,fn,false);}else if(obj.attachEvent){obj["e"+type+fn]=fn;obj[type+fn]=function(){obj["e"+type+fn](window.event);};obj.attachEvent("on"+type,obj[type+fn]);}}};JSTarget.addEvent(window,'load',function(){JSTarget.init("rel","external","");});

/**************************************

 **************************************/

/* ########################################################### */
/* !vars */

var isIe = false;
var isIe6 = false;

/** *******************************************************
 * contain text vars
 */
var vars = {
	init: function(){
		if($('body.en')[0]){ // if site EN
			vars.lang = 'en';
			// colobox
			vars.current = "image {current} of {total}";
			vars.currentLyrics = "Song {current} of {total}";
			vars.previous = "previous";
			vars.next = "next";
			vars.close = "close";
		}else{
			vars.lang = 'fr';
			// colobox
			vars.current = "image {current} de {total}";
			vars.currentLyrics = "Chanson {current} de {total}";
			vars.previous = "suivant";
			vars.next = "précédent";
			vars.close = "fermer";
		}
	}
};

/**
 * Check if browser is IE
 */
if ($.browser.msie) {
	isIe = true;
}
/**
 * Check if browser is IE6 or less
 */
if (isIe && $.browser.version < 7) {
	isIe6 = true;
}

/**
 * Put elements at the same height
 */
var equalHeight = {
	/**
	 * init
	 * @param	jQuery $group - jQuery object of the elements to equalize
	 */
	init: function(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = jQuery(this).height();
			if (thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}
};


/**
 * Make whole blocks cliquable
 */
var blocs = {
	/**
	 * init blocs
	 * @param	jQuery $target - jQuery object of link to follow
	 * @param	string $parent - selector of the parent where to add the click
	 */
	init: function($target, $parent) {
		$target.each(function(){
			var _this = $(this); // the link
			$(this).closest($parent).click(function(){ // add pointer cursor
				window.location = _this.attr('href'); // go to link url
			});
		});
	}
};


/**
 * Activate colorbox
 */
var zoom = {
	/**
	 * init colorbox on .img-zoom elements
	 */
	init: function() {
		if($.colorbox){
			$('.img-zoom').each(function(){
				$(this).colorbox({
					maxWidth: '100%',
					maxHeight: '100%'
				});
			});
			$('#ls-catalogue .img-zoom').each(function(){
				$(this).colorbox({
					width: '800',
					initialWidth: '400',
					maxHeight: '100%'
				});
			});
			$('.ls-gal').each(function(){
				if(typeof($(this).attr('id')) !== 'undefined'){
					var e = $('a', this).attr('rel', $(this).attr('id'));
				}else{
					var e = $('a', this).attr('rel', 'gal');
				}
				e.colorbox({
					maxWidth: '100%',
					maxHeight: '100%',
					current: vars.current,
					previous: vars.previous,
					next: vars.next,
					close: vars.close
				});
			});
		}
	}
};


/**
 * Fix floated image bug in IE
 */
var imgs = {
	/**
	 * adjust the size of .img depending on the width of the img inside
	 */
	init: function() {
		if(isIe === true && $.browser.version < 8) { // if IE 7 or minus
			$('.img').each(function(){
				var _width = parseInt($(this).find('img').width(),10); // width of the img
				if(_width > 0){
					$(this).width(_width);
				}
			});
		}
	}
};


/**
 * Fix the content height
 */
var content = {
	/**
	 * adjust the height of content if col is higher
	 */
	init: function() {
		if($('#col')[0] && $('#content')[0]){

			var col = $('#col').height(); // #col height
			var contentCss = parseInt($('#content').css('margin-bottom'),10) + parseInt($('#content').css('padding-bottom'),10) + parseInt($('#content').css('padding-top'),10); // #content margin+padding
			var content = parseInt($('#content').height(),10) - contentCss; // #content height
			
			if(col>content){ // if #col higher than #content
				$('#content').css('min-height', parseInt(col,10) - contentCss);
			}
		}
	}
};


/**
 * Control display of jobs in job form
 */
var jobs = {
	/**
	 * add actions on check form element
	 */
	init: function() {
		if($('#ls-jobs')[0]){
			$('#ls-jobs').hide().removeClass('none');
			$('#check-jobs').find('input:checkbox').each(function(){ // get all jobs checkbox
				$(this).click(jobs.click);
			});
		}
	},
	/**
	 * check the status of the clicked item and show or hide job details
	 */
	click: function(){
		var ind = $(this).closest('div').find('input:checkbox').index($(this)); // index of cliked item
		if($('#ls-jobs article:eq('+ind+')')[0]){ // check if job details for clicked checkbox exist
		
			if($('#ls-jobs:visible')[0]){ // if jobs already open
				if($(this).is(':checked')){ // if item is checked
				
					$('#ls-jobs article:eq('+ind+')').slideDown(); // show job
				
				}else{ // if item not checked out
					
					if($('#ls-jobs article:visible').length > 1){ // if more than 1 job showing
						$('#ls-jobs article:eq('+ind+')').slideUp(); // hide current job
					}else{
						$('#ls-jobs').slideUp(500, function(){ // hide all jobs
							$('#ls-jobs article').hide();
						});
					}
					
				}
			}else{ // if jobs not open
				$('#ls-jobs article').hide();
				$('#ls-jobs article:eq('+ind+')').show(); // show clicked article
				$('#ls-jobs').slideDown(500);
			}
		}
	}
};


/**
 * Control Google maps
 */
var map = {
	/**
	 * load google map
	 */
	init: function(){
		if(typeof(google) == 'object' && $('#gmap')[0]){
			var latlng = new google.maps.LatLng(45.82176048817253, -72.724560546875);
			var options = {
				zoom: 9,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.TERRAIN,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
				},
				navigationControlOptions: {
					style: google.maps.NavigationControlStyle.SMALL
				},
				scrollwheel: false
			};

			var map = new google.maps.Map(document.getElementById('gmap'), options);

			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(45.45805362689433, -73.41476440429688),
				map: map,
				title: 'St-Hubert',
				clickable: false//,
				//icon: '/img/marker.png'
			});

			var marker2 = new google.maps.Marker({
				position: new google.maps.LatLng(45.87590365871672, -72.4916285276413),
				map: map,
				title: 'Drummondville',
				clickable: false//,
				//icon: '/img/marker.png'
			});
			
			var marker3 = new google.maps.Marker({
				position: new google.maps.LatLng(46.05817137101456, -71.9645208120346),
				map: map,
				title: 'Victoriaville',
				clickable: false//,
				//icon: '/img/marker.png'
			});
		}
	}
};


/**
 * Control the homepage slider
 */
var slider = {
	/**
	 * load homepage slider
	 */
	init: function() {
		this.dist = $('#box-slides li').height(); // animation distance
		
		if($('#slide-nav li').length > 1){ // if more than 1 slide
			$('#slider').hover(slider.interClear, slider.interSet); // stop interval on hover, start on hover out
			slider.interSet();
			$('#slide-nav a').click(this.change);
		}else{
			$('#slide-nav').hide();
		}
		
		
	},
	/**
	 * set interval
	 */
	interSet: function(){
		slider.int = setInterval(slider.click, 5000);
	},
	/**
	 * clear interval
	 */
	interClear: function(){
		clearInterval(slider.int);
	},
	/**
	 * change the slide according to the pressed button
	 * @return false
	 */
	change: function(){

		if(!$(this).closest('li').hasClass('selected')){ // if link not already selected
			
			if($('#box-slides ul:animated')[0]){ // if already animated
				return false;
			}
						
			var _ind = $(this).text(); // link index
			var _this = $(this); // clicked link
			
			$('#box-slides ul').fadeTo(50, 0.5).animate({ // fade 50%
				marginTop: - slider.dist * (_ind - 1) // animate margin-top
			},500, function(){
				$('#box-slides ul').fadeTo(50, 1); // fade back to 100%
				$('#slide-nav .selected').removeClass('selected'); // remove all .selected
				_this.closest('li').addClass('selected'); // add .selected on clicked link
			});
		}
		
		return false;
	},
	/**
	 * fake click used by interval
	 * @return false
	 */
	click: function(){
		if($('#slide-nav li.selected').next()[0]){
			$('#slide-nav li.selected').next().find('a').trigger('click');
		}else{
			$('#slide-nav li:eq(0)').find('a').trigger('click');
		}
		return false;
	}
};


/**
 * Control the footer logo slider
 */
var logos = {
	/**
	 * load footer logo slider
	 */
	init: function() {
		this.dist = $('#logos-slide').width(); // animation distance

		$('#logos-next a').click(this.change);
	},
	/**
	 * animate the logo slider
	 * @return false
	 */
	change: function(){

		if($("#logos-slide li:first").is(':animated')){
			return false;
		}
		
		$("#logos-slide li:first").animate({
			marginLeft: - $("#logos-slide li:first").width()
		}, 500, function(){
			$("#logos-slide li:first").hide().css('margin-left', 0).appendTo($("#logos-slide ul")).show();
		});
		
		return false;
	}
};


/**
 * Control the print preview
 */
var prnt = {
	/**
	 * add action on print button
	 */
	init: function() {
		$('.bt-print, #bt-screen').click(this.setup);
		$('#bt-print').click(function(){ // add js print on print bt
			window.print();
		});
	},
	/**
	 * change the media type of the print stylesheet
	 * @return false
	 */
	setup: function(){
		var css = $('head link[href$="print-screen.css"]'); // print-screen stylesheet
		
		if(css.attr('media') == 'print'){ // if print-screen media is print
			css.attr('media', 'screen'); // change media to screen
		}else{
			css.attr('media', 'print'); // change media back to print
			ajax.init(); // reload function that could affect content change
		}

		return false;
	}
};


/**
 * Fonction to relaunch after an ajax refresh
 */
var ajax = {
	init: function() {
		JSTarget.init("rel", "external", "");
		content.init();
	}
};


/**
 * Fonctions to call on DOM ready
 */

$(document).ready(function() {
	
	if(typeof(DD_roundies) !== 'undefined' && isIe6 === true){
		DD_roundies.addRule('#logo img, #foot-logo img');
	}
	
	vars.init();
	blocs.init($('#blocs h2 a'), 'li');
	zoom.init();
	imgs.init();
	//jobs.init();
	slider.init();
	prnt.init();
	logos.init();
	content.init();
	
	if(typeof($().datepicker) !== 'undefined'){
		if($('body').hasClass('en')){ // cal EN
			$('#i-date').datepicker({
				nextText: 'Next',
				prevText: 'Previous',
				dateFormat: 'yy-mm-dd',
				showButtonPanel: false,
				currentText: "Today",
				closeText: 'Close',
				changeYear: true,
				changeMonth: true,
				minDate: new Date(),
				showAnim: 'slideDown'
			});
		}else{
			$('#i-date').datepicker({ // cal FR
				monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
				dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
				dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], // more than 2 letters break the display
				monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jui','Aoû','Sep','Oct','Nov','Déc'],
				nextText: 'Suivant',
				prevText: 'Précédent',
				dateFormat: 'yy-mm-dd',
				showButtonPanel: false,
				currentText: "Aujourd'hui",
				closeText: 'Fermer',
				changeYear: true,
				changeMonth: true,
				minDate: new Date(),
				showAnim: 'slideDown'
			});
		}
	}
});


/**
 * Fonctions to call on window load
 */
$(window).load(function() {

	content.init();
	map.init();
	
	$("#logos-slide li").each(function(){
		var position = $(this).position();
		if( position.left >= logos.dist ){
			$('#logos-next').css('display','block');
		}
	});

});
