$(document).ready(init);
function init(){
	initCalendar() ;
	initCycle() ;
	initScroll() ;
	initThickbox() ;
	initSearch() ;
	initCluetip() ;
	initChronique() ;
	initFestival() ;
//	initPubBackground() ;
	
	 $(document).pngFix(); 
	
	if(typeof sIFR == "function"){
   		sIFR.replaceElement(".wrapper-article h2", named(	{
			sFlashSrc: const_base_url+"/public/images/riotsqua.swf",
		 	sColor: "#000",
			sWmode:"transparent", 
			sBgColor: "#fff"
		 }));
    	sIFR.replaceElement( "#content-wrapper h1", named(	{
			sFlashSrc: const_base_url+"/public/images/riotsqua.swf",
		 	sColor: "#000",
			sWmode:"transparent", 
			sBgColor: "#fff"
		 }));
		 
		$("#sitemap li").bind('mouseenter', function() {
			$("#sitemap li span").hide() ;
			$(this).find('span').show() ;
		});
	};
	
	var offset = $('#callSsMenuAgenda').offset();
	var decalage=$('#callSsMenuAgenda').height() + 1 ;
	
	$('#sousMenuAgenda :submit').css('width', 'auto');

	
	$('#callSsMenuAgenda').click(function () {
		$('#sousMenuAgenda').css('left', (offset.left - 40)).css('top', offset.top + decalage).slideToggle() ;
		var paramDatePicker = {
	        firstDay: 1,
	        dateFormat: 'dd-mm-yy',
	        dateStatus: 'DD d  MM yy ',
	    	navigationAsDateFormat: true, prevText: '< MM', nextText: 'MM >'
    	};
	
		$("#ssMenuCalendar").datepicker($.extend({}, $.datepicker.regional["fr"], paramDatePicker))	;
		return false ;
	});
	
	$("#ssMenuAgendaDepartement option").not('.optgroup').hide() ;
	
	$("#ssMenuAgendaDepartement").find('.optgroup').click(function() {
		$("#ssMenuAgendaDepartement").find("option[rel=" +$(this).attr('rel')+ "]").not('.optgroup').each(function() {
			$(this).attr('selected', 'selected').show();
		}) ;
	}) ;

}
function initPubBackground() {
	var generalOffset = $('#content-outer').offset();
	var generalWidth=$('#content-outer').width() ;

	$('#content-outer').mouseout(function() {
		$('body').css('cursor', 'pointer') ;
	}) ;
	$('#content-outer').mouseover(function() {
		$('body').css('cursor', 'auto') ;
	}) ;
	$(document).click(function(ev){
		mouseX = ev.pageX;
		if (mouseX<(generalOffset.left) || mouseX>(generalOffset.left+generalWidth)) {
			window.open('http://ad.fr.doubleclick.net/clk;215422074;37694548;m') ;
			//alert(mouseX+' '+generalOffset.left) ;
		}
	}) ;
}
function initFestival() {
	$('#festivalGeneral').pager('div', {
	  navId: 'navPagerFestival',
	  highlightClass : 'ui-state-highlight',
	  prevClass : 'ui-newsfestival-prev ui-corner-all',
	  prevSpanClass : ' ui-icon ui-icon-circle-triangle-w',
	  nextClass : 'ui-newsfestival-next ui-corner-all',
	  nextSpanClass : ' ui-icon ui-icon-circle-triangle-e',
	  navClass : 'ui-newsfestival-header ui-widget-header ui-helper-clearfix ui-corner-all'
	});

}
function initThickbox(){

	$("a.lightbox").lightBox({
	overlayBgColor: '#000',
	overlayOpacity: 0.7,
	imageLoading: 'public/styles/images/lightbox-ico-loading.gif',
	imageBtnClose: 'public/styles/images/lightbox-btn-close.gif',
	imageBtnPrev: 'public/styles/images/lightbox-btn-prev.gif',
	imageBtnNext: 'public/styles/images/lightbox-btn-next.gif',
	containerResizeSpeed: 350,
	txtImage: 'Image',
	txtOf: 'de'
   });

}

function initChronique () {
	$('#chroniquesDvd').hide() ;
	$('#chroniquesLivres').hide() ;
	$('#showChroniquesDisques').addClass('highlight') ;
	
	$('#showChroniquesDisques').click(function() {
		$('#chroniquesDisques').show() ;
		$('#chroniquesLivres').hide() ;
		$('#chroniquesDvd').hide() ;
		$(this).toggleClass('highlight') ;
		$('#showChroniquesDisques').addClass('highlight') ;
		$('#showChroniquesDvd').removeClass('highlight') ;
		$('#showChroniquesLivres').removeClass('highlight') ;
	}) ;
	
	$('#showChroniquesLivres').click(function() {
		$('#chroniquesLivres').show() ;
		$('#chroniquesDisques').hide() ;
		$('#chroniquesDvd').hide() ;
		$(this).toggleClass('highlight') ;
		$('#showChroniquesLivres').addClass('highlight') ;
		$('#showChroniquesDvd').removeClass('highlight') ;
		$('#showChroniquesDisques').removeClass('highlight') ;
	}) ;
	
	$('#showChroniquesDvd').click(function() {
		$('#chroniquesDvd').show() ;
		$('#chroniquesDisques').hide() ;
		$('#chroniquesLivres').hide() ;
		$(this).toggleClass('highlight') ;
		$('#showChroniquesDvd').addClass('highlight') ;
		$('#showChroniquesLivres').removeClass('highlight') ;
		$('#showChroniquesDisques').removeClass('highlight') ;
	}) ;
}
function initCluetip() {
	$('a.cluetip').cluetip({local:true, cursor: 'pointer'});
	$('a.cluetipChronique').cluetip({local:true, cursor: 'pointer',positionBy:'fixed',leftOffset : -340, topOffset : -68, width : 240, cluezIndex: 120});
}
function initSearch() {
	$('#lm_qsearch').focus(function() {
		$(this).val('') ;
	});
}

jQuery.log = function(message){
    if (window.console && window.console.log) {
      window.console.log(message);
  	};
}
function initCalendar(){

    var paramDatePicker = {
        firstDay: 1,
        dateFormat: 'yy/mm/dd',
        dateStatus: 'DD d  MM yy ',
        onSelect: function(date) { 
        	window.location = const_base_url+"/agenda/" + date.substring(0, 4) + "/"+ date.substring(5, 7)+ "/"+ date.substring(8, 10);
    	},
    	navigationAsDateFormat: true, prevText: '< MM', nextText: 'MM >'
    };
	
    $("#general-calendar").attr('rel', 'formatLink') ;
   	customizeDatePicker() ;
    $("#general-calendar").datepicker($.extend({}, $.datepicker.regional["fr"], paramDatePicker)) ;
}
function initScroll() {
	if ($("#ticker-news").length >0 ) {
		$('#ticker-news').addClass('ui-widget').addClass('ui-widget-content').addClass('ui-helper-clearfix').addClass('ui-corner-all').addClass('ui-newspager') ;
		
		$('#ticker-news').pager('ul', {
		  navId: 'navPagerNews',
		  navClass:'ui-pager-nav',
		  highlightClass : 'ui-state-highlight',
		  prevClass : 'ui-newspager-prev ui-corner-all',
		  prevSpanClass : ' ui-icon ui-icon-circle-triangle-w ui-corner-all',
		  nextClass : 'ui-newspager-next ui-corner-all',
		  nextSpanClass : ' ui-icon ui-icon-circle-triangle-e ui-corner-all',
		  navClass : 'ui-newspager-header ui-widget-header ui-helper-clearfix ui-corner-all' 
		}) ;
		$('#ticker-news').css('visibility', 'visible');
		$('#ticker-news a').mouseover(function() {$(this).addClass('ui-state-hover');}) ;
		$('#ticker-news a').mouseout(function() {$(this).removeClass('ui-state-hover');}) ;

	}
}
function initCycle() {
	if ($("#slider").length > 0) {
		$("#slider").after('<ul id="nav-pager">').cycle({
			speed: 1,
			timeout: 4000,
			pager: '#nav-pager',
			pagerEvent: 'mouseover',
			fastOnEvent: true,
			containerResize : 0,
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				imgSrc = $(slide).find('.slider-img').eq(0).attr('src');
				return '<li><a href="#"><img src="' + imgSrc + '" width="60" height="25" /></a></li>';
			}
		});
		$('.slider-overlay').css('visibility', 'visible') ;
	}
}
// redefine Cycle's updateActivePagerLink function 
$.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) {
    $(pager).find('li').removeClass('activeLI')
	.filter('li:eq('+currSlideIndex+')').toggleClass('activeLI'); 
}; 

function customizeDatePicker() {
jQuery.datepicker._generateHTML= function(inst) {
		var boolFormat=false;
		if ($('#'+inst.id).attr('rel')=='formatLink') {boolFormat=true ;}
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>';
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '')+ // highlight selected day
							(boolFormat==true ? 
							'" href="agenda/'+drawYear+'/'+ // formatage du mois
							(drawMonth>=10 ?(drawMonth+1) : '0'+(drawMonth+1) )+ '/'+
							(printDate.getDate()>=10 ? printDate.getDate() : '0'+printDate.getDate() )+'">' + 
							(printDate.getDate()>=10 ? printDate.getDate() : '0'+printDate.getDate() ) + '</a>' + '</td>' // display for this month
							:
							'" href="#">' + printDate.getDate() + '</a>' + '</td>' // display for this month
							)));
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' : '');
				group += calender;
			}
			html += group;
		}
		html += (!inst.inline ? buttonPanel : '') +
			($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	};
}

	
