/* Опции */

function Calendar(mode)
{
	this.mode = mode;
    this.mainNode = null;
    this.root = null;
    this.buffer = null;
    this.body = null;
    this.lang = 'RUS';
    this.initialized = false;
    this.date = new Date();
    this.days = new Array();
    this.daysInMonth = 0;
    this.wasShown = false;
    this.fromMonth = 0;
    this.toMonth = 12;
    this.fromDay = 0;
    this.toDay = 31;
    this.fromYear = 0;
    this.toYear = 0;
    this.selectedYear = 0;
    this.selectedMonth = 0;
    this.selectedDay = 0;
this.curYear = 0;
this.curMonth = 0;
this.curDay = 0;
this.startEndDateLink = '';
}

Calendar.prototype.getDate = function() { return new Date(this.date); };
Calendar.prototype.setDate = function(date) { this.date = date; };
Calendar.prototype.getLang = function() { return this.lang.toUpperCase(); };
Calendar.prototype.setFromMonth = function(num) { this.fromMonth = num; };
Calendar.prototype.setToMonth = function(num) { this.toMonth = num; };
Calendar.prototype.setFromYear = function(num) { this.fromYear = num; };
Calendar.prototype.setToYear = function(num) { this.toYear = num; };
Calendar.prototype.setFromDay = function(num) { this.fromDay = num; };
Calendar.prototype.setToDay = function(num) { this.toDay = num; };

Calendar.prototype.setMonth = function(num)
{
	var newDate = new Date(this.date);

	newDate.setMonth(num, 1);
//, newDate.getDate()
//alert(num);
//alert(typeof(newDate.getDate()));
//alert(typeof(newDate.getDate()*1));
//alert(newDate.getMonth());
    if(this.isValidDate(newDate, 'MONTH'))
    {
//alert('month valid');
        this.date = new Date(newDate);
this.curMonth = num;
        this.process(true);
    }

    else
    {
//alert('month not valid');
        if(this.date.getFullYear() == this.fromYear)
        {
            newDate.setMonth(this.fromMonth, newDate.getDate());
        }
        else if(this.date.getFullYear() == this.toYear)
        {
            newDate.setMonth(this.toMonth, newDate.getDate());
        }
        this.date = new Date(newDate);
        this.process(true);
    }

};

Calendar.prototype.setYear = function(num)
{
    var newDate = new Date(this.date);
    newDate.setFullYear(num, newDate.getMonth(), 1);
//newDate.getMonth(), newDate.getDate()

    if(this.isValidDate(newDate, 'YEAR'))
    {
this.curYear = num;
        if(!this.isValidDate(newDate, 'MONTH'))
        {
//alert('month not valid');
            if(this.date.getFullYear() == this.fromYear)
            {
                newDate.setMonth(this.date.getMonth(), 1);
//newDate.getDate()
            }
            else if(this.date.getFullYear() == this.toYear)
            {
                newDate.setMonth(this.date.getMonth(), 1);
//newDate.getDate()
            }
        }
//alert(newDate.getMonth());
        this.date = new Date(newDate);
        this.process(true);
    }
};

Calendar.prototype.isValidDate = function(date, mode)
{
    mode = (typeof(mode) == 'string') ? mode : "ALL";
    var from = 0;
    var to = 0;
    var curr = 0;
    if(mode.toUpperCase() == 'YEAR')
    {
        from = parseInt(this.fromYear,10);
        to = parseInt(this.toYear,10);
        curr = parseInt(date.getFullYear(),10);
    }
    else if(mode.toUpperCase() == 'MONTH')
    {
        from = parseInt(this.fromYear + '' + ( (this.fromMonth < 10) ? '0'+this.fromMonth : this.fromMonth ),10);
        to = parseInt(this.toYear + '' + ( (this.toMonth < 10) ? '0'+this.toMonth : this.toMonth ),10);
        curr = parseInt(date.getFullYear() + '' + ( (date.getMonth() < 10) ? '0'+date.getMonth() : date.getMonth() ),10);
    }
    else
    {
        from = parseInt(this.fromYear + '' + ( (this.fromMonth < 10) ? '0'+this.fromMonth : this.fromMonth ) + '' + ( (this.fromDay < 10) ? '0'+this.fromDay : this.fromDay ),10);
        to = parseInt(this.toYear + '' + ( (this.toMonth < 10) ? '0'+this.toMonth : this.toMonth ) + '' + ( (this.toDay < 10) ? '0'+this.toDay : this.toDay ) ,10);
        curr = parseInt(date.getFullYear() + '' + ( (date.getMonth() < 10) ? '0'+date.getMonth() : date.getMonth() ) + '' + ( (date.getDate() < 10) ? '0'+date.getDate() : date.getDate() ),10);
    }

    return (curr >= from && curr <= to);
};

Calendar.prototype.init = function (prefix)
{
    this.mainNode = $(prefix);
    this.root = this.mainNode.getElementsByTagName('table')[0];
    this.body = this.root.tBodies[this.root.tBodies.length - 1];

    if(!this.initialized)
    {
        this.initGlobalVariables();
    }
};

Calendar.prototype.show = function()
{
    if(!this.mainNode)
    {
        return false;
    }

    if(this.mainNode.offsetHeight > 0)
	{
		this.process(false);
		return false;
	}	
	else
	{
		this.process(true);
		return true;
	}
};

Calendar.prototype.process = function(show)
{
	var i,j;
    if(this.buffer === null)
    {
        this.buffer = this.root.cloneNode(true);
        this.buffer.style.display = 'none';
    }
	
    if(this.wasShown) // if was shown, then we need to clear old values
    {
        for(i=0; i<this.root.tBodies.length; i++)
        {
            count = this.root.tBodies[i].rows.length;
            for(j=count-1; j>=0; j--)
            {
                this.root.tBodies[i].deleteRow(j);
            }
        }

        // then insert default templates
        for(i=0; i<this.buffer.tBodies.length; i++)
        {
            for(j=0; j<this.buffer.tBodies[i].rows.length; j++)
            {
                this.root.tBodies[i].appendChild(this.buffer.tBodies[i].rows[j].cloneNode(true));
            }
        }

        this.wasShown = false;
    }

    if(!show)
    {
        this.root.parentNode.style.display = 'none';
    }

    this.getDays();
    this.prepareDayRows();

    if(show)
    {
        this.root.parentNode.style.display = 'block';
        this.wasShown = true;
    }
};

Calendar.prototype.parse = function(node, value)
{
	var i;
	if(node.nodeType == 1) // if HTML object node
    {
        var nodes = node.childNodes;
		if(node.tagName == 'DIV')
		{
			var thisDate = new Date(this.date);
			var thisYear = thisDate.getFullYear();
			var thisMonth = thisDate.getMonth();
			
			var nowDate = new Date();
	    	var nowYear = nowDate.getFullYear();
			var nowMonth = nowDate.getMonth();
			var nowDay = nowDate.getDate();

			if (DATES_EVENTS)
			{
				if (DATES_EVENTS['year_'+thisYear+''])
				{
					if(DATES_EVENTS['year_'+thisYear+'']['month_'+(thisMonth*1+1)+''])
					{
						var dateArray = DATES_EVENTS['year_'+thisYear+'']['month_'+(thisMonth*1+1)+''];
						for(var day in dateArray)
						{
							var dayWithEvent = 0;
							if (dateArray[day] == value)
							{
								setItemEvent(node,value,this.mode);
								break;
							}
							if (dayWithEvent === 0)
							{
								node.innerHTML = '<span>'+value+'</span>';
							}
						}
					}
					else
					{
						node.innerHTML = '<span>'+value+'</span>';
					}
				}
				else
				{
					node.innerHTML = '<span>'+value+'</span>';
				}	
			}
			else
			{
				node.innerHTML = '<span>'+value+'</span>';
			}
			
			if (value !== '')
			{
				if ((thisYear < nowYear) || (thisYear == nowYear && thisMonth < nowMonth) || (thisYear == nowYear && thisMonth == nowMonth && value < nowDay))
		    	{
    				node.className = 'lastDay';
		    	}
		    	if ((thisYear == nowYear) && (thisMonth == nowMonth) && (value == nowDay))
		    	{
    				node.className = 'today';
		    	}
		    	if ((thisYear > nowYear) || (thisYear == nowYear && thisMonth > nowMonth) || (thisYear == nowYear && thisMonth == nowMonth && value > nowDay))
		    	{
    				node.className = 'nextDay';
		    	}
		    	if ((thisYear == this.selectedYear) && (thisMonth == this.selectedMonth) && (this.selectedDay == value))
		    	{
	    			node.className = 'selectedDay';
		    	}
		    }
		}
        for(i=0; i<nodes.length; i++)
        {
           this.parse(nodes[i], value); // recursive parse child nodes  
        }
    }
};

Calendar.prototype.getDays = function()
{
	var i;
    this.days = new Array();
    var tmpDate = new Date(this.date);

    tmpDate.setDate(1);

    var offsetLeft = tmpDate.getDay() - 1;
    if(tmpDate.getDay() === 0)
    {
        offsetLeft = 6;
    }

    this.daysInMonth = getDaysInMonth(tmpDate);
    var offsetRight = 7 - ( new Date( tmpDate.setDate(this.daysInMonth) ) ).getDay();
    offsetRight = ( offsetRight == 7 ) ? 0 : offsetRight;

    var j = 1;
    for(i = offsetLeft * -1; i < (this.daysInMonth + offsetRight); i++ )
    {
        if(this.daysInMonth <= i)
        {
            this.days[this.days.length] = j;
            j++;
        }
        else
        {
            this.days[this.days.length] = (i >= 0) ? i+1 : i;
        }
    }
};

Calendar.prototype.prepareDayRows = function()
{
	var i,j,lock = 0;
    var rows = this.days.length / 7 - 1;
    for(i=0; i<rows; i++)
    {
        this.body.appendChild( this.body.rows[0].cloneNode(true) );
    }

    var k = 0;
    var daysInPrevMonth = 0;
    for(i=0; i<this.body.rows.length; i++)
    {
        tr = this.body.rows[i];
        for(j=0; j<tr.cells.length; j++)
        {
            var day = new Date(this.date);

            var td = tr.cells[j];

		//if (this.days[k] >= 1 && k < this.daysInMonth)
		if (this.days[k] >= 1 && this.days[k] <= this.daysInMonth && !lock)
            {
		if (this.days[k] == this.daysInMonth) lock = 1;
                day.setDate(this.days[k]);
                /*
                if(day.getDay() === 0 || day.getDay() == 6)
                {
                    //td.className = 'holiday';
                }
				*/
                //var now = new Date();
                /*
                if( day.getFullYear()+''+day.getMonth()+''+day.getDate() == now.getFullYear()+''+now.getMonth()+''+now.getDate() )
                {
                    //td.className = 'today';
                }
                */
                this.parse(td, day.getDate());
            }

            var isValid = this.isValidDate(day);

            this.setDayHandlers(td, isValid);

            k++;
        }
    }
};

Calendar.prototype.setDayHandlers = function(td, valid)
{
	var i;
    var links = td.getElementsByTagName('DIV');
    /*
    for(i=0; i<links.length; i++)
    {
        if(valid)
        {
            //links[i].onclick = function(value) { alert(value); };
            //links[i].onmouseover = function() {  };
            //links[i].onmouseout = function() {  };
        }
        else
        {
            //links[i].onclick = function() { return false; };
        }
    }
    */
};

Calendar.prototype.initGlobalVariables = function()
{
    var lang = getAttributeByName(this.mainNode, 'LANG');
    if(lang !== '')
    {
        this.lang = lang.toUpperCase();
    }

    var fromDate = getAttributeByName(this.mainNode, 'FROM_DATE');
    if(fromDate !== '')
    {
        var fromDateVals = fromDate.split('.');
        if(fromDateVals.length === 0)
        {
            this.setFromYear(parseInt(fromDate,10));
        }
        else if(fromDateVals.length == 2)
        {
            this.setFromMonth(parseInt(fromDateVals[0],10) - 1);

            this.setFromYear(parseInt(fromDateVals[1],10));
        }
        else if(fromDateVals.length == 3)
        {
            this.setFromDay(parseInt(fromDateVals[0],10));
            this.setFromMonth(parseInt(fromDateVals[1],10) - 1);
            this.setFromYear(parseInt(fromDateVals[2],10));
        }
    }

    var toDate = getAttributeByName(this.mainNode, 'TO_DATE');
    if(toDate !== '')
    {
        var toDateVals = toDate.split('.');
        if(toDateVals.length === 0)
        {
            this.setToYear(parseInt(toDate,10));
        }
        else if(toDateVals.length == 2)
        {
            this.setToMonth(parseInt(toDateVals[0],10) - 1);
            this.setToYear(parseInt(toDateVals[1],10));
        }
        else if(toDateVals.length == 3)
        {
            this.setToDay(parseInt(toDateVals[0],10));
            this.setToMonth(parseInt(toDateVals[1],10) - 1);
            this.setToYear(parseInt(toDateVals[2],10));
        }
    }

    var startDate = getAttributeByName(this.mainNode, 'START_DATE');
    if(startDate !== '')
    {
        var startDateVals = startDate.split('.');
        var startTime = new Date();

        if(startDateVals.length === 0)
        {
            startTime.setFullYear(parseInt(startDate,10));
        }
        else if(toDateVals.length == 2)
        {
            startTime.setFullYear(parseInt(startDateVals[1],10), parseInt(startDateVals[0],10) - 1);
        }
        else if(toDateVals.length == 3)
        {
            startTime.setFullYear(parseInt(startDateVals[2],10), parseInt(startDateVals[1],10) - 1, parseInt(startDateVals[0],10));
        }

        if(this.isValidDate(startTime))
        {
            this.setDate(new Date(startTime));
        }
    }	
    this.initialized = true;
};

function getDaysInMonth(date)
{
    var tmpDate = new Date(date);
    if( ( new Date( tmpDate.setDate(28) ) ).getMonth() != ( new Date( tmpDate.setDate(29) ) ).getMonth() )
    {
        return 28;
    }
    else if( ( new Date( tmpDate.setDate(29) ) ).getMonth() != ( new Date( tmpDate.setDate(30) ) ).getMonth() )
    {
        return 29;
    }
    else if( ( new Date( tmpDate.setDate(30) ) ).getMonth() != ( new Date( tmpDate.setDate(31) ) ).getMonth() )
    {
        return 30;
    }
    else
    {
        return 31;
    }
}

function getAttributeByName(elem, name)
{
	name = name.toUpperCase();
	try
	{
		var value = elem.getAttribute(name);
		return ( (value) ? value : '' );
	}
	catch(e)
	{
		return '';
	}
	return '';
}

/* var calendar = new Calendar(); */ /* Запуск */
