/* flexdate: a multi-calendar date picker with a simple time picker */
// Copyright (c) 2009 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

(function($){

$.ui.flexcal.subclass('ui.flexdate',{
	setDate: function(d){
		this._super(d);
		var box = this.box();
		var h = this.d.getHours(), m = this.d.getMinutes(), ampm = 0;
		if (h > 12){
			h -= 12;
			ampm = 1;
		}else if (h == 0){
			h = 12;
		}else if (h == 12){
			ampm = 1;
		}
		if (m < 10) m = '0'+m;
		box.find('.ui-flexdate-time input:eq(0)').val(h);
		box.find('.ui-flexdate-time input:eq(1)').val(m);
		box.find('.ui-flexdate-ampm input').eq(ampm).attr('checked', 'checked');
	},
	commit: function(d){
		this.d = d;
		var box = this.box();
		var h = parseInt(box.find('.ui-flexdate-time input:eq(0)').val()) % 12;
		if (box.find('.ui-flexdate-ampm input:eq(1)').attr('checked')) h += 12;
		this.d.setHours(h);
		this.d.setMinutes(parseInt(box.find('.ui-flexdate-time input:eq(1)').val()));
		this._super(this.d);
	},
	format: function(d){
		var h = d.getHours(), m = d.getMinutes(), ampm = 0;
		if (h > 12){
			h -= 12;
			ampm = 1;
		}else if (h == 0){
			h = 12;
		}else if (h == 12){
			ampm = 1;
		}
		if (m < 10) m = '0'+m;
		// is this now faster than [].join? I can't keep track
		return $.ui.flexcal.date2string(d)+' '+h+':'+m+[' AM',' PM'][ampm];
	},
	options: {
		url: '/inc/flexdate.html'
	}
});

})(jQuery);