Ext.namespace('Ext.ux'); 

Date.prototype.getFirstDateOfWeek = function(){
	var value = this.clone();
	var dayOfWeek = this.getDay();
	dayOfWeek = (dayOfWeek + 6) % 7;
	value.setDate(value.getDate() - dayOfWeek);
	return value;
}


Ext.ux.DatePickerRange = Ext.extend(Ext.DatePicker, { 
    selectionMode:'week',
    
	amount: 1,
	
    setSelectionMode:function(mode){
        this.selectionMode=mode;
        this.setValue(this.value);
		//Update todayBtn Text on mode change
		this.todayBtn.setText(this._TodayText());

		
		if(mode=='month')
		{
			this.showMonthPicker();
		}else{
			this.hideMonthPicker();
		}
		
    },
	
    getSelectionMode:function()
    {
        return this.selectionMode();
    },
	
    handleDateClick : function(e, t){
    	
		e.stopEvent();
        if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){
			if (Ext.EventObject.shiftKey) {
				if (t.dateValue && t.dateValue >= this.activeDate) {
					
					var d = new Date(t.dateValue);
					var DAY = 86400000;
					
					if(this.selectionMode=='day') {
						this.amount = ((d.getTime() - this.activeDate.getTime()) / DAY) + 1;
					//if(this.selectionMode=='month')
					//	this.amount = 1;
					} else if(this.selectionMode=='week'){
						var days = d.getFirstDateOfWeek().getTime() - this.activeDate.getFirstDateOfWeek().getTime() + DAY;
						this.amount = Math.ceil(days / (DAY * 7));
					}
					
					this.setValue(new Date(this.value));
				}
			} else {
				
				this.amount = 1;
				this.setValue(new Date(t.dateValue));
			}
			
			this.fireEvent("select", this, this.value, this.amount);
        }
       
    },
    createMonthPicker : function(){
        if(!this.monthPicker.dom.firstChild){
            var buf = ['<table border="0" cellspacing="0">'];
            for(var i = 0; i < 6; i++){
                buf.push(
                    '<tr><td class="x-date-mp-month"><a href="#">', Date.getShortMonthName(i), '</a></td>',
                    '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', Date.getShortMonthName(i + 6), '</a></td>',
                    i === 0 ?
                    '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
                    '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
                );
            }
            buf.push(
                '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
                    this.okText,
                    '</button><button type="button" class="x-date-mp-cancel" id="buttoncancelId">',
                    this.cancelText,
                    '</button></td></tr>',
                '</table>'
            );
            this.monthPicker.update(buf.join(''));

            this.mon(this.monthPicker, 'click', this.onMonthClick, this);
            this.mon(this.monthPicker, 'dblclick', this.onMonthDblClick, this);

            this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
            this.mpYears = this.monthPicker.select('td.x-date-mp-year');

            this.mpMonths.each(function(m, a, i){
                i += 1;
                if((i%2) === 0){
                    m.dom.xmonth = 5 + Math.round(i * 0.5);
                }else{
                    m.dom.xmonth = Math.round((i-1) * 0.5);
                }
            });
        }
    },

    showMonthPicker : function(){
        if(!this.disabled){
            this.createMonthPicker();
            
            
            var size = this.el.getSize();
            this.monthPicker.setSize(size);
            this.monthPicker.child('table').setSize(size);

            this.mpSelMonth = (this.activeDate || this.value).getMonth();
            this.updateMPMonth(this.mpSelMonth);
            this.mpSelYear = (this.activeDate || this.value).getFullYear();
            this.updateMPYear(this.mpSelYear);
            
            //do not show cancel if choose month
			if( this.selectionMode =='month')
        	{
        		Ext.get('buttoncancelId').setStyle('display', 'none');
        	}else{
        		Ext.get('buttoncancelId').setStyle('display', '');
        	}
            //this.monthPicker.slideIn('t', {duration:0.0});
            this.monthPicker.show();
        }
    },
    // private
    hideMonthPicker : function(disableAnim){
        if(this.monthPicker){
            if(disableAnim === true){
                this.monthPicker.hide();
            }else{
                this.monthPicker.hide();
            }
        }
    },
    
    onMonthDblClick : function(e, t){
        e.stopEvent();
        var el = new Ext.Element(t), pn;
        
        if((pn = el.up('td.x-date-mp-month', 2))){
            this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
            
            if(this.selectionMode == 'month')
            {
            	 this.fireEvent("select", this, new Date(this.mpSelYear, this.mpSelMonth));
            }else{
            	this.hideMonthPicker();
            }
            
           
        }
        else if((pn = el.up('td.x-date-mp-year', 2))){
            this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
            if(this.selectionMode == 'month')
            {
            	 this.fireEvent("select", this, new Date(this.mpSelYear, this.mpSelMonth));
            }else{
            	this.hideMonthPicker();
            }
        }
    },
    

    onMonthClick : function(e, t){
        e.stopEvent();
        var el = new Ext.Element(t), pn;
        if(el.is('button.x-date-mp-cancel')){
        	
        	//its not necessary because button cancel is not visible if month selected
        	if( this.selectionMode =='month')
        	{
	        }else{
        		this.hideMonthPicker();
        	}
        
        }
        else if(el.is('button.x-date-mp-ok')){
            var d = new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate());
            if(this.selectionMode == 'month')
        	{
	            this.fireEvent("select", this, new Date(this.mpSelYear, this.mpSelMonth));
	            return;
        	}
            if(d.getMonth() != this.mpSelMonth){
                // 'fix' the JS rolling date conversion if needed
                d = new Date(this.mpSelYear, this.mpSelMonth, 1).getLastDateOfMonth();
            }
            this.update(d);
            
           
            this.hideMonthPicker();
        		
        	
        }
        else if((pn = el.up('td.x-date-mp-month', 2))){
            this.mpMonths.removeClass('x-date-mp-sel');
            pn.addClass('x-date-mp-sel');
            this.mpSelMonth = pn.dom.xmonth;
        }
        else if((pn = el.up('td.x-date-mp-year', 2))){
            this.mpYears.removeClass('x-date-mp-sel');
            pn.addClass('x-date-mp-sel');
            this.mpSelYear = pn.dom.xyear;
        }
        else if(el.is('a.x-date-mp-prev')){
            this.updateMPYear(this.mpyear-10);
        }
        else if(el.is('a.x-date-mp-next')){
            this.updateMPYear(this.mpyear+10);
        }
    },

	
	//private
    update : function(date){
    //	alert('update');
        var vd = this.activeDate;
        this.activeDate = date;
        if(vd && this.el){
            var t = date.getTime();
            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
                this.cells.removeClass("x-date-selected");
                this.cells.each(function(c){
                   if(this.isSelected(  c.dom.firstChild.dateValue  )){
                       c.addClass("x-date-selected");
                   }
                },this);
                return;
            }
        }
        var days = date.getDaysInMonth();
        var firstOfMonth = date.getFirstDateOfMonth();
        var startingPos = firstOfMonth.getDay()-this.startDay;

        if(startingPos <= this.startDay){
            startingPos += 7;
        }

        var pm = date.add("mo", -1);
        var prevStart = pm.getDaysInMonth()-startingPos;

        var cells = this.cells.elements;
        var textEls = this.textNodes;
        days += startingPos;

        
        var day = 86400000;
        var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
        var today = new Date().clearTime().getTime();
        var sel = date.clearTime().getTime();
        var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
        var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
        var ddMatch = this.disabledDatesRE;
        var ddText = this.disabledDatesText;
        var ddays = this.disabledDays ? this.disabledDays.join("") : false;
        var ddaysText = this.disabledDaysText;
        var format = this.format;
		
        var setCellClass = function(cal, cell){
            cell.title = "";
            var t = d.getTime();
            cell.firstChild.dateValue = t;
            if(t == today){
                cell.className += " x-date-today";
                cell.title = cal.todayText;
            }
            if(cal.isSelected(cell.firstChild.dateValue)){
                cell.className += " x-date-selected";
            }
            
            if(t < min) {
                cell.className = " x-date-disabled";
                cell.title = cal.minText;
                return;
            }
            if(t > max) {
                cell.className = " x-date-disabled";
                cell.title = cal.maxText;
                return;
            }
            if(ddays){
                if(ddays.indexOf(d.getDay()) != -1){
                    cell.title = ddaysText;
                    cell.className = " x-date-disabled";
                }
            }
            if(ddMatch && format){
                var fvalue = d.dateFormat(format);
                if(ddMatch.test(fvalue)){
                    cell.title = ddText.replace("%0", fvalue);
                    cell.className = " x-date-disabled";
                }
            }
        };

        var i = 0;
        for(; i < startingPos; i++) {
            textEls[i].innerHTML = (++prevStart);
            d.setDate(d.getDate()+1);
            cells[i].className = "x-date-prevday";
            setCellClass(this, cells[i]);
        }

        for(; i < days; i++){
            intDay = i - startingPos + 1;
            textEls[i].innerHTML = (intDay);
            d.setDate(d.getDate()+1);
            cells[i].className = "x-date-active";
            setCellClass(this, cells[i]);
        }
        var extraDays = 0;
        for(; i < 42; i++) {
             textEls[i].innerHTML = (++extraDays);
             d.setDate(d.getDate()+1);
             cells[i].className = "x-date-nextday";
             setCellClass(this, cells[i]);
        }

        this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());

        if(!this.internalRender){
            var main = this.el.dom.firstChild;
            var w = main.offsetWidth;
            this.el.setWidth(w + this.el.getBorderWidth("lr"));
            Ext.fly(main).setWidth(w);
            this.internalRender = true;
            
            if(Ext.isOpera && !this.secondPass){
                main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
                this.secondPass = true;
                this.update.defer(10, this, [date]);
            }
        }
    },
	//end update
    
    
    isSelected:function(date){
		// date to test
        date=new Date(date).clearTime();
		// activeDate
		ad = new Date(this.value).clearTime();
		var DAY = 86400000;
		
        if(this.selectionMode=='day') {
			date = date.getTime()
			for (var i=0; i<this.amount;++i) {
				if (date == ad.add(Date.DAY,i).getTime()) return true;
			}
			return false;
		}
        if(this.selectionMode=='month')
            return date.getFirstDateOfMonth().getTime() == this.value.getFirstDateOfMonth().getTime();
		
        if(this.selectionMode=='week'){
			var refTime = date.getFirstDateOfWeek().getTime();
			var ad = ad.getFirstDateOfWeek();
			
			if (refTime == ad.getTime())
				return true;
			
			for (var i=1; i<this.amount;++i) {
				ad.setDate(ad.getDate() + 7);
				if (refTime == ad.getTime())
					return true;
			}
			return false;
        }
        throw 'Illegal selection mode';
    
    },
	
    getValues : function(startEnd, unix_timestamp) {
        //arguments
        startEnd            = (startEnd === undefined)?false:startEnd;
        unix_timestamp        = (unix_timestamp === undefined)?false:unix_timestamp; 
        //predefined data
        var currentAmount    = this.amount;
        var currentValue    = this.value;
        var currentDate        = new Date(currentValue);
        var date            = new Date(currentDate);
        //private data
        var selectedDates    = new Array();
        var push            = false;
        var tmp_date        = null;
        
        switch (this.selectionMode) {
            case 'week':
                currentAmount  *= 7;
                currentDate     = date.getFirstDateOfWeek();
                break;
                
            case 'month':
                currentAmount  *= date.getDaysInMonth();
                currentDate        = date.getFirstDateOfMonth();
                break;
                
            default:
        }
        
        for (var i = 0; i < currentAmount; i++) {
            push = (startEnd)?((i === 0 || (i + 1) === currentAmount)?true:false):true;
            if (push) {
                tmp_date = currentDate.add(Date.DAY, i).getTime();
                tmp_date = (unix_timestamp)?parseInt(tmp_date / 1000):tmp_date;
                selectedDates.push(tmp_date);
                tmp_date = null;
            }
        }
        
        return selectedDates;
    },
	
	selectToday : function(){
        if(this.todayBtn && !this.todayBtn.disabled){
			this.amount = 1;
	        this.setValue(new Date().clearTime());
	        this.fireEvent("select", this, this.value);
        }
    },
	
	_TodayText : function () {
		var todayText = '';
		switch (this.selectionMode) {
			case 'day':
				todayText += 'Heute';
				break;
				
			case 'week':
				todayText += 'Aktuelle Woche';
				break;
				
			case 'month':
			default:
				todayText += 'Aktuelle Monat';
		}
        return todayText;
	},
	
	initComponent: function() {
		this.todayText = this._TodayText();
        Ext.ux.DatePickerRange.superclass.initComponent.apply(this, arguments);
    }
        
    
}); 

Ext.reg('datepickerrange', Ext.ux.DatePickerRange);
