dojo.provide("epages.widget.Calendar");
dojo.require("epages.widget");
dojo.require('dijit.Calendar');
dojo.require('epages.lang.date');
dojo.require('epages.widget.Tooltip');
dojo.require('epages.io.translation');

dojo.declare("epages.widget.Calendar", [dijit.Calendar], {
		/**
		 * public properties
		 */
		firstAvailableDate : null,
		lastAvailableDate  : null,

		/**
		 * private properties
		 */
		templateType       : "default",
		defaultTemplateType: "default", // read-only!
		templatePath       : dojo.moduleUrl("epages.widget", "templates/Calendar.html"), // need template for weeknumber
		_templateDirectory : dojo.moduleUrl("epages.widget", "templates"),
		widgetsInTemplate : true,
		_templateMapping : {
			'default' : {templatePath: dojo.moduleUrl('epages.widget', 'templates/Calendar.html')},
			'flat'    : {templatePath: dojo.moduleUrl('epages.widget', 'templates/CalendarFlat.html')}
		},
		_yearTip: '',

		postMixInProperties: function() {
			this.inherited("postMixInProperties", arguments);
			if (this._templateMapping !== undefined &&  this.templateType !== undefined &&  this._templateDirectory !== undefined) {
				if(this._templateMapping[this.templateType]!==undefined) {
					// check if set to widget's default using its prototype value
					if(this.templateType != this.defaultTemplateType) {
						var tempPath = '';

							// load templates from json object..
							if(typeof this._templateMapping[this.templateType] == 'object'){
								var TempObj = this._templateMapping[this.templateType];

								// ..from shrinksafed packages
								if(TempObj.templateString){
										this.templatePath   = null;
										this.templateString = TempObj.templateString;
								}

								// ..from sources
								else if(TempObj.templatePath){
									var TempTemplateString;
									dojo.xhrGet({
										url: TempObj.templatePath,
										sync: true,
										load: function(data){
											TempTemplateString = data;
										}
									});
									this.templatePath   = null;
									this.templateString = TempTemplateString;
								} else {
										console.warn('Template type: "'+ this.templateType +'" could not be loaded from json object! Use properties templatePath or templateString to declare its template file!');
								}
							}

					}
				} else {
					console.warn('Template type: "'+ this.templateType +'" does not exist in this widget - use default. ('+this.declaredClass+')');
				}
			}
			this._dictionary = new epages.io.Translation(dojo.moduleUrl('epages.widget', "templates/translation"), "auto");
			this._yearTip = this._dictionary.get('YearTip');


		},

		postCreate: function() {
			var d = this.value;
			this.inherited("postCreate", arguments);
			this.attr('value',null);
			this.attr('value',d);

		},

		_populateGrid: function(){
			epages.widget.Calendar.superclass._populateGrid.apply(this);
			dojo.query(".dijitCalendarWeekLabel", this.domNode).forEach(function(label, i) {
				if (i) {
					var node = label.parentNode.nextSibling;
					while (node != null && node.nodeName == '#text'){
						node = node.nextSibling;
					}
					this._setText(label, epages.lang.date.getWeekOfYear(new Date(node.dijitDateValue), dojo.cldr.supplemental.getFirstDayOfWeek(this.lang)));
				}
			}, this);
		},

		_dateNode: function (node) {
			while(node && !node.dijitDateValue){ node = node.parentNode; }
			return node;
		},

		// disallow clicks on calendar weeks
		_onDayClick: function(/*Event*/evt){
			var node = evt.target;
			if(dojo.hasClass(node, "dijitCalendarDateLabel")) {
				epages.widget.Calendar.superclass._onDayClick.apply(this, arguments);
			} else {
				dojo.stopEvent(evt);
			}
		},

		isDisabledDate: function(/*Date*/ date, /*String?*/ locale) {
			date.setHours(0,0,0,0);
			// check if a date is between a the available period
			return (this.lastAvailableDate && date > this.lastAvailableDate) ||
						 (this.firstAvailableDate && date < this.firstAvailableDate);
		},

		_onMenuHover: function(e){
			dojo.stopEvent(e);
			dojo.toggleClass(e.target, "dijitMenuItemHover");
		},

		_onMonthToggle: function(/*Event*/ evt){
			// summary:
			//      Handler for when user triggers or dismisses the month list
			// tags:
			//      protected
			dojo.stopEvent(evt);

			if(evt.type == "mousedown"){
				var coords = dojo.position(this.monthLabelNode);
//				coords.y -= dojo.position(this.domNode, true).y;
				// Size the dropdown's width to match the label in the widget
				// so that they are horizontally aligned
				var dim = {
					width: coords.w + "px",
					top: -this.displayMonth.getMonth() * coords.h + "px"
				};
				if((dojo.isIE && dojo.isQuirks) || dojo.isIE < 7){
					dim.left = -coords.w/2 + "px";
				}
				dojo.style(this.monthDropDown, dim);
				this._popupHandler = this.connect(document, "onmouseup", "_onMonthToggle");
			}else{
				this.disconnect(this._popupHandler);
				delete this._popupHandler;
			}

			dojo.toggleClass(this.monthDropDown, "dijitHidden");
			dojo.toggleClass(this.monthLabelNode, "dijitVisible");
		}
});