/*
 * JavaScript PNCalendar
 * version 0.1
 *
 * Copyright (c) 2009 Rafael Lucio (poste9 [at] gmail [dot] com[nospam])
 * JavaScript PNCalendar is licensed under the LGPL license.
 *
 * Visit www.postenove.com.br for more information.
 * @dependence: utmjs
 * download at: http://utmproject.org
 */
 
 /**
 * Constants
 */
 UNABLE_TO_FIND_LANG_FILE = "Language file not found";
 MONTH_OUT_OF_RANGE       = "Invalid Month";
 
 var PNCalendar = new utm.Class({
	/**
	* Constructor function
	* @param Date date
	*/
	__construct:function( date ) {
		/**
		* Defines init date to display in calendar.
		* If not passed as param in constructor of the class,
		* current date will be considered
		* @name Date date
		* @default new Date()
		*/
		this.date = (date) ? date : new Date();
		
		 /**
		* Defines calendar in flat form (Case false, it'll be displayed in absolute position)
		* @name Boolean flat
		* @default true
		*/
		this.flat = true;
		
		/**
		* Defines language 
		* @name language
		* @default en
		*/
		this.language = "en";
		
		/**
		* Defines template 
		* @name template
		* @default calendar-unordered-list.pntpl
		*/
		this.template = 'calendar-unordered-list.pntpl';
		
		
		this.selectedDates = [];
	},
	/**
	* Load language file
	* @param String lang
	* Defines wich language file will be loaded
	* @default 'en'
	*/
	getLang:function(lang) {
		lang && (this.language = lang);
		
		var langfile = utm.file('/js/projects/pncalendar/lang/pncalendar-lang-'+this.language+'.pnjs').text;
		
		if (!langfile) { alert(UNABLE_TO_FIND_LANG_FILE); return; }
		this.dateTranslated = eval("("+langfile+")");
	},
	//Obtém o calendário
	getCalendar:function() {
		var firstMonthDay = new Date(this.date.getFullYear(), this.date.getMonth(), 1).getDay(),
			lastMonthDay  = new Date((new Date(this.date.getFullYear(), this.date.getMonth()+1,1))-1).getDate();
			
		this.makeCalendarHash(firstMonthDay, lastMonthDay);
		return this.makePNCalendar();
	},
	//Gera as datas
	makeCalendarHash:function(firstMonthDay,lastMonthDay) {
		this.calendarHash = [];
		for(var i=0;i<firstMonthDay;i++)this.calendarHash.push("");
		//for(var i=1;i<=lastMonthDay;i++)this.calendarHash.push((i > 9)?i:"0"+i);
		for(var i=1;i<=lastMonthDay;i++)this.calendarHash.push(i);
	},
	//Altera o mês
	refreshMonth:function(month) {
		
		this.date = new Date(this.date.getFullYear(), month-1, 1);
		this.getCalendar();		
	},
	refreshYear:function(year) {
		this.date = new Date(year, this.date.getMonth(), 1);
		this.getCalendar();		
	},
	onUpdateChange:function(el, format) {
		this.onupdate = true;
		this.updateElement = u(el);
		this.updateFormat  = format;
	},
	makePNCalendar:function() {
		if (this.onupdate) {
			this.updateElement[0].innerHTML = this.updateFormat
								 .replace("%M",this.dateTranslated.Month[this.date.getMonth()])
								 .replace("%Y",this.date.getFullYear());
			
		}
		
		var PNCalendar   = u.create("div#pncalendar-container"), 
			PNTemplate   = u.file('/js/projects/pncalendar/tpl/'+this.template).text.replace(/[\n\r]/g,''),
			delimiter    = PNTemplate.match(/%section \|delimiter=([^%]*)%/)[1],
			loopTemplate = PNTemplate.match(/%section[^%]*%(.+)%\/section%/)[1],
			container    = PNTemplate.replace(/(.+)?%section[^%]*%.+%\/section%(.+)?/,'$1%container%$2'),
			loopTemplateModified="";
			
			var m = this.date.getMonth()+1, y = this.date.getFullYear(), d = this.date.getDate();
			var current_date = new Date(),
 				current_day = current_date.getDate();

			for(var i=-1;typeof this.calendarHash[++i] != 'undefined';) {

				if (i && (i % 7 == 0)) loopTemplateModified+=delimiter;
				
				var value = loopTemplate.replace('%day_number%', this.calendarHash[i]);
				var value = value.replace('%day_name%', this.dateTranslated.Day[i % 7] );
				var is_selected = u.index(this.selectedDates,m+"/"+this.calendarHash[i]+"/"+y);

				is_selected != -1 && 
				(value = value.replace('%day_class%','pncalendar-selected %day_class%'));
				
				if (current_date.getMonth() == this.date.getMonth()) {
				
				this.calendarHash[i] == current_day &&
				(value = value.replace('%day_class%','pncalendar-current-day %day_class%'));

				this.calendarHash[i] < (current_day-1) &&
				(value = value.replace('%day_class%','pncalendar-previous-day %day_class%'));				
				
				this.calendarHash[i] > current_day &&
				(value = value.replace('%day_class%','pncalendar-next-day %day_class%'));
				} else {
					if ((current_date.getMonth() < this.date.getMonth()) || ( current_date.getFullYear() < this.date.getFullYear()) )
					value = value.replace('%day_class%','pncalendar-next-day %day_class%');
					else 
					value = value.replace('%day_class%','pncalendar-previous-day %day_class%');
				}
				
				mm= m > 9 ? m : "0"+m;
				var dd=this.calendarHash[i]>9?this.calendarHash[i]:"0"+this.calendarHash[i];
				if (is_selected != -1) {
					value = value.replace("%attrs%", 'onclick=window.location.href="/home/'+
					y+'-'+mm+'-'+dd+'"');
				} else {
					if ((this.calendarHash[i] >= current_day -1) || (current_date.getMonth() < this.date.getMonth()) || ( current_date.getFullYear() < this.date.getFullYear())){
						value = value.replace("%attrs%", "onclick="+this.handler+".clickHandler('"+dd+"','"+mm+"','"+y+"')");
					}
				}
				
				if (!this.calendarHash[i]) value = value.replace('%day_class%','pncalendar-unselectable');
				loopTemplateModified+=value;
			}

			var conta = 7 - this.calendarHash.length % 7;
			if (conta < 7) {
			for (var j=0;j<conta;j++) {
				value = loopTemplate.replace('%day_number%', '')
									.replace('%day_class%','pncalendar-unselectable')
									.replace('%day_name%', this.dateTranslated.Day[(i+j) % 7]);
				loopTemplateModified+=value;
			}
			}
			container = container.replace('%container%',loopTemplateModified);
			PNCalendar[0].innerHTML = container;
			if (!this.calendar) this.calendar = PNCalendar;
			else this.calendar[0].innerHTML = container;
		return PNCalendar;
	},
	clickHandler:function(dd,mm,yyyy) {
		if (this.onclick) this.onclick(dd,mm,yyyy);

	},
	setSelectedDates:function(datesObj) {
		this.selectedDates = datesObj;
	}
 });