/*
	This is a modified version of Lightbox done by Fabien Udriot (http://www.ecodev.ch) with jquery integration.
	I first started with the script example done by www.macrabbit.com (Jan Van Boghout). 
		
	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://huddletogether.com/projects/lightbox/

	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
*/

var currentMonth = null;
var currentYear = null;
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);

var macImageZoomAnimationTimer = null;
var macImageZoomWaitTimer = null;
var macImageZoomAnimationFrame = 0;
var isFirstMacImageZoom = true;
var progressWheelFrameHeight = 40;

$(document).ready(function() {
	
	//CALENDAR CMD
	$('#nextBt').click(getNextEvents);
	$('#previousBt').click(getPreviousEvents);
	$('#currentMonth').change(changeMonth);
	$('#currentYear').change(changeYear);
	
	//CALENDAR DETAIL
	$('.cal-event').click(showLayoutEvent); //add a listener
	$('.cal-event-big').click(showLayoutEvent); //add a listener
	
	initLayoutEvent(); //this generate some html	
});

function changeMonth(){
	
	//update date navigation variables...
	currentMonth = this.value - 0;
	nextMonth = nextMonth - 0;
	previousMonth = previousMonth - 0;
	nextYear = $('#currentYear').attr('value') - 0;
	previousYear = $('#currentYear').attr('value') - 0;
	
	switch(currentMonth){
		case 12 :
			nextMonth = 1;
			previousMonth = 11;
			nextYear++;
			break;
		case 1 : 
			nextMonth = 2;
			previousMonth = 12;
			previousYear--;
			break;
		default :
			nextMonth = currentMonth + 1;
			previousMonth = currentMonth - 1;
			break;
	}
	$.post(getEventsURL,{'categoryId': categoryId,'month' : currentMonth, 'year' : currentYear,'lang': langEvent, 'allEvents' : allEvents},setEvents);
}

function changeYear(){
	//update date navigation variables...
	var diff = this.value - currentYear;
	currentYear = this.value - 0;
	nextYear = nextYear - 0 + diff;
	previousYear = previousYear - 0 + diff;
	
	$.post(getEventsURL,{'categoryId': categoryId,'month' : currentMonth, 'year' : currentYear,'lang': langEvent, 'allEvents' : allEvents},setEvents);
}

function getNextEvents(){
	//give the calendar a limit max
	if(!(currentMonth == 12 && (nextYear) > (maxYear - 0))){
		$.post(getEventsURL,{'categoryId': categoryId,'month' : nextMonth, 'year' : nextYear,'lang': langEvent, 'allEvents' : allEvents},setEvents);
		
		//update the current month - year
		currentMonth = nextMonth;
		currentYear = nextYear;
		//update the next month variables
		if(nextMonth == 12){
			nextMonth = 1;
			nextYear++;
		}
		else{
			nextMonth ++;
		}
		//update the previous month variables
		if(previousMonth == 12){
			previousMonth = 1;
			previousYear++;
		}
		else{
			previousMonth++;
		}	
	}
}

function getPreviousEvents(){
	//give the calendar a limit min
	if(!(currentMonth == 1 && (previousYear) < (minYear - 0))){
		$.post(getEventsURL,{'categoryId': categoryId,'month' : previousMonth, 'year' : previousYear, 'lang': langEvent, 'allEvents' : allEvents},setEvents);
		//update the current month - year
		currentMonth = previousMonth;
		currentYear = previousYear;
		
		//update the next month variables
		if(nextMonth == 1){
			nextMonth = 12;
			nextYear--;
		}
		else{
			nextMonth --;
		}
		
		//update the previous month variables
		if(previousMonth == 1){
			previousMonth = 12;
			previousYear--;
		}
		else{
			previousMonth--;
		}
	}
}

//when the user navigate in the calendar
function setEvents(data){
	var cols = data.split('****');
	
	var j = 0; 
	for(var i = 1; i <= (cols.length) / 2; i++){
		var month = $.trim(cols[j]);
		j++;
		var html = $.trim(cols[j]);
		j++;
		
		$('#colHeader'+ (i)).find('span').remove();
		$('#colHeader'+ (i)).html(month);
		$('#colEvent'+ (i)).find('div').remove();
		$('#colEvent'+ (i)).html(html);
	}
	
	$('.cal-event').click(showLayoutEvent); //add a listener
	$('.cal-event-big').click(showLayoutEvent); //add a listener
	
	$('#currentMonth').attr('value',currentMonth);
	$('#currentYear').attr('value',currentYear);
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	pageHeight = (yScroll < windowHeight) ? windowHeight : yScroll;
	pageWidth = (xScroll < windowWidth) ? windowWidth : xScroll;

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getPageOffsetY()
{
	if (self.pageYOffset)
		return self.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	else if (document.body)
		return document.body.scrollTop;
		
	return 0;
}

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

function eventKeyDown(e) {
	var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;
	var c = (window.event) ? event.keyCode : e.keyCode;
	if (c == Esc) { hideLayoutEvent(); }
}

function showLayoutEvent(mouseEvent,me)
{
	// prep objects
	var zoomedImage = document.getElementById('macImageZoom-image');
	
	var arrayPageSize = getPageSize();
	var scrollY = getPageOffsetY();

	// set height of Overlay to take up whole page and show
	$('#overlayCal').css('height',arrayPageSize[1] + 'px');
	$('#overlayCal').css('display','block');
	
	//
	var spaceTop = scrollY + ((arrayPageSize[3] - 35 - progressWheelFrameHeight) / 2);
	var spaceLeft = ((arrayPageSize[0] - 20 - progressWheelFrameHeight) / 2);
	$('#eventContainer').css('top',(spaceTop - 100) + 'px');
	$('#eventContainer').css('left',(spaceLeft-200) + 'px');
	$('#progressWheel').css('top',spaceTop + 'px');
	$('#progressWheel').css('left',spaceLeft + 'px');
	
	// Listen to escape
	document.onkeypress = eventKeyDown;
	
	if (document.getElementById('progressWheel') != null)
		macImageZoomWaitTimer = setInterval(delayAnimateLoad, 500); //make the wheel turns
		
	if($.browser.msie){
		//prevent a display bug in IE
		$('select').css('visibility','hidden');
	}
	
	var id = $(this).find('input').attr('value');
	$.post(getEventDetailURL,{ 'id': id, 'lang': langEvent },handleData);
}

function delayAnimateLoad()
{
	clearInterval(macImageZoomWaitTimer);
//	document.getElementById('progressWheel').style.display = 'block';
	macImageZoomAnimationTimer = setInterval(animateLoad, 66);
}

function animateLoad()
{
	var loadIndicator = document.getElementById('progressWheel');
	loadIndicator.style.backgroundPosition = '0 -'+(macImageZoomAnimationFrame * progressWheelFrameHeight)+'px';
	macImageZoomAnimationFrame = (macImageZoomAnimationFrame + 1) % 12;
}

function hideLayoutEvent()
{
	clearInterval(macImageZoomWaitTimer);
	clearInterval(macImageZoomAnimationTimer);
	$('#overlayCal').css('display','none');
	$('#progressWheelContainer').css('display','inline');
	if($.browser.msie){
		$('select').css('visibility','visible');
	}
	$('#eventContainer').css('visibility','hidden');
	document.onkeypress = '';
}

function stopProp(event){
	if(window.event){
		window.event.cancelBubble = true;
	}
	if(event){
		event.stopPropagation(); 
	}
}

function initLayoutEvent(){
	
	var html = '<div style="display: none;" id="overlayCal">' +
					'<div id="bgTransparent"></div>' +
				    '<div id="eventContainer" onclick="if(window.event){window.event.cancelBubble = true;}if(event){event.stopPropagation();}">' +
				      '<div id="tableDetailDiv"></div>' +
				      '<div id="closeDiv"></div>' +
				      '<div id="closeBtDiv">' +
				        '<a href="" onclick="return false" style="text-decoration: underline" id="closeBt">'+strCloseBt+'</a>' +
				        '<div>' +
				          '<a href="http://www.mozilla-europe.org/fr/" target="_blank">' +
				            '<img src="'+getFirefoxImg+'"/>' +
				          '</a>' +
				        '</div>' +
				      '</div>' +
				    '</div>' +
				    '<a href="#" id="progressWheelContainer">' +
				      '<span id="progressWheel" style="position: absolute; z-index: 150;"/>' +
				    '</a>' +
				'</div>';
	$('body').append(html);
	$('#eventContainer').click(stopProp);
	$('#closeDiv').click(hideLayoutEvent);
	$('#closeBtDiv a:eq(0)').click(hideLayoutEvent);
	$('#overlayCal').click(hideLayoutEvent);
	$('#eventContainer').css('visibility','hidden');
  
	//register some event
	$('#eventContainer').Draggable(
	{
		zIndex: 	1000,
		ghosting:	true,
		opacity: 	0.7
	}
	);
}

function handleData(data){
	$('#tableDetailDiv').html(data);
  	$('#eventContainer').css('visibility','visible');
	$('#progressWheelContainer').css('display','none');
}

/********* UTIL *********/
function echo(data){
	try{
		dump(data+"\n");
		console.log(data);
	}
	catch(e){
		e = null;
	}
}