/*
 * Author:
 *      david.marquis 2010
 */

;(function($) {
    /**
     * Documentation here
     */
    $.fn.multifieldDate = function(options) {
        var settings = $.extend({
            regional: {
                dayHint: 'JJ',
                monthHint: 'MM',
                yearHint: 'AAAA'
            },
            day: {
                className: "multi-date-day",
                suffix: "-day",
                maxlength: 2,
                size: 2,
				label: 'Jour'
            },
            month: {
                className: "multi-date-month",
                suffix: "-month",
                maxlength: 2,
                size: 2,
				label: 'Mois'
            },
            year: {
                className: "multi-date-year",
                suffix: "-year",
                maxlength: 4,
                size: 4,
				label: 'Année'
            },
            dateFormat: "dd/mm/yyyy",
            validAttributeName: "isDateValid"
        }, options);

        return this.each(function(idx, el) {
            var txtDate = $(el);
			var pi = $(txtDate).parent().children('img').wrap('<div class="field date picker-image"/>');
			var editor = new MultiFieldDateEditor(txtDate, settings);

            // layout elements
            $(editor.wrapFields(editor.fields,settings)).insertBefore(txtDate);

            // configure original input
            txtDate.css({width: 0, "font-size": 0, border: 0, visibility: "hidden"});
			txtDate.parent('div').find('[for='+txtDate.attr('id')+']').css('display', 'none');
			$(txtDate).detach().appendTo(pi.parent());
			el.dateFields = editor.fields;
        });
		
    };

    function MultiFieldDateEditor(field, settings) {
        this.settings = settings;
        this.originalField = field;
        this.fieldName = field.attr("name");
		
        this.createFields();
        this.bindEvents();

        var currentValue = $(this.originalField).val();
        this.updateDate((currentValue == null || currentValue == "") ? null : $(this.originalField).datepicker("getDate"));
    }

    MultiFieldDateEditor.prototype.createFields = function () {
        var settings = this.settings;
        var fieldName = this.fieldName;
		
        this.txtDay = $("<input/>").attr(this.generateFieldAttributes(fieldName, settings.day)).addClass(settings.day.className);
        this.txtMonth = $("<input/>").attr(this.generateFieldAttributes(fieldName, settings.month)).addClass(settings.month.className);
        this.txtYear = $("<input/>").attr(this.generateFieldAttributes(fieldName, settings.year)).addClass(settings.year.className);
        this.fields = [this.txtDay, this.txtMonth, this.txtYear];

        var editor = this;
        this.originalField.bind('dateSelected', function(event, params) {
            editor.updateDate(params.date);
        }).attr(this.settings.validAttributeName, false);
    };

    MultiFieldDateEditor.prototype.bindEvents = function () {
        var editor = this;
        var handler = function (e) {
			//alert('blur');
			//console.log(editor.originalField.attr('id'), 'val = '+$(this).val()+' :: oldValue = '+$(this).attr('oldValue'));
			var el = $(this);
			var target = e.target;
			if(el.val() != el.attr('oldValue')) {
				el.attr('oldValue', el.val());
				el.attr('hasChange', "true");
			}
            editor.pushDate();
			// $('body').bind('focusin.'+editor.originalField.attr('id')+' click.'+editor.originalField.attr('id'), function(e) {
			$('body').bind('focusin.'+target.id+' click.'+target.id, function(e) {
				$('body').unbind('focusin.'+target.id+' click.'+target.id);
				var ot = e.target;
				if(ot != editor.txtDay.get(0) && 
				   ot != editor.txtMonth.get(0) && 
				   ot != editor.txtYear.get(0)) {
						$(editor.originalField).valid();
				}
			});
        };
		
        $(this.txtDay).bind('focusout', handler);
        $(this.txtMonth).bind('focusout', handler);
        $(this.txtYear).bind('focusout', handler);
		
		//$('body').bind('focusin.body', function() {alert('focusin')});
    };

    MultiFieldDateEditor.prototype.generateFieldAttributes = function(fieldName, attr) {
        return $.extend({
            name : fieldName + attr.suffix,
			id : fieldName + attr.suffix,
			hasChange: "false",
			oldValue: "",
			type: "text"
        }, attr);
    };
    
	MultiFieldDateEditor.prototype.wrapFields = function(fields, settings) {
		var html = '';
		var ret = [];
		var type = ['day', 'month', 'year'];
		
		$(fields[0]).attr('title', settings.regional.dayHint);
		$(fields[1]).attr('title', settings.regional.monthHint);
		$(fields[2]).attr('title', settings.regional.yearHint);
		
		var labels = [settings.day.label,settings.month.label,settings.year.label];
		for(var i=0; fields[i]; i++) {
			var field = $('<div class="field date ' + type[i] + '" />');
			var el = $(fields[i]).appendTo(field);
			$('<div class="label"><label for="'+$(fields[i]).attr('id')+'">'+labels[i]+'</label></div>').appendTo(field);
			ret.push(field);
		}
		return ret;
    };

    MultiFieldDateEditor.prototype.updateDate = function (date) {
        this.txtDay.val("");
        this.txtMonth.val("");
        this.txtYear.val("");

        if (date != null) {
            this.txtDay.val($.zeroPad(date.getDate(), 2));
            this.txtMonth.val($.zeroPad(date.getMonth() + 1, 2));
            this.txtYear.val(date.getFullYear());
			//console.log('my value is = ', $(this.originalField).val());
			$(this.originalField).attr(this.settings.validAttributeName, true).trigger('focusout');
        }
    };

    MultiFieldDateEditor.prototype.pushDate = function () {
        var srcField = $(this.originalField);
        var day = this.getAndFixFieldValueAsNumber(this.txtDay, 2);
        var month = this.getAndFixFieldValueAsNumber(this.txtMonth, 2) - 1;
        var year = this.getAndFixFieldValueAsNumber(this.txtYear, 4);
        var date = new Date(year, month, day);
        var isDateValid = this.isSameDate(date, day, month, year);

		var values = {
			day: $(this.txtDay).val(),
			dayTitle: $(this.txtDay).attr('title'),
			month: $(this.txtMonth).val(),
			monthTitle: $(this.txtMonth).attr('title'),
			year: $(this.txtYear).val(),
			yearTitle: $(this.txtYear).attr('title')
		};
		
        srcField.attr(this.settings.validAttributeName, isDateValid);
        srcField.val((values.day.length && values.day !== values.dayTitle ? values.day+'/' : '')+(values.month.lenght && values.month !== values.monthTitle?values.month+'/':'')+(values.year !== values.yearTitle ? values.year : ''));
		//console.log(srcField.attr('id'), srcField.val());
        if (!isNaN(date.getTime()) && isDateValid) {
            srcField.datepicker("setDate", date);
        }
    };

    MultiFieldDateEditor.prototype.getAndFixFieldValueAsNumber = function (field, length) {
        var valueAsInt = parseInt($(field).val(), 10);
        if (valueAsInt < 0 || isNaN(valueAsInt)) {
            valueAsInt = 0;
        }
        // possibly fix entered value to match expected format
        $(field).val(valueAsInt === 0 ? $(field).val() : $.zeroPad(valueAsInt, length));
        return valueAsInt;
    };

    MultiFieldDateEditor.prototype.isSameDate = function(date, day, month, year) {
        return (date.getDate() == day && date.getMonth() == month && date.getFullYear() == year);
    }

})(jQuery);
