$.namespace('Surveys.Datepicker');


Surveys.Datepicker = $.klass({
	
	currentDate: null,
	dateFormat: null,
	dateType:-1,
	picker: null,
	scope: null,
	
	initialize: function(config){
		var that = this;

		/* This is used to keep track of the control that launches the
		 * datepicker.  The default parent for a picker is the entire document
		 */		
		this.scope = this.element.parents('.datetime-question:first');
		
		var info = this.scope.find('.q-var-info:first');
		
		var showdate = info.is('.showdateattr');
		var showtime = info.is('.showtimeattr');
		var timezoneFrom = info.is('.showzoneattr');
		var noyear = info.is('.noyearattr');
		var startDate = this.element.val();
		
		/* Find out what type of date we are dealing with */
		if (showdate == true && showtime == true && noyear == false) {
			this.dateType = 1;
			this.dateFormat = "yy-mm-dd";
		}
		else if (showdate == true && showtime == false && noyear == false) {
			this.dateType = 2;
			this.dateFormat = "yy-mm-dd";
		}
		else if (showdate == false && showtime == true && noyear == false) {
			this.dateType = 3;
			this.dateFormat = "yy-mm-dd";
		}
		else if (showdate == true && showtime == false && noyear == true) {
			this.dateType = 4;
			this.dateFormat = "mm-dd";
		}
		
		$('.datetime-question-var, .datetime-question-inst', this.scope).hide();
		
		this.bind('dateChanged', function() {
			
			that.currentDate = that.picker.datepicker('getDate');
			
			var month = $.datepicker.formatDate("yy-mm-dd",that.currentDate);
				
			var hour = $('.start-date-hour', that.scope).val();
			
			if($('.selection-start-date-ampm', that.scope).val() == "PM" && hour != "12") {
				hour = (parseInt(hour,10) + 12).toString();
			}
			if($(' .selection-start-date-ampm', that.scope).val() == "AM" && hour == "12") {
				hour = "00";
			}
			var minutes = $(' .start-date-minute', that.scope).val().toString();
			var ddate = month.split('-');
			
			month = new Date(parseInt(ddate[1],10) + "/" + parseInt(ddate[2],10) + "/" + parseInt(ddate[0],10)  + " " + parseInt(hour,10) + ":" + parseInt(minutes,10) + ":00 GMT " );
			
			if (showdate == true && showtime == true) {
				var val = (month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate() + " " + month.getUTCHours() + ":" + month.getUTCMinutes()).toString();			
			}
			else if (showdate == true && showtime == false) {
				var val = (month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate()).toString();
			}
			else if (showdate == false && showtime == true) {
				var val = (month.getUTCHours() + ":" + month.getUTCMinutes()).toString();
			}
			else {
				var val = "";
			}
			
			that.element.val(val);
		});	
		
		$.datepicker.setDefaults($.datepicker.regional[LANG_CODE]);
		//Quota/Deadline Code
		/*
		 *  For all dates which aren't month-day only we want a typical calendar
		 */

		if ( this.dateType != 4)
		{
			$('.start-datepicker', this.scope)
				.datepicker({
					dateFormat: that.dateFormat
				})
				.find(' div')
				.addClass('hasdatepicker');
				
		} 
		/* For the month-day calendar we want to hide the date and make sure
		 * the date range is just for the current year
		 */
		else
		{
			var now = new Date();
			var currentYear = now.getFullYear();
			$('.start-datepicker', this.scope)
				.datepicker({
					dateFormat: that.dateFormat,
					showYear: false,
					minDate : new Date (currentYear, 0, 1),
					maxDate : new Date (currentYear, 11, 31)
				})
				.find(' div')
				.addClass('hasdatepicker');
			
		}
		this.picker = $('.start-datepicker',this.scope);
		
		if(startDate == "" || startDate == "None") {
			
			this.currentDate = new Date();
			this.picker.datepicker('setDate',this.currentDate);
			
			$(' .start-date-span', this.scope).hide();
			month = $.datepicker.formatDate("yy-mm-dd", this.currentDate);
			hour = $('.start-date-hour', this.scope).val();
			
			if($('.selection-start-date-ampm', this.scope).val() == "PM" && hour != "12") {
				hour = (parseInt(hour,10) + 12).toString();
			}
			
			if($('.selection-start-date-ampm', this.scope).val() == "AM" && hour == "12") {
				hour = "00";
			}
			
			minutes = $('.start-date-minute', this.scope).val().toString();
			var ddate = month.split('-');
			
			month = new Date(parseInt(ddate[1],10) + "/" + parseInt(ddate[2],10) + "/" + parseInt(ddate[0],10)  + " " + parseInt(hour,10) + ":" + parseInt(minutes,10) + ":00 GMT ");
				
			if (this.dateType == 1) {
				$('.datetime-question-var input[type="text"]', this.scope).val(month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate() + " " + month.getUTCHours() + ":" + month.getUTCMinutes());
			}
			else if (this.dateType == 2 || this.dateType == 4) {
				$('.datetime-question-var input[type="text"]', this.scope).val(month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate() );
			}
			else if (this.dateType == 3) {
				$('.datetime-question-var input[type="text"]', this.scope).val( month.getUTCHours() + ":" + month.getUTCMinutes());
			}
			$('.start-date-span', this.scope).show();
			
		} else {
			
			var pieces = startDate.split(" ");
			var ddate = pieces[0];
			
			var sdate = ddate.split("-");
			var dtime;
			var stime;
			var butldate;
			
			if (this.dateType == 1) 
			{
				dtime = pieces[1];
				stime = dtime.split(":");

				butldate = new Date();
				butldate.setDate(sdate[2]);
				butldate.setYear(sdate[0]);
				/* Javascript months go from 0 - 11 */
				butldate.setMonth(sdate[1] - 1);
				butldate.setHours(stime[0]);
				butldate.setMinutes(stime[1]);
				

			}
			else if (this.dateType == 2)
			{
				butldate = $.datepicker.parseDate(that.dateFormat,startDate);

			}
			else if (this.dateType == 3)
			{
				stime = ddate.split(":");

				butldate = new Date();
				butldate.setHours(stime[0]);
				butldate.setMinutes(stime[1]);

			}
			else if (this.dateType == 4)
			{
				butldate = $.datepicker.parseDate("yy-mm-dd",startDate);
			}
			
			var hs = butldate.getHours();
			
			if(hs == 0) {
				hs = 12;
				$('option[value=AM]', $(' .selection-start-date-ampm', that.scope)).attr('selected', true);
			} else if( hs >= 12 ){
				if(hs != 12) {
					hs = hs - 12;
				}
				$('option[value=PM]', $(' .selection-start-date-ampm', that.scope)).attr('selected', true);
			}
			
			if(hs<10) {
				hstr = "0" + hs.toString();
			} else {
				hstr = hs.toString();
			}
			
			if(butldate.getMinutes() <10) {
				mstr = "0" + butldate.getMinutes().toString();
			} else {
				mstr = butldate.getMinutes().toString();
			}
			
			$('.start-date-hour', this.scope).val(hstr);
			$('.start-date-minute', this.scope).val(mstr);
			this.picker.datepicker('setDate', butldate);
			$('.start-date-span', this.scope).show();
			
			this.currentDate = butldate;
		}
		
		
		$('.start-date-lbl', this.scope)
			.val(
				$.datepicker
					.formatDate(
						that.dateFormat,
						that.currentDate
					)
			);
			
		$(' .start-date-lbl', this.scope).click(function() {
			if($(' .start-datepicker-dialog', that.scope).css('display') == "none") {
				$(' .start-datepicker-dialog', that.scope).css('position', 'absolute')
					.css('left', $(this).position().left)
					.css('top', $(this).position().top+$(this).height()+12)
					.css('z-index', '1000')
					.slideDown("slow");
			} else {
				$(' .start-datepicker-dialog', that.scope).slideUp("slow");
			}
		});
	
		/*
		 * Called when the label on the date time question changes
		 * 
		 * Performs basic validation, and if an invalid date is passed into
		 * it, the last valid date is used
		 * 
		 * Note: Due to datepicker conversions any text a valid date is
		 * ignored.  So 12-02ksdjfklsadf gets stored as 12-02 in the response
		 */
		$('.start-date-lbl',this.scope).bind('change',function()	{
			var newDate = null;
			
			try {
				newDate = $.datepicker.parseDate(that.dateFormat, $(this).val());
			}
			catch (error){
				$(this).val($.datepicker.formatDate(that.dateFormat, that.currentDate));
			}
			
			if (newDate) {
				that.picker.datepicker('setDate', newDate);
				this.currentDate = newDate;
			}
			that.trigger('dateChanged');
			
		});
		
		$('.inline-dialog', this.scope)
			.hide()
			.prepend("<div class='inline-dialog-title dialog-title'>&nbsp;" + 
			         "<span style='color: #FFFFFF; font-weight: bold; position: absolute; top: -2px; left: 2px;'>" + 
					 "<img src='" + MEDIA_URL + "img/icons/silk/calendar.png' \/>" + 
					 "<span style='position: relative; top: -2px;'>&nbsp;"+gettext("Select a date...")+"<\/span>" + 
					 "<\/span><span style='position: absolute; top: -2px; right:5px;' class='inline-dialog-close'>" +
					 "<a href='javascript:;'><img src='" + MEDIA_URL + "img/eeeeee_11x11_icon_close.gif' \/>" + 
					 "<\/a><\/span><\/div><div class='inline-dialog-content'>")
			.append("<\/div>");
		
		$('.inline-dialog-close', this.scope, $(' .start-datepicker-dialog', that.scope)).click(function() {
			$(this).parent().parent().slideUp("slow");
		});		
		
		$(' .start-date-png', this.scope).click(function() {
			if ($('.start-datepicker-dialog', that.scope).css('display') == "none") {
				$('.start-datepicker-dialog', that.scope).css('position', 'absolute')
					.css('left', $(this).position().left)
					.css('top', $(this).position().top+$(this).height()+12)
					.css('z-index', '1000')
					.slideDown("slow");
			} else {
				$(' .start-datepicker-dialog', that.scope).slideUp("slow");
			}
		});
				
		$('.start-datepicker',this.scope).change(function() {
			
			that.trigger('dateChanged');
			$('.start-date-lbl', that.scope)
				.val($.datepicker.formatDate(that.dateFormat, that.currentDate));
			$(' .start-datepicker-dialog', that.scope).slideUp("slow");
		});
		
		$(' .txt-date-hour', this.scope).change( function() {
				if ($(this).val() == ''){
					$('.txt-date-minute', that.scope).val('');
					return false;
				}		
					
				if(isNaN(parseInt($(this).val(),10))) {
					$(this).val('12');
					return false;
				}
				
				hour = parseInt($(this).val(),10);
				
				if(hour > 12) {
					if(hour < 24) {
						$(this).val((hour - 12).toString())
						$('option[value=PM]', that.scope).attr('selected', true);
						if(parseInt($(this).val(),10) < 10) {
							$(this).val('0' + $(this).val());
						}
					} else if(hour == 24) {
						$(this).val('00');
						$('option[value=AM]').attr('selected', true);
					} else {
						$(this).val('12');
					}
				} else if(hour >= 0) {
					if(hour < 10) {
						$(this).val('0'+hour.toString());
					}
				} else {
					$(this).val('12');
				}
				that.trigger('dateChanged');
				
		});
		
		$(' .txt-date-minute', this.scope).change( function() {
				if ($(this).val() == '') {
					$('.txt-date-hour', that.scope).val('');
					return false;						
				}
							
				if(isNaN(parseInt($(this).val(),10))) {
					$(this).val('00');
					return false;
				}
				minute = parseInt($(this).val(),10);
				
				if(minute < 0) 
				{
					$(this).val('00');
				
				} 
				/* Only prepend a zero to the minute field if it's less than 10
				 * and it's one digit.  (Avoids 01 becoming 001)
				 */
				else if(minute < 10 && minute.length == 1) 
				{
					$(this).val('0'+$(this).val());
				} 
				else if(minute > 59) 
				{
					$(this).val('59');
				}
				
				that.trigger('dateChanged');
				return false;
		});
		
		$(' .selection-start-date-ampm', this.scope).change(function() {
			if ($('.txt-date-minute', this.scope).val() && $('.txt-date-hours', this.scope).val()){
				that.trigger('dateChanged');
			}
		});
	
	}
});

