/**
* 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 isOp = false;
var isSaf = false;

/**
 * if browser is IE
 */
if ($.browser.msie) {
	isIe = true;
}
/**
 * if browser is Opera
 */
if ($.browser.opera) {
	isOp = true;
}
/**
 * if browser is Safari
 */
if ($.browser.safari) {
	isSaf = true;
}

/**
 * create rounded corner box with shadows
 * @author: Roger Johansson, http://www.456bereastreet.com/
 */
var cbb = {
	init : function() {
		// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) { return false; }
		var oElement, oOuter, oI1, oI2, tempId;
		// Find all elements with a class name of cbb
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)cbb(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
			// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
				// Create a new element and give it the original element's class name(s) while replacing 'cbb' with 'cb'
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1cb$2');
				// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
				// Change the original element's class name and replace it with the new div
				oElement.className = 'i3';
				oElement.parentNode.replaceChild(oOuter, oElement);
				// Create two new div elements and insert them into the outermost div
				oI1 = document.createElement('div');
				oI1.className = 'i1';
				oOuter.appendChild(oI1);
				oI2 = document.createElement('div');
				oI2.className = 'i2';
				oI1.appendChild(oI2);
				// Insert the original element
				oI2.appendChild(oElement);
				// Insert the top and bottom divs
				cbb.insertTop(oOuter);
				cbb.insertBottom(oOuter);
			}
		}
	},
	insertTop : function(obj) {
		var oOuter, oInner;
		// Create the two div elements needed for the top of the box
		oOuter=document.createElement("div");
		oOuter.className="bt"; // The outer div needs a class name
		oInner=document.createElement("div");
		oOuter.appendChild(oInner);
		obj.insertBefore(oOuter,obj.firstChild);
	},
	insertBottom : function(obj) {
		var oOuter, oInner;
		// Create the two div elements needed for the bottom of the box
		oOuter=document.createElement("div");
		oOuter.className="bb"; // The outer div needs a class name
		oInner=document.createElement("div");
		oOuter.appendChild(oInner);
		obj.appendChild(oOuter);
	},
// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	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]);
			}
		}
	}
};


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


/**
 * remove and put back default values in field
 * @param targ: jquery selector of the chosen field
 */
var inputLabel = {
	/**
	 * add events on field and set default value;
	 */
	init: function(targ){
		var val1 = '';

		$(targ).each(function(){
			$(targ).focus(function(){
				if(val1 === ''){val1 = $(this).val();}
				inputLabel.clear(targ, val1);
			})
			.blur(function(){
				inputLabel.blur(targ, val1);
			})
			.addClass("label-in");
		});
	},
	/**
	 * clear the field of default value
	 */
	clear: function(targ, startValue){

		if($(targ).val() !== startValue){
			$(targ).val();
		}else{
			$(targ).val("").removeClass("label-in");
		}
	},
	/**
	 * put the default value back
	 */
	blur: function(targ, startValue){

		if($(targ).val() !== ""){
			$(targ).val();
		}else{
			$(targ).val(startValue).addClass("label-in");
		}
	}
};

/**
 * loader to insert just before ajax calls
 */
var loader = '<p class="loader center"><img src="/img/ajax-loader.gif" alt="" /></p>';


/**
 * popup creator
 * @param _url: url to call in ajax
 * @param _id: action link id
 * @param _popId: id of popup
 * @param _url: url to get and load in popup
 * @param _title: popup titlebar text
 * @param _width: popup width
 */

var popup = {
	init: function(_id, _popId, _url, _title, _width) {
		this.popId = '#'+_popId;
		var popHtml = '<div id="'+_popId+'"></div>';
		$('body').append(popHtml);

		$('#'+_id).click(function(){

			$(popup.popId).load(_url, function(){

			$(popup.popId).dialog({
					modal: true,
					autoOpen: false,
					title: _title,
					draggable: false,
					width: _width
				}).hide();

				$('.bt-cancel', this).click(function(){
					$(popup.popId).dialog('close');
					return false;
				});

				$(popup.popId).dialog('open');
			});

			return false;
		});

	}
};


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


/**
 * Fonction to show/hide submenu
 */
var menu = {
	init: function(){
		$('#menu>li>a').addClass('item');
		$('#menu>li>a, #menu .sm').each(function(){
			$(this).hover(menu.hover, menu.out);
		});

	},
	open: function(_this){
		clearTimeout(menu.timeOut);
		menu.clear();
		$(_this).closest('li').find('.sm').addClass('open').show();
		$(_this).closest('li').find('.item').addClass('over');
	},
	close: function(_this){
		menu.clear();
	},
	hover: function(){
		_this = this;
		menu.open(_this);
	},
	out: function(){
		_this = this;
		menu.timeOut = setTimeout("menu.close(_this)", 300);
	},
	clear: function(){
		$('#menu>li>a').removeClass('over');
		$('#menu .sm').removeClass('open').hide();
	}
};


/**
 * Fonction to animate the homepage slider
 */
var slider = {
	init: function() {
		$('#slider-nav a').click(this.change);
		
		slider.inter = setInterval(slider.move, 5000);
		
		slider.end = $('#slider-nav a').length;
		slider.curr = 1;
		slider.dist = $('#slider').width();
	},
	move: function() {
		if(slider.curr < slider.end){
			slider.moveTo(slider.curr + 1);
		}else{
			slider.moveTo(1);
		}
	},
	change: function() {
		clearInterval(slider.inter);
		//setTimeout("slider.inter = setInterval(slider.move, 5000);", 8000);
		slider.moveTo($(this).text());
		
		return false;
	},
	moveTo: function(_index) {
		if(!$('#slider li:animated')[0] && slider.curr != _index){
		
			$('#slider li:eq('+ (slider.curr-1) +')').css('z-index', 2).animate({
				left: -slider.dist
			}, 500, function(){
					$('#slider li:eq('+ (slider.curr-1) +')').css('z-index', 443).hide();
			});
			
			
			$('#slider li:eq('+ (_index-1) +')').animate({
				left: slider.dist
			}, 1, function(){
					$('#slider li:eq('+ (_index-1) +')').css('z-index', 1).show().removeClass('none').animate({
						left: 0
					}, 500, function(){
							$('#slider-nav li.selected').removeClass('selected');
							$('#slider-nav li:eq('+ (_index-1) +')').addClass('selected');
							if(_index <= 1){
								slider.curr = 1;
							}else{
								slider.curr = _index;
							}
					});
				});
		}
		
	}
};


/**
 * galerie photo with colorbox
 * @param _ele: jquery ele of galllery links
 */
var galerie = {
	init: function(_ele) {
	
		if($().colorbox){
			if($('body').hasClass('en')){
				prevText = 'previous';
				nextText = 'next';
				currText = '{current} of {total}';
			}else{
				if($('body').hasClass('es')){
					prevText = 'anterior';
					nextText = 'siguiente';
					currText = '{current} de {total}';
				}else{
					prevText = 'précédente';
					nextText = 'suivante';
					currText = '{current} de {total}';
				}
			}
	
			_ele.attr('rel', 'box').colorbox({
				current: currText,
				previous: prevText,
				next: nextText,
				loop: false,
				maxWidth: '100%'
			});
		}
		
	}
};


/**
 * get url params
 * @param name: param name
 */
var gup = function( name )
{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
	    return "";
	  else
	    return results[1];
};

/**
 * Date picker function
 * @param _ele: jquery ele of the input field
 * @param _range1: nb of past years to show in select
 * @param _range2: nb of future years to show in select
 */
var datePicker = {
	init: function(_ele, _range1, _range2){
		
		if($().datepicker && _ele[0]){
		
			var auj = new Date();
			var currYear = parseInt(auj.getFullYear(), 10);
	
			var rangeStart = currYear - _range1;
			var rangeEnd = currYear + _range2;
			
			if($('body').hasClass('en')){
				_ele.datepicker({
					nextText: 'Next',
					prevText: 'Previous',
					dateFormat: 'yy-mm-dd',
					showButtonPanel: false,
					currentText: "Today",
					closeText: 'Close',
					changeYear: true,
					changeMonth: true,
					yearRange: rangeStart+':'+rangeEnd,
					showAnim: 'slideDown'
				});
			}else{
				if($('body').hasClass('es')){
					_ele.datepicker({
						monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
						dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
						dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'], // more than 2 letters break the display
						monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Set','Oct','Nov','Dic'],
						nextText: 'Siguiente',
						prevText: 'Anterior',
						dateFormat: 'yy-mm-dd',
						showButtonPanel: false,
						currentText: "Hoy",
						closeText: 'Cerrar',
						changeYear: true,
						changeMonth: true,
						yearRange: rangeStart+':'+rangeEnd,
						showAnim: 'slideDown'
					});
				}else{
					_ele.datepicker({
						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,
						yearRange: rangeStart+':'+rangeEnd,
						showAnim: 'slideDown'
					});
				}
			}
		}
	}
};


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

$(document).ready(function() {

	cbb.init();
	menu.init();
	
	galerie.init($('#ls-gal .view'));
	datePicker.init($('#kid-bdate'), 10, 0);
	
	if($('#pg-acc')[0]){
		slider.init();
	}
	
	if($('#home-bloc .col3')[0]){
		equalHeight.init($('#home-bloc .col3'));
	}
	
	if(isIe === true && $.browser.version <= 7){
		DD_roundies.addRule('#schools li a', '5px 5px 0 0');
		DD_roundies.addRule('#bloc-news', '0 0 0 5px');
		DD_roundies.addRule('#bloc-eve', '0 0 5px 0');
		DD_roundies.addRule('#side .sm', '0 5px 5px 0');

		$('#col-in').corner('top');
	}
	
	if(isIe === true && ($.browser.version < 9 && $.browser.version > 7)){
		$('#schools li a').corner('top cc:#92bbe9');
		$('#col-in').corner('top');
		$('#bloc-news').corner('bl');
		$('#bloc-eve').corner('br');
		$('#side .sm').corner('tr br');
	}

});


$(window).load(function() {
	(function(){
		if(typeof(google) == 'object' && $('#gmap')[0]){
			var latlng = new google.maps.LatLng(45.601067798973766, -73.73748779296875);
			var options = {
				zoom: 11,
				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.53429594655307, -73.67435932159424),
				map: map,
				title: 'Pavillon de Montréal',
				clickable: false,
				icon: '/img/marker.png'
			});

			var marker2 = new google.maps.Marker({
				position: new google.maps.LatLng(45.65146583666382, -73.80223095417023),
				map: map,
				title: 'Pavillon de Blainville',
				clickable: false,
				icon: '/img/marker.png'
			});
		}

	})();

});

$(document).ready(function(){
	//Alumini Year slection
	$('#i-sel-year').change(function() {
		var val = $(this).val();
			if (val != '') {
				location.href=val;
			}
	});
	$('#i-sel-year2').change(function() {
		var val = $(this).val();
			if (val != '') {
				location.href=val;
			}
	});
});

