$.namespace('Surveys.Datepicker');

Surveys.Datepicker = $.klass({
	
	initialize: function(config){
		var that = this;
		this.parent = this.element
			.parents('.datetime-question:first');
		
		var info = this.parent.find('.q-var-info:first');
		
		var showdate = info.is('.showdateattr');
		var showtime = info.is('.showtimeattr');
		var timezoneFrom = info.is('.showzoneattr');
		
		var startDate = this.element.val();
		
		$('select option[text="---"]', this.parent).each(function(i){
			if (timezoneFrom != '') {
				timezoneFrom = parseInt(timezoneFrom, 10) + 1;
			}
		});
		
		if (timezoneFrom == 'none' || !timezoneFrom){
			timezoneFrom = '-1';
		}
		
		var soptions = {
			startDate: startDate,
			timeZone: timezoneFrom
		};
		
		$('.datetime-question-var, .datetime-question-inst', this.parent).hide();
		
		this.bind('dateChanged', function() {
			var month = $.datepicker
				.formatDate('yy-mm-dd', $(' .start-datepicker', that.parent)
				.datepicker('getDate'))
				
			var hour = $('.start-date-hour', that.parent).val();
			
			if($('.selection-start-date-ampm', that.parent).val() == "PM" && hour != "12") {
				hour = (parseInt(hour,10) + 12).toString();
			}
			if($(' .selection-start-date-ampm', that.parent).val() == "AM" && hour == "12") {
				hour = "00";
			}
			var minutes = $(' .start-date-minute', that.parent).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);
		});	
		
		
		var cur_date = new Date();
		
		//Quota/Deadline Code
		$('.start-datepicker', this.parent)
			.datepicker({
				dateFormat: 'yy-mm-dd'
			})
			.find(' div')
			.addClass('hasdatepicker');
		
		if(soptions['timeZone'] == '') {
			var getTz = new Date();
			getTz = getTz.toString().split("GMT");
			getTz = getTz[1].split(" ")[0];
			$('option[value='+getTz+']', this.parent).attr('selected', true);
		} else {
			$('option[value='+soptions['timeZone']+']', this.parent).attr('selected', true);
		}
		
		if(soptions['startDate'] == "" || soptions['startDate'] == "None") {
			
			$(' .start-datepicker',this.parent).datepicker('setDate',cur_date);
			$(' .start-date-span', this.parent).hide();
			month = $.datepicker.formatDate('yy-mm-dd', $(' .start-datepicker', this.parent).datepicker('getDate'));
			hour = $('.start-date-hour', this.parent).val();
			
			if($('.selection-start-date-ampm', this.parent).val() == "PM" && hour != "12") {
				hour = (parseInt(hour,10) + 12).toString();
			}
			
			if($('.selection-start-date-ampm', this.parent).val() == "AM" && hour == "12") {
				hour = "00";
			}
			
			minutes = $('.start-date-minute', this.parent).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) {
				$('.datetime-question-var input[type="text"]', this.parent).val(month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate() + " " + month.getUTCHours() + ":" + month.getUTCMinutes());
			}
			else if (showdate == true && showtime == false) {
				$('.datetime-question-var input[type="text"]', this.parent).val(month.getUTCFullYear() + "-" + (parseInt(month.getUTCMonth(),10) + 1).toString() + "-" + month.getUTCDate() );
			}
			else if (showdate == false && showtime == true) {
				$('.datetime-question-var input[type="text"]', this.parent).val( month.getUTCHours() + ":" + month.getUTCMinutes());
			}
			$('.start-date-span', this.parent).show();
			
		} else {
			
			var pieces = soptions['startDate'].split(" ");
			var ddate = pieces[0];
			
			var sdate = ddate.split("-");
			var dtime;
			var stime;
			
			/* Flag to indicate what type of date we are dealing with:
			 * 1 - Day and Time
			 * 2 - Day only
			 * 3 - Time only
			 */
			var dateType = 0;
			
			/* If we have two pieces to the date, there is also a time component */
			if (pieces.length == 2) 
			{
				dtime = pieces[1];
				stime = dtime.split(":");
				dateType = 1;
			}
			/* If the date only has one and it was separated by dashes we have a date only */
			else if (pieces.length == 1 && sdate.length != 1)
			{
				dateType = 2;
			}
			/* If we split on dash and have nothing, this must be a time value */
			else if (pieces.length == 1 && sdate.length == 1)
			{
				stime = ddate.split(":");
				dateType = 3;
			}
		
			var butldate;
			if (dateType == 1) 
			{
				butldate = new Date(this.createUTCDate(parseInt(sdate[0], 10), parseInt(sdate[1] - 1, 10), parseInt(sdate[2], 10), parseInt(stime[0], 10), parseInt(stime[1], 10)));
			}
			else if (dateType == 2)
			{
				butldate = new Date();
				butldate.setDate(sdate[2]);
				butldate.setYear(sdate[0]);
				/* Javascript months go from 0 - 11 */
				butldate.setMonth(sdate[1] - 1);
			}
			else if (dateType == 3)
			{
				butldate = new Date();
				butldate.setMinutes(stime[1]);
				butldate.setHours(stime[0]);
			}
			
			if(soptions['timeZone'] != '') {
				var toff = parseFloat(soptions['timeZone'])/100;
				var utco = butldate.getTime() + (butldate.getTimezoneOffset() * 60000);
				var utldate = new Date(utco + (3600000 * toff));
			} else {
				var utldate = butldate;
			}
			
			var hs = utldate.getHours();
			
			if(hs == 0) {
				hs = 12;
				$('option[value=AM]', $(' .selection-start-date-ampm', that.parent)).attr('selected', true);
			} else if( hs >= 12 ){
				if(hs != 12) {
					hs = hs - 12;
				}
				$('option[value=PM]', $(' .selection-start-date-ampm', that.parent)).attr('selected', true);
			}
			
			if(hs<10) {
				hstr = "0" + hs.toString();
			} else {
				hstr = hs.toString();
			}
			
			if(utldate.getMinutes() <10) {
				mstr = "0" + utldate.getMinutes().toString();
			} else {
				mstr = utldate.getMinutes().toString();
			}
			
			$('.start-date-hour', this.parent).val(hstr);
			$('.start-date-minute', this.parent).val(mstr);
			$('.start-datepicker', this.parent).datepicker('setDate', utldate);
			$('.start-date-span', this.parent).show();
			
		}
		
		
		$('.start-date-lbl', this.parent)
			.html(
				$.datepicker
					.formatDate(
						'M d, yy',
						$('.start-datepicker', this.parent).datepicker('getDate')
					)
			);
		
		$('.inline-dialog', this.parent)
			.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;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.parent, $(' .start-datepicker-dialog', that.parent)).click(function() {
			$(this).parent().parent().slideUp("slow");
		});		
		
		$(' .start-date-png', this.parent).click(function() {
			if ($('.start-datepicker-dialog', that.parent).css('display') == "none") {
				$('.start-datepicker-dialog', that.parent).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.parent).slideUp("slow");
			}
		});
		
		$(' .start-date-lbl', this.parent).click(function() {
			if($(' .start-datepicker-dialog', that.parent).css('display') == "none") {
				$(' .start-datepicker-dialog', that.parent).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.parent).slideUp("slow");
			}
			
		});
		
		$(' .start-datepicker', this.parent).change(function() {
			$('.start-date-lbl', that.parent)
				.text($.datepicker.formatDate('M d, yy', $(' .start-datepicker', that.parent).datepicker('getDate')));
				
			that.trigger('dateChanged');
			$(' .start-date-png', that.parent).click();
		});
		
		$(' .txt-date-hour', this.parent).change( function() {
				if(isNaN(parseInt($(this).val(),10))) {
					$(this).val('12');
					return;
				}
				
				hour = parseInt($(this).val(),10);
				
				if(hour > 12) {
					if(hour < 24) {
						$(this).val((hour - 12).toString())
						$('option[value=PM]').attr('selected', true);
						if(parseInt($(this).val(),10) < 10) {
							$(this).val('0' + $(this).val());
						}
						return;
					} else if(hour == 24) {
						$(this).val('00');
						$('option[value=AM]').attr('selected', true);
						return;
					} else {
						$(this).val('12');
						return;
					}
				} else if(hour >= 0) {
					if(hour < 10) {
						$(this).val('0'+hour.toString());
					}
				} else {
					$(this).val('12');
				}
				that.trigger('dateChanged');
				
		});
		
		$(' .txt-date-minute', this.parent).change( function() {
				if(isNaN(parseInt($(this).val(),10))) {
					$(this).val('00');
					return false;
				}
				minute = parseInt($(this).val(),10);
				
				if(minute < 0) {
					$(this).val('00');
				} else if(minute < 10) {
					$(this).val('0'+$(this).val());
				} else if(minute > 59) {
					$(this).val('59');
				}
				
				that.trigger('dateChanged');
				return false;
		});
		
		$(' .selection-start-date-ampm', this.parent).change(function() {
			that.trigger('dateChanged');
		});
	
	},
	createUTCDate: function(year, month, day, hour, minute) {
		var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		var p_hour = (hour < 10) ? "0" + hour.toString() : hour.toString();
		var p_minute = (minute < 10) ? "0" + minute.toString() : minute.toString();
		var p_day = (day < 10) ? "0" + day.toString() : day.toString();
		return months[month] + " " + p_day + ", " + year.toString() + " " + p_hour + ":" + p_minute + ":00 GMT";
	}
});

