var ferme1 = new Array();
var ferme2 = new Array();

// Filtres pour déclencher les initiliazers de pages
var triggers = [
	{
		filter:'body.home', 
		funct:initHome
	},
	{
		filter:'body.schedule', 
		funct:initSchedule
	},
	{
		filter:'body.rides', 
		funct:initRides
	},
	{
		filter:'body.rink', 
		funct:initRink
	},
	{
		filter:'body.invitation-form', 
		funct:initInvitation
	},
	{
		filter:'body.newsletter', 
		funct:initNewsletter
	},
	{
		filter:'body.birthday-parties', 
		funct:initParties
	}
];



/*--------------------------------------------------------------
	Globals
--------------------------------------------------------------*/
var lang;

/*--------------------------------------------------------------
	Entry point
--------------------------------------------------------------*/

$(document).ready(function(){
	lang = ($('html').attr('lang')) ? $('html').attr('lang') : 'fr';
	
	// Call global initializer
	initMenu();
	initWindowEvents();
	
	// Loop through triggers to call initializer
	for (var i = 0; i < triggers.length; i++) {
		var trigger = triggers[i];
		
		if ($(trigger.filter).length) {
			trigger.funct();
			
			break;
		}
	}
});

/*--------------------------------------------------------------
	Global initializers
--------------------------------------------------------------*/

function initCustomSelect() {
	var selects = $('select');
	
	if (!selects.length) {
		return false;
	}
	
	selects.sb({});
}

function initWindowEvents() {
	$('p#top-page').hide();
	
	$('a.scroll').smoothScroll();

	window.didResize = false;
	$(window).bind('resize', onWindowResize);
	
	if ($('ul.menu-scroll').length || $('div.scroll').length ) {
		window.didScroll = false;
		$(window).bind('scroll', onWindowScroll);
	}
	
	var windowInterval = setInterval(onWindowInterval, 500);
}

function initMenu() {
	var flashvars = {};
		flashvars.items = '/' + lang + '/menu.json';
		flashvars.lang = lang;
	
	var params = {};
		params.menu = false;
		params.wmode = 'transparent';
		params.allowscriptaccess = 'always';
	
	var attributes = {};
		attributes.id = 'nav-secondary';

	swfobject.embedSWF('/swf/menu.swf', 'nav-secondary', '960', '210', '9.0.0','/swf/expressInstall.swf', flashvars, params, attributes);
}

function initMiddleClick() {
	$(window).mousedown(onWindowMouseDown);
}

function initCalendars() {

	

	$.datepicker.setDefaults($.datepicker.regional[(lang == 'fr') ? lang : 'en']);
	
	var calendars = $('div.calendar');
	
	if (!calendars.length) {
		return false;
	}
	
	var d = new Date();
	
	var opts = {};
		opts.onSelect = onDateSelect;
		opts.onChangeMonthYear = onChangeMonthYear;
		opts.beforeShowDay = setDateStatus;
		opts.minDate = new Date(d.getFullYear(), d.getMonth(), 1);
		
		
		
	calendars.each(
		function() {
			$(this)
				.datepicker(opts)
					.find('a.ui-state-highlight')
					.parent().trigger('click');		
					onInitSetClosed(d.getFullYear(), (d.getMonth()+1), 2);
		}
	);
	
	
}


/*--------------------------------------------------------------
	Page initializers
--------------------------------------------------------------*/
function initHome() {
	initSlideShow();
	refreshSchedules();
}

function initSchedule() {
	initCalendars();
	refreshSchedules();
}

function initRink() {

	var d = new Date();
	
	initCalendars();
	$('#rink-schedule').find('a.ui-state-highlight')
					.parent().trigger('click');		
					onInitSetClosed(d.getFullYear(), (d.getMonth()+1), 2);
	refreshSchedules();
}

function initRides() {
	initCustomSelect();
	
	$('form#select-view select').change(function() {
		window.location.href = window.location.href.replace(/\?(.*)/, '') + '?type=' + $(this).val();
	});
}

function initParties() {
	 setHeight('.horaire-fete-enfants li');
}

function initNewsletter() {
	$('.bulle').hide();
	$('#confirmation').hide();
	
	// Placeholders for text inputs
	$('input, textarea').live('focusin', onInputFocusIn);
	$('input, textarea').live('focusout', onInputFocusOut);
	
	//$('form').bind('submit', onFormSubmit);
	
	$('#form-fields .liens-boutons a').click(
		function() {
			if (validateForm($('#form-fields'))) {
				//$('#form-fields').hide();
				//$('#confirmation').show();
				$('#frm-infolettre').submit();
			} else {
				$('.bulle').show();
			}
			
			return false;
		}
	);
}

function initInvitation() {
	console.log('initInvitation');
	
	initCustomSelect();
	
	$('.bulle').hide();
	
	// Placeholders for text inputs
	$('input, textarea').live('focusin', onInputFocusIn);
	$('input, textarea').live('focusout', onInputFocusOut);
	
	$('form').bind('submit', onFormSubmit);
	
	$('#form-fields .liens-boutons a').click(
		function() {
			if (validateForm($('#form-fields'))) {
				$('#form-fields').hide();
				$('#email-friends').show();
			} else {
				$('.bulle').show();
			}
			
			return false;
		}
	);
	
	$('#email-friends .liens-boutons a').click(
		function() {
			if (validateForm($('#email-friends'))) {
				$(this).parents('form').trigger('submit');
			} else {
				$('.bulle').show();
			}
			
			return false;
		}
	);
}

/*--------------------------------------------------------------
	Functions
--------------------------------------------------------------*/
function getMovie(movieName) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};

function validateForm(form) {
	var validForm = true;
	
	var email_reg = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "g");
	var postal_reg = /([a-z])\d([a-z])(.?)\d([a-z])\d/gi;
	
	form.find(':input').each(function() {
		var value = $(this).val();
		var validField = true;
		
		if ($(this).hasClass('required')) {
			if (!value) {
				validField = false;
			} else if (value == $(this).attr('title')) {
				validField = false;
			} else if ($(this).hasClass('email') && !value.toLowerCase().match(email_reg)) {
				validField = false;
			} else if ($(this).hasClass('postal') && !value.match(postal_reg)) {
				validField = false;
			} else if ($(this).is(':checkbox') && !$(this).is(':checked')) {
				validField = false;
			}
		}
		
		if (!validField) {
			validForm = false;
			
			if ($(this).is(':checkbox')) {
				$(this).parent().addClass('error');
			} else {
				$(this).addClass('error');
			}
			
		} else {
			
			if ($(this).is(':checkbox')) {
				$(this).parent().removeClass('error');
			} else {
				$(this).removeClass('error');
			}
		}
	});
	
	return validForm;
}

/*--------------------------------------------------------------
	Events
--------------------------------------------------------------*/

function onWindowMouseDown(ev) {
	if (ev.which == 2) {
		// getMovie('nav-secondary').middleClick();
	}
}

function onWindowResize() {
	window.didResize = true;
}

function onWindowScroll() {
	window.didScroll = true;
}

function onWindowInterval() {
	if (window.didScroll) {
		window.didScroll = false;
		
		var top = $('p#top-page');
		var body = $('html, body');
		
		var percent = body.scrollTop() / ($(document).height() - $(window).height());
		
		if (percent > 0.9) {
			top.animate({marginBottom: 115 * percent}, 250);
		} else {
			top.animate({marginBottom: 0}, 250);
		}
		
		if (body.scrollTop() <= 400 ||( body.scrollTop() > 400 && body.scrollTop() <= $("div.left-col").height()+50)) {
			top.fadeOut(250);
		} else {
			top.fadeIn(250);
		}
	}
	
	if (window.didResize) {
		window.didResize = false;
		
		if ($(window).height() > $('body').height()) {
			$('body, .background-lines, .background-castle, .background-roller-coaster').css('height', '100%');
		} else {
			$('body, .background-lines, .background-castle, .background-roller-coaster').css('height', 'auto');
		}
	}
}

function onDateSelect(dateText, inst) {
	var box = inst.dpDiv.parents('.box:first');
	var type = inst.dpDiv.parent().data('type');
	
	var params = {};
		params.type = (type) ? type : 1;
		params.day = dateText;
		params.lang = lang;
	
	var date = new Date(dateText);
		
	var info = box.find('div.calendar-info:first');
	
	$.ajax(
		{
			url:'/ajax/get_schedule',
			type:'get',
			data:params,
			success:function(data) {
				info.find('p.month').html(data.month);
				info.find('p.date').html(data.date);
				
				info.find('p.schedule').html(data.schedule);
				
				if (data.closed) {
					info.find('p.closed').show();
					if(type == 1) $('#park-schedule a.ui-state-active').addClass('closed');
					if(type == 2) $('#rink-schedule a.ui-state-active').addClass('closed');
				} else {
					info.find('p.closed').hide();
				}
			},
			dataType:'json'
		}
	);
}

function onInitSetClosed(year, month, type) {
	var params = {};
		params.type = (type) ? type : 1;
		params.year = year;
		params.month = month;
	
	$.ajax(
		{
			url:'/ajax/get_month_closed',
			type:'get',
			async:false,
			data:params,
			success:function(data) {
				switch(type) {
					case 1:
						ferme1 = data;
						break;
					case 2:
						ferme2 = data;
						break;
				}
			},
			dataType:'json'
		}
	);
}


function onChangeMonthYear(year, month, inst) {
	var box = inst.dpDiv.parents('.box:first');
	var type = inst.dpDiv.parent().data('type');
	
	var params = {};
		params.type = (type) ? type : 1;
		params.year = year;
		params.month = month;
	
		
	var info = box.find('div.calendar-info:first');
	
	$.ajax(
		{
			url:'/ajax/get_month_closed',
			type:'get',
			async:false,
			data:params,
			success:function(data) {
				switch(type) {
					case 1:
						ferme1 = data;
						break;
					case 2:
						ferme2 = data;
						break;
				}
			},
			dataType:'json'
		}
	);
	
}



var tabDates = null;

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

function setDateStatus(dateReceived){
	var arr = new Array();
	var params = {};
	
		
	dt = new Date(dateReceived);
	
	var css = "";
	switch(this.id) {
		case "park-schedule":
			if(dt.getDate() in oc(ferme1)) {
				css = "closed";
			}
			break;
		case "rink-schedule":
			if(dt.getDate() in oc(ferme2)) {
				css = "closed";
			}
			break;
	}
		
	arr = new Array(true,css,"");
	
	return arr;
}

/**
 *	Form submit
 */
function onFormSubmit() {
	if (!validateForm($(this))) {
		return false;
	}
	
	var action = $(this).attr('action');
	var method = $(this).attr('method');
	
	var data = {};
	
	// Populate data fields
	$(this).find(':input').each(function() {
		var name = $(this).attr('name');
		var value = $(this).val();
		
		if ($(this).is('[type=submit]') || $(this).is('[type=image]') || $(this).is('[type=button]')) {
			return false;
		}
		
		if (value == $(this).attr('title')) {
			return false;
		}
		
		if ($(this).is(':checkbox') && $(this).is(':not(:checked)')) {
			value = '';
		}
		
		if (name.match(/\[\]/g)) {
			name = name.replace(/\[\]/g, '');
			
			if (typeof(data[name]) == 'undefined') {
				data[name] = [];
			}
			
			data[name].push(value);
		} else {
			data[name] = value;
		}
		
	});
	
	$.ajax({
		type:method,
		url:action,
		data:data,
		success:function(data) {
			if (data.match(/error/g)) {
				onFormSubmitError(data);
			} else {
				onFormSubmitSuccess(data);
			}
		},
		error:onFormSubmitError
	});
	
	return false;
}

function onFormSubmitSuccess(data) {
	console.log('onFormSubmitSuccess');
	
	$('#form-fields').hide();
	$('#email-friends').hide();
	$('#confirmation').show();
}

function onFormSubmitError(data) {
	console.log('onFormSubmitError');
	
	if (data.match(/\//)) {
		window.location.href = data;
	}
	
	onLoadComplete();
}

/**
 *	Input focus in event
 */
function onInputFocusIn() {
	var value = $(this).val();
	var defaultValue = $(this).attr('title');
	
	if (value == defaultValue) {
		$(this).val('');
	}
	
	$(this).removeClass('error');
	$(this).parents('.error:first').removeClass('error');
}

/**
 *	Input focus out event
 */
function onInputFocusOut() {
	var value = $(this).val();
	var defaultValue = $(this).attr('title');
	
	if (value == '') {
		$(this).val(defaultValue);
	}
}

/* same height cols */
var maxHeight = 0;
function setHeight(column) {
    //Get all the element with class = col
    column = $(column);
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();;
        }
    });
    //Set the height
    column.height(maxHeight);
}

/* select custom */

function visibilitySelects(visibility){
	$("select").each(function(i){
		$(this).css("visibility", visibility);
	});
}

/*--------------------------------------------------------------
	Slideshow
--------------------------------------------------------------*/

function initSlideShow(){
	// Initialize Slides
	$('#slides').slides({
		generatePagination: true,
		play: 5000,
		pause: 2500,
		hoverPause: false,
		slideSpeed: 500
	});
};


/*--------------------------------------------------------------
	Refresh schedules
--------------------------------------------------------------*/
function refreshSchedules() {
	var d = new Date();
	
	if(d.getHours() == 0 && d.getMinutes == 0) window.location.reload();
	
	dateChargementT = setTimeout("refreshSchedules()", 6000);
}
