if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.GregorianCalendar = 
{
	// Fields
    DatePartDay : 3,
    DatePartDayOfYear : 1,
    DatePartMonth : 2,
    DatePartYear : 0,
    DaysPer100Years : 36524,
    DaysPer400Years : 146097,
    DaysPer4Years : 1461,
    DaysPerYear : 365,
    DaysTo10000 : 3652059,
    DaysToMonth365 : [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ],
    DaysToMonth366 : [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 ],
    MaxMillis : 315537897600000,
    MillisPerDay : 86400000,
    MillisPerHour : 3600000,
    MillisPerMinute : 60000,
    MillisPerSecond : 1000,
    TicksPerDay : 864000000000,
    TicksPerHour : 36000000000,
    TicksPerMillisecond : 10000,
    TicksPerMinute : 600000000,
    TicksPerSecond : 10000000,
    MaxYear : 9999,
    
    GetDateFromArguments : function()
    {
		var year, month, date;			
		switch (arguments.length)
		{
			case 1:
				var date = arguments[0];
				if ("object" != typeof(date))
				{
					throw new Error("Unsupported input format");
				}
				
				if (date.getDate)
				{	
					// js Date object
					year = date.getFullYear();
					month = date.getMonth() + 1;
					date = date.getDate();
				}
				else if (3 == date.length)
				{
					// array: [year, month, date]
					year	= date[0];
					month	= date[1];
					date	= date[2];
				}
				else
				{
					throw new Error("Unsupported input format");
				}
				break;
				
			case 3:
				// year, month, date
				year	= arguments[0];
				month	= arguments[1];
				date	= arguments[2];
				break;
				
			default:
				throw new Error("Unsupported input format");
				break;
		}
		
		year = parseInt(year);
		if (isNaN(year))
		{
			throw new Error("Invalid YEAR");
		}
		
		month = parseInt(month);
		if (isNaN(month))
		{
			throw new Error("Invalid MONTH");
		}
		
		date = parseInt(date);
		if (isNaN(date))
		{
			throw new Error("Invalid DATE");
		}
		return [year, month, date];
    },
    
    DateToTicks : function()
    {
        var arr = this.GetDateFromArguments.apply(null, arguments);                
        
        var year	= arr[0];
        var month	= arr[1];
        var day		= arr[2];
        
        return (this.GetAbsoluteDate(year, month, day) * this.TicksPerDay);
    },
    
    TicksToDate : function(ticks)
    {
		var y = this.GetDatePart(ticks, 0);
		var m = this.GetDatePart(ticks, 2);
		var d = this.GetDatePart(ticks, 3);
		
		return [y, m, d];
    },
    
    GetAbsoluteDate : function(year, month, day)
    {
		if (year < 1 || year > this.MaxYear + 1)
			throw new Error("Year is out of range [1..9999].");
			
		if (month < 1 || month > 12)
			throw new Error("Month is out of range [1..12].");
    
		var isLeapYear = ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)));
		var arrDays = isLeapYear ? this.DaysToMonth366 : this.DaysToMonth365;
		var daysInMonth = arrDays[month] - arrDays[month - 1];
		
		if (day < 1 || day > daysInMonth)
			throw new Error("Day is out of range for the current month.");
			
		var fullYearsCount = year - 1;
		var num = fullYearsCount * this.DaysPerYear
					+ this.GetInt(fullYearsCount / 4)
					- this.GetInt(fullYearsCount / 100)
					+ this.GetInt(fullYearsCount / 400)
					+ arrDays[month - 1]
					+ day - 1;
					
		return num;
    },
    
    GetDatePart : function(ticks, part)
    {
        var num1 = this.GetInt(ticks / this.TicksPerDay);
        var num2 = this.GetInt(num1 / this.DaysPer400Years);
        num1 -= this.GetInt(num2 * this.DaysPer400Years);
        var num3 = this.GetInt(num1/this.DaysPer100Years);
        if (num3 == 4)
        {
            num3 = 3;
        }
        num1 -= this.GetInt(num3 * this.DaysPer100Years);
        var num4 = this.GetInt(num1 / this.DaysPer4Years);
        num1 -= this.GetInt(num4 * this.DaysPer4Years);
        var num5 = this.GetInt(num1 / this.DaysPerYear);
        if (num5 == 4)
        {
            num5 = 3;
        }
        if (part == 0)
        {
            return (((((num2 * 400) + (num3 * 100)) + (num4 * 4)) + num5) + 1);
        }
        num1 -= this.GetInt(num5 * 365);
        if (part == 1)
        {
            return (num1 + 1);
        }
        var flag1 = (num5 == 3) && ((num4 != 24) || (num3 == 3));
        var numArray1 = flag1 ? this.DaysToMonth366 : this.DaysToMonth365;
        var num6 = num1 >> 6;
        while (num1 >= numArray1[num6])
        {
            num6++;
        }
        if (part == 2)
        {
            return num6;
        }
        return ((num1 - numArray1[num6 - 1]) + 1);
    },
    
    GetDayOfMonth : function(date)
    {
        return (this.GetDatePart(this.DateToTicks(date), 3)+1);
    },
    
    GetDayOfWeek : function(date)
    {
        var DateClicks = this.DateToTicks(date);
        var DateDays = (DateClicks/864000000000) + 1;
        //return Math.round(DateDays%7);
        return this.GetInt(DateDays%7);
    },
    
    AddMonths : function(date, months)
    {
        var dateTicks = this.DateToTicks(date);
        var num1 = this.GetInt(this.GetDatePart(dateTicks, 0));
        var num2 = this.GetInt(this.GetDatePart(dateTicks, 2));
        var num3 = this.GetInt(this.GetDatePart(dateTicks, 3));
        var num4 = this.GetInt((num2 - 1) + months);
        if (num4 >= 0)
        {
            num2 = this.GetInt((num4 % 12) + 1);
            num1 += this.GetInt((num4 / 12));
        }
        else
        {
            num2 = this.GetInt(12 + ((num4 + 1) % 12));
            num1 += this.GetInt((num4 - 11) / 12);
        }
        var numArray1 = (((num1 % 4) == 0) && (((num1 % 100) != 0) || ((num1 % 400) == 0))) ? this.DaysToMonth366 : this.DaysToMonth365;
        var num5 = numArray1[num2] - numArray1[num2 - 1];
        if (num3 > num5)
        {
            num3 = num5;
        }
        var num6 = this.GetInt(this.DateToTicks(num1, num2, num3) + (dateTicks % 864000000000));
        //return new DateTime(num6);
        return ([this.GetDatePart(num6, 0)
					, this.GetDatePart(num6, 2)
					, this.GetDatePart(num6, 3)]);
    },
    
    AddYears : function(date, years)
    {
        return this.AddMonths(date, years * 12);
    },
    
    AddDays : function(date, days)
	{
		return this.Add(date, days, this.MillisPerDay);
	},
	
	Add : function(date, value, scale)
	{
		var dateTicks = this.DateToTicks(date);
		var valueTicks = this.GetInt(value * scale * this.TicksPerMillisecond);
		var ticks = this.GetInt(dateTicks + valueTicks);
		
		return this.TicksToDate(ticks);
	},
	    	
    GetWeekOfYear : function(date, rule, firstDayOfWeek)
    {
        switch (rule)
        {
            case RadCalendarUtils.FIRST_DAY:
            {
                return this.GetInt(this.GetFirstDayWeekOfYear(date, firstDayOfWeek));
            }
            case RadCalendarUtils.FIRST_FULL_WEEK:
            {
                return this.GetInt(this.InternalGetWeekOfYearFullDays(date, firstDayOfWeek, 7, 365));
            }
            case RadCalendarUtils.FIRST_FOUR_DAY_WEEK:
            {
                return this.GetInt(this.InternalGetWeekOfYearFullDays(date, firstDayOfWeek, 4, 365));
            }
        }
    },
    
    InternalGetWeekOfYearFullDays : function(time, firstDayOfWeek, fullDays, daysOfMinYearMinusOne)
    {
        var num4 = this.GetDayOfYear(time) - 1;
        var num1 = ((this.GetDayOfWeek(time)) - (num4 % 7));
        var num2 = ((firstDayOfWeek - num1) + 14) % 7;
        if ((num2 != 0) && (num2 >= fullDays))
        {
            num2 -= 7;
        }
        var num3 = num4 - num2;
        if (num3 >= 0)
        {
            return ((num3 / 7) + 1);
        }
        var num5 = this.GetYear(time);
        num4 = this.GetDaysInYear(num5 - 1);

        num1 -= (num4 % 7);
        num2 = ((firstDayOfWeek - num1) + 14) % 7;
        if ((num2 != 0) && (num2 >= fullDays))
        {
            num2 -= 7;
        }
        num3 = num4 - num2;
        return ((num3 / 7) + 1);
    },
    
    GetFirstDayWeekOfYear : function(date, firstDayOfWeek)
    {
        var num1 = this.GetDayOfYear(date) - 1;
        var num2 = (this.GetDayOfWeek(date)) - (num1 % 7);
        var num3 = ((num2 - firstDayOfWeek) + 14) % 7;
        return (((num1 + num3) / 7) + 1);
    },
    
    GetLeapMonth : function(year)
    {
        var year = this.GetGregorianYear(year);
        return 0;
    },
    
    GetMonth : function(date)
    {
        return this.GetDatePart(this.DateToTicks(date), 2);
    },
    
    GetMonthsInYear : function(year)
    {
        var year = this.GetGregorianYear(year);
        return 12;
    },
    
    GetDaysInMonth : function(year, month)
    {
        var year = this.GetGregorianYear(year);
        var numArray1 = (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0))) ? this.DaysToMonth366 : this.DaysToMonth365;
        return (numArray1[month] - numArray1[month - 1]);
    },
    
    GetDaysInYear : function(year)
    {
        var year = this.GetGregorianYear(year);
        if (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)))
        {
            return 366;
        }
        return 365;
    },
    
    GetDayOfYear : function(date)
    {
        return this.GetInt(this.GetDatePart(this.DateToTicks(date), 1));
    },
    
    GetGregorianYear : function(year)
    {
        return year;
    },
    
    GetYear : function(date)
    {
        var num1 = this.DateToTicks(date);
        var num2 = this.GetDatePart(num1, 0);
        return (num2);
    },
    
    IsLeapDay : function(date)
    {
        var year = date.getFullYear();
        var month = date.getMonth();
        var day = date.getDate();
        
        if (this.IsLeapYear(date) && ((month == 2) && (day == 29)))
        {
            return true;
        }
        return false;
    },
    
    IsLeapMonth : function(date)
    {
        var year = date.getFullYear();
        var month = date.getMonth();
        if(this.IsLeapYear(date))
        {
            if (month == 2)
            {
                return true;
            }
        }
        return false;
    },
    
    IsLeapYear : function(date)
    {
        var year = date.getFullYear();
        if ((year % 4) != 0)
        {
            return false;
        }
        if ((year % 100) == 0)
        {
            return ((year % 400) == 0);
        }
        return true;
    },
    
    GetInt : function(value)
    {
		if (value > 0)
			return Math.floor(value);
		else
			return Math.ceil(value);
    }
};;if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.DateTimeFormatInfo = function(data)
{
	this.DayNames							= data[0];
	this.AbbreviatedDayNames				= data[1];
	this.MonthNames							= data[2];
	this.AbbreviatedMonthNames				= data[3];
	this.FullDateTimePattern				= data[4];
	this.LongDatePattern					= data[5];
	this.LongTimePattern					= data[6];
	this.MonthDayPattern					= data[7];
	this.RFC1123Pattern						= data[8];
	this.ShortDatePattern					= data[9];
	this.ShortTimePattern					= data[10];
	this.SortableDateTimePattern			= data[11];
	this.UniversalSortableDateTimePattern	= data[12];
	this.YearMonthPattern					= data[13];
	this.AMDesignator						= data[14];
	this.PMDesignator						= data[15];
	this.DateSeparator						= data[16];
	this.TimeSeparator						= data[17];
	this.FirstDayOfWeek                     = data[18];
	this.CalendarType					    = 0;
	this.CalendarWeekRule					= 0;
	this.Calendar						    = null;
}

RadCalendarNamespace.DateTimeFormatInfo.prototype.LeadZero = function(x)
{
    return (x < 0 || x > 9 ? "" : "0") + x;
}
// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | MMMM (full)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name - dddd)   | E (abbr - ddd)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | tt (2 digits)      | t (1 or 2 digits)
RadCalendarNamespace.DateTimeFormatInfo.prototype.FormatDate = function(date,format)
{
	format = format+"";
	format = format.replace(/%/ig, "");
	
	var result="";
	var i_format=0;
	var c="";
	var token="";
	
	var y = "" + date[0];
	var M = date[1];
	var d = date[2];	
	var E = this.Calendar.GetDayOfWeek(date) ; //date.getDay();
	var H = 0;	//date.getHours();
	var m = 0;	//date.getMinutes();
	var s = 0;	//date.getSeconds();
	
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4)
	{
	    y=""+(y-0+1900);
	}
	var WithoutCentury = y.substring(2,4);
	var IslessThan10 = 0 + WithoutCentury;
	if (IslessThan10<0) 
	{
	    value["y"]=""+ WithoutCentury.substring(1,2);
	}
	else
	{
	    value["y"]=""+ WithoutCentury;
	}
	value["yyyy"]=y;
	value["yy"]=WithoutCentury;
	value["M"]=M;
	value["MM"]=this.LeadZero(M);
	value["MMM"]= this.AbbreviatedMonthNames[M-1];
	value["MMMM"]= this.MonthNames[M-1];
	value["d"]=d;
	value["dd"]=this.LeadZero(d);
	value["dddd"]= this.DayNames[E];
	value["ddd"]= this.AbbreviatedDayNames[E];
	value["H"]=H;
	value["HH"]=this.LeadZero(H);
	if (H==0)
	{
	    value["h"]=12;
	}
	else if (H>12)
	{
	    value["h"]=H-12;
	}
	else 
	{
	    value["h"]=H;
	}
	value["hh"]=this.LeadZero(value["h"]);
	if (H > 11) 
	{ 
	    value["tt"]="PM";
	    value["t"]="P"; 
	}
	else 
	{ 
	    value["tt"]="AM"; 
	    value["t"]="A";
	}
	value["m"]=m;
	value["mm"]=this.LeadZero(m);
	value["s"]=s;
	value["ss"]=this.LeadZero(s);
	while (i_format < format.length) 
	{
		c = format.charAt(i_format);
		token = "";
		
		if (format.charAt(i_format) == "'")
		{
			//skip the opening ' marker
			i_format++;
		
			while((format.charAt(i_format) != "'"))
			{
				token += format.charAt(i_format);
				i_format++;
			}
			
			//skip the closing ' marker
			i_format++;
			
			result += token;
			continue;
		}
		
		while ((format.charAt(i_format) == c) && (i_format < format.length)) 
		{
			token += format.charAt(i_format++);
		}
		
		if (value[token] != null) 
		{ 
		    result += value[token]; 
		}
		else
		{ 
		    result += token; 
		}
	}
	return result;
};if (typeof window.RadControlsNamespace == "undefined")
{
	window.RadControlsNamespace = {};
}

if (
	typeof(window.RadControlsNamespace.EventMixin) == "undefined" ||
	typeof(window.RadControlsNamespace.EventMixin.Version) == null ||
	window.RadControlsNamespace.EventMixin.Version < 2
	)
{	
	
	RadControlsNamespace.EventMixin = 
	{
		Version : 2, // Change the version when make changes. Change the value in the IF also

		Initialize : function (obj)
		{
	
			obj._listeners = {};
			obj._eventsEnabled = true;
			obj.AttachEvent = this.AttachEvent;
		    
			obj.DetachEvent = this.DetachEvent;
			obj.RaiseEvent = this.RaiseEvent;
		    
			obj.EnableEvents = this.EnableEvents;
			obj.DisableEvents = this.DisableEvents;
			
			obj.DisposeEventHandlers = this.DisposeEventHandlers;
	
		},
	
		DisableEvents : function ()
		{
			this._eventsEnabled = false;
		},
	
		EnableEvents : function ()
		{
			this._eventsEnabled = true;
		},
	
		AttachEvent : function (eventName, handler)
		{
			if (!this._listeners[eventName]) 
			{
				this._listeners[eventName] = [];
			}
	
			this._listeners[eventName][this._listeners[eventName].length] = (RadControlsNamespace.EventMixin.ResolveFunction(handler));
		},
	
	
		DetachEvent : function (eventName, handler)
		{
			var listeners = this._listeners[eventName];
			if (!listeners) 
			{
				return false;
			}
		    
			var funcHandler = RadControlsNamespace.EventMixin.ResolveFunction(handler);
		    
			for (var i = 0; i < listeners.length; i ++)
			{
				if (funcHandler == listeners[i])
				{
					listeners.splice(i, 1);
					return true;
				}
			}
	
			return false;
		},
		
		DisposeEventHandlers : function()
		{
            for (var eventName in this._listeners)
            {
                var listeners = null;
                if (this._listeners.hasOwnProperty(eventName))
                {
                    listeners = this._listeners[eventName];
                    for (var i = 0; i < listeners.length; i++)
			        {
				        listeners[i] = null;
			        }
			        
			        listeners = null;
                }
            }
		},
	
		ResolveFunction : function (func)
		{
			if (typeof(func) == "function")
			{
				return func;
			}
			else if (typeof(window[func]) == "function")
			{
				return window[func];
			}
			else
			{
				return new Function("var Sender = arguments[0]; var Arguments = arguments[1];" + func);
			}
		},
	
	
		RaiseEvent : function (eventName, eventArgs)
		{
			if (!this._eventsEnabled)
			{
				return true;
			}
			var outcome = true;
		    
			if (this[eventName])
			{
		        
				var eventResult = RadControlsNamespace.EventMixin.ResolveFunction(this[eventName])(this, eventArgs);
				if (typeof(eventResult) == "undefined")
				{
					eventResult = true;
				}
				outcome = outcome && eventResult;        
			}
		    
			if (!this._listeners[eventName]) return outcome;
		    
			for (var i = 0; i < this._listeners[eventName].length; i ++)
			{
				var handler = this._listeners[eventName][i];
				var eventResult = handler(this, eventArgs);
				if (typeof(eventResult) == "undefined")
				{
					eventResult = true;
				}
				outcome = outcome && eventResult;
			}
		    
			return outcome;
		}
	}
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.MonthYearFastNavigation = function(monthNames
	, minYear
	, maxYear
	, skin
	, calendarID
	, monthYearNavigationSettings )
{
	this.MonthNames = monthNames;
	this.MinYear = minYear;
	this.MaxYear = maxYear;
	this.Skin = skin;
	this.CalendarID = calendarID;
	
	this.TodayButtonCaption = monthYearNavigationSettings[0];
	this.OkButtonCaption = monthYearNavigationSettings[1];
	this.CancelButtonCaption = monthYearNavigationSettings[2];
	this.DateIsOutOfRangeMessage = monthYearNavigationSettings[3];
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.CreateLayout = function(style)
{
	var thisObject = this;
	var currMonth = this.Month;

	var table = document.createElement("TABLE");
	table.id = 	this.CalendarID + "_FastNavPopup";

    table.className = style[1];    
    table.style.cssText = style[0];    

	var monthNames = this.MonthNames;
	var monthNamesCount = monthNames.length;
	if (!monthNames[12])
	{
		monthNamesCount--;
	}
	
	var rowsCount = Math.ceil(monthNamesCount / 2.0);
	table.YearRowsCount = rowsCount - 1;
	
	var monthIndex = 0;
	var row, cell;
	
	this.YearCells = [];
	this.MonthCells = [];
	
	for (var i = 0; i < rowsCount; i++)
	{
		row = table.insertRow(table.rows.length);
		
		// col 1 - month
		cell = this.AddMonthCell(row, monthIndex++);
		if (null != cell.Month)
		{
			this.MonthCells[this.MonthCells.length] = cell;
		}
		
		// col 2 - month
		cell = this.AddMonthCell(row, monthIndex++);	
		if (null != cell.Month)
		{
			this.MonthCells[this.MonthCells.length] = cell;
		}
		
		// col 3 - year | <<
		cell = row.insertCell(row.cells.length);
		this.FastNavPrevYears = cell;
		cell.unselectable = "on";
		if (i < (rowsCount - 1))
		{
			this.YearCells[this.YearCells.length] = cell;
			
			cell.innerHTML = "&nbsp;"		
			cell.onclick = function()
			{
				thisObject.SelectYear(this.Year);
			};
		}
		else
		{
			cell.id = "RadCalendar_FastNav_PrevYears";
			cell.innerHTML = "&lt;&lt;";
			if(thisObject.StartYear < thisObject.MinYear[0])
			{
			      cell.style.color = "GrayText";
			}
			else
			{
			    cell.onclick = function()
			    {
			        thisObject.ScrollYears(-10);				
			    };
			}
		}
		
		// col 4 - year | >>
		cell = row.insertCell(row.cells.length);
		this.FastNavNextYears = cell;
		cell.unselectable = "on";
		if (i < (rowsCount - 1))
		{
			this.YearCells[this.YearCells.length] = cell;
			
			cell.innerHTML = "&nbsp;"
			cell.onclick = function()
			{
				thisObject.SelectYear(this.Year);
			};
		}
		else
		{
			cell.id = "RadCalendar_FastNav_NextYears";
			cell.innerHTML = "&gt;&gt;";
			var endYear = thisObject.StartYear + 10;
			if( endYear > thisObject.MaxYear[0])
			{
			      cell.style.color = "GrayText";						            
			}
			else
			{
			    cell.onclick = function()
			    {			    	
			        thisObject.ScrollYears(10);				
			    };	
			}
		}
	}
	
	row = table.insertRow(table.rows.length);
	cell = row.insertCell(row.cells.length);
	cell.className = "bottom_" + this.Skin;
	cell.colSpan = 4;
	cell.noWrap = true;
	
	this.CreateButton("RadCalendar_FastNav_TodayButton", cell, this.TodayButtonCaption, RadCalendarUtils.AttachMethod(this.OnToday, this));
	cell.appendChild(document.createTextNode("   "));	
	this.CreateButton("RadCalendar_FastNav_OkButton", cell, this.OkButtonCaption, RadCalendarUtils.AttachMethod(this.OnOK, this) );	
	cell.appendChild(document.createTextNode(" "));	
	this.CreateButton("RadCalendar_FastNav_CancelButton", cell, this.CancelButtonCaption, RadCalendarUtils.AttachMethod(this.OnCancel, this));
		
	return table;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.CreateButton = function(elementId, parentNode, text, onclickFunc)
{
	var btn = document.createElement("INPUT");
	btn.id = elementId;
	btn.type = "button";
	btn.value = text;
	if ("function" == typeof(onclickFunc))
	{
		btn.onclick = onclickFunc;
	}
	
	parentNode.appendChild(btn);	
	return btn;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.FillYears = function()
{
	var startYear = this.StartYear;
	var yearCells = this.YearCells;
	
	var yearsLookup = [];
	
	var cell;
	var rowsCount = yearCells.length / 2
	for (var i = 0; i < rowsCount; i++)
	{	    
		cell = yearCells[i*2];
		this.SelectCell(cell, false);
		cell.id = "RadCalendar_FastNav_" + startYear.toString();
		cell.innerHTML = startYear;
		cell.Year = startYear;
		if(cell.Year < this.MinYear[0] || cell.Year > this.MaxYear[0])
		{   
		    cell.onclick = null;
		    cell.style.color = "GrayText";
		}
		else
		{		    
		    cell.style.color = "";		 
	        if(cell.onclick == null)
	        {
	            var thisObject = this;
	            cell.onclick = function() { thisObject.SelectYear(this.Year);}
	        }		    
		}
		yearsLookup[startYear] = cell;		
		
		cell = yearCells[i*2 + 1];
		this.SelectCell(cell, false);
		cell.id = "RadCalendar_FastNav_" + (startYear + rowsCount).toString();
		cell.innerHTML = startYear + rowsCount;
		cell.Year = startYear + rowsCount;		
		if(cell.Year < this.MinYear[0] || cell.Year > this.MaxYear[0])
		{
		    cell.onclick = null;
		    cell.style.color = "GrayText";		    
	    }
	    else
	    {
	        cell.style.color = "";		 
	        if(cell.onclick == null)
	        {
	            var thisObject = this;
	            cell.onclick = function() { thisObject.SelectYear(this.Year);}
	        }		    
	    }
		yearsLookup[startYear + rowsCount] = cell;
		
		startYear++;
	}
	
	this.YearsLookup = yearsLookup;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.SelectCell = function(cell, selected)
{
	if (cell)
	{
		cell.className = (false == selected ? "" : "selected_" + this.Skin);
	}
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.SelectYear = function(year)
{
	var yearCell = this.YearsLookup[year];
	this.Year = year;
	
	this.SelectCell(this.SelectedYearCell, false);
	this.SelectCell(yearCell, true);
	
	this.SelectedYearCell = yearCell;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.SelectMonth = function(month)
{
	var monthCell = this.MonthCells[month];
	this.Month = month;
	
	this.SelectCell(this.SelectedMonthCell, false);
	this.SelectCell(monthCell, true);
	
	this.SelectedMonthCell = monthCell;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.ScrollYears = function(step)
{
    this.StartYear += step;
    this.FillYears();    
    this.SetNavCells();    
};


RadCalendarNamespace.MonthYearFastNavigation.prototype.SetNavCells = function()
{
    var endYear = this.StartYear + 10;
    var cellPrevNav = this.FastNavPrevYears;
    var cellNextNav = this.FastNavNextYears;
    var thisObj = this;
    if(this.StartYear < this.MinYear[0])
    {
        cellPrevNav.style.color = "GrayText";
        cellPrevNav.onclick = null;
    }
    else
    {        
        cellPrevNav.style.color = "";	
        if(cellPrevNav.onclick == null)            
            cellPrevNav.onclick = function() {thisObj.ScrollYears(-10);}
    }
    
    if(endYear > this.MaxYear[0])
    {	          
        cellNextNav.style.color = "GrayText";
        cellNextNav.onclick = null;
    }
    else
    {
        cellNextNav.style.color = "";
        if(cellNextNav.onclick == null)
            cellNextNav.onclick = function () { thisObj.ScrollYears(10); }
    }
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.AddMonthCell = function(row, monthIndex)
{
	var cell = row.insertCell(row.cells.length);		
	cell.innerHTML = "&nbsp;"
	cell.unselectable = "on";
	
	var month = this.MonthNames[monthIndex];
	if (month)
	{		
		cell.id = "RadCalendar_FastNav_" + month;
		cell.innerHTML = month;
		cell.Month = monthIndex;
		
		var thisObject = this;
		cell.onclick = function(e)
		{
			thisObject.SelectMonth(this.Month);
		};
	}	
	return cell;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.GetYear = function()
{
	return this.Year;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.GetMonth = function()
{
	return this.Month;
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.Show = function(popup, x, y, month, year, exitFunc, style)
{
	if (!popup)
		return;
    		
	this.Popup = popup;
	this.StartYear = year - 4;
	
	var table = this.DomElement;
	if (!table)
	{
		table = this.CreateLayout(style);
		this.DomElement = table;
	}
	else
	{
        this.SetNavCells();
	}
		
	this.FillYears();
		
	this.SelectYear(year);
	this.SelectMonth(month - 1);	
	
	this.ExitFunc = exitFunc;	
	
	popup.Show(x, y, table, RadCalendarUtils.AttachMethod(this.OnExit, this));	
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.OnExit = function()
{
	if ("function" == typeof(this.ExitFunc))
	{
		this.ExitFunc(this.Year, this.Month, this.Date);
		this.Date = null;
	}
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.OnToday = function(e)
{
	var today = new Date();
	
	this.Date = today.getDate();
	this.Month = today.getMonth();	// + 1;
	this.Year = today.getFullYear();
	
	this.Popup.Hide(true);
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.OnOK = function(e)
{
	this.Popup.Hide(true);
};

RadCalendarNamespace.MonthYearFastNavigation.prototype.OnCancel = function(e)
{
	this.Popup.Hide();
};;if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.Popup = function()
{
    this.DomElement = null;
    this.ExcludeFromHiding = [];
};

RadCalendarNamespace.Popup.zIndex = 50000;

RadCalendarNamespace.Popup.prototype.CreateContainer = function()
{
	var div = document.createElement("DIV");
	var styleObj = RadHelperUtils.GetStyleObj(div);
	styleObj.position = "absolute";
	
	if (navigator.userAgent.match(/Safari/))
	{
	    styleObj.visibility = "hidden";
	    styleObj.left = "-1000px";
	}
	else
	{
	    styleObj.display = "none";
	}
		
	styleObj.border = "0";
	styleObj.zIndex = RadCalendarNamespace.Popup.zIndex;
	RadCalendarNamespace.Popup.zIndex += 2;
	
	div.onclick = function(e)
	{
		if (!e)
		    e = window.event;
		e.returnValue = false;
		e.cancelBubble = true;
		if (e.stopPropagation)
			e.stopPropagation();
		return false;		
	};
	
	document.body.insertBefore(div, document.body.firstChild);
	return div;
};

/**
* Opera re-evals all script blocks once their container is appended to another parent element.
* We don't want that as it creates many RadCalendar objects.
*/
RadCalendarNamespace.Popup.prototype.RemoveScriptsOnOpera = function(innerElement)
{
	if (window.opera)
	{
		var scripts = innerElement.getElementsByTagName("*");
		for (var i = 0; i < scripts.length; i++)
		{
			var script = scripts[i];
			if (script.tagName != null && script.tagName.toLowerCase() == "script")
			{
				script.parentNode.removeChild(script);
			}
		}
	}
}

RadCalendarNamespace.Popup.prototype.Show = function(x, y, innerElement, exitFunc)
{
	if (this.IsVisible())
	{
		this.Hide();
	}

	this.ExitFunc = ("function" == typeof(exitFunc) ? exitFunc : null);
	
	var div = this.DomElement;
	if (!div)
	{
		div = this.CreateContainer();
		this.DomElement = div;
	}

	if (innerElement)
	{
		div.innerHTML = "";	
		
		if (innerElement.nextSibling)
		{
			this.Sibling = innerElement.nextSibling;
		}
		this.Parent = innerElement.parentNode;
		
		this.RemoveScriptsOnOpera(innerElement);
		div.appendChild(innerElement);
		
		if (navigator.userAgent.match(/Safari/) && innerElement.style.visibility == "hidden")
		{
		    innerElement.style.visibility = "visible";
		    innerElement.style.position = "";
		    innerElement.style.left = "";
		}
		else if (innerElement.style.display == "none")
		{
			innerElement.style.display = "";
	    }
	}
	
    var styleObj = RadHelperUtils.GetStyleObj(div);
	styleObj.left = parseInt(x) + "px";
	styleObj.top = parseInt(y) + "px";
	
	if (navigator.userAgent.match(/Safari/))
	{
	    styleObj.visibility = "visible";
	}
	else
	{
	    styleObj.display = "";
	}
	
	

	//IFRAME code
	RadHelperUtils.ProcessIframe(div, true);
	
	this.OnClickFunc = RadCalendarUtils.AttachMethod(this.OnClick, this);
	this.OnKeyPressFunc = RadCalendarUtils.AttachMethod(this.OnKeyPress, this);
	
	var thisPopup = this;
	window.setTimeout(function()
		{
			RadHelperUtils.AttachEventListener(document, "click", thisPopup.OnClickFunc);
			RadHelperUtils.AttachEventListener(document, "keypress", thisPopup.OnKeyPressFunc);
		}, 300);
};

RadCalendarNamespace.Popup.prototype.Hide = function(updateData)
{
	var div = this.DomElement;
	var styleObj = RadHelperUtils.GetStyleObj(div);
	
	if (div)
	{
		if (navigator.userAgent.match(/Safari/))
		{
		    styleObj.visibility = "hidden";
		    styleObj.position = "absolute";
		    styleObj.left = "-1000px";
		}
		else
		{
		    styleObj.display = "none";
		}
		
		styleObj = null;
		
		if (div.childNodes.length != 0)
        {
            if (navigator.userAgent.match(/Safari/))
            {
                div.childNodes[0].style.visibility = "hidden";
		        div.childNodes[0].style.position = "absolute";
		        div.childNodes[0].style.left = "-1000px";
            }
            else
            {
                div.childNodes[0].style.display = "none";
            }
        }
        
		var innerElement = div.childNodes[0];
		if (innerElement != null)
		{
			div.removeChild(innerElement);		
			
			if (this.Parent != null || this.Sibling != null)
			{
				if (this.Sibling != null)
				{
					var parentElement = this.Sibling.parentNode;
					if (parentElement != null)
						parentElement.insertBefore(innerElement, this.Sibling);
				}
				else
				{
					this.Parent.appendChild(innerElement);
				}
			}
			
			if (navigator.userAgent.match(/Safari/))
			{
			    RadHelperUtils.GetStyleObj(innerElement).visibility = "hidden";
		        RadHelperUtils.GetStyleObj(innerElement).position = "absolute";
		        RadHelperUtils.GetStyleObj(innerElement).left = "-1000px";		    
			}
			else
			{
			    RadHelperUtils.GetStyleObj(innerElement).display = "none";
			}
		}
		//IFRAME code
		RadHelperUtils.ProcessIframe(div, false);
	}
	
	if (this.OnClickFunc != null)
	{
	    RadHelperUtils.DetachEventListener(document, "click", this.OnClickFunc);
	    this.OnClickFunc = null;
	}
	if (this.OnKeyPressFunc != null)
	{
        RadHelperUtils.DetachEventListener(document, "keydown", this.OnKeyPressFunc);
        this.OnKeyPressFunc = null;
    }
	
	if (updateData && this.ExitFunc)
	{	
		this.ExitFunc();
	}
};

RadCalendarNamespace.Popup.prototype.IsVisible = function()
{
	var div = this.DomElement;
	var styleObj = RadHelperUtils.GetStyleObj(div);
	if (div)
	{
		if (navigator.userAgent.match(/Safari/))
		    return (styleObj.visibility != "hidden");
		    
		return (styleObj.display != "none");
	}
	return false;
};


RadCalendarNamespace.Popup.prototype.IsChildOf = function (node, parentNode)
{
	while (node.parentNode)
	{
		if (node.parentNode == parentNode)
		{
			return true;
		}
		node = node.parentNode;
	}
	return false;
};


RadCalendarNamespace.Popup.prototype.ShouldHide = function(e)
{
	var target = e.target;
	if (target == null)
		target = e.srcElement;
		
	for (var i = 0; i < this.ExcludeFromHiding.length; i++)
	{
		if (this.ExcludeFromHiding[i] == target)
			return false;
		if (this.IsChildOf(target, this.ExcludeFromHiding[i]))
			return false;
	}
	return true;
}

RadCalendarNamespace.Popup.prototype.OnKeyPress = function(e)
{
	if (!e)
	    e = window.event;
	    
	if (e.keyCode == 27)
	{
		this.Hide();
	}
};

RadCalendarNamespace.Popup.prototype.OnClick = function(e)
{	
	if (!e)
	    e = window.event;
	
	if (this.ShouldHide(e))
	{
		this.Hide();
	}
};

//HACK: Popup does not need to be inside RadCalendar, but customers are using it.  
//Keep the original name
if (typeof(window["RadCalendar"]) != "undefined")
{
	RadCalendar.Popup = RadCalendarNamespace.Popup;
};/* Obfuscation Map Terms to be excluded - needs to be done as the script is 
to be used globally.*/
/*
 RadBrowserUtils
 Version
 IsInitialized
 IsOsWindows
 IsOsLinux
 IsOsUnix
 IsOsMac
 IsUnknownOS
 IsNetscape4
 IsNetscape6
 IsNetscape6Plus
 IsNetscape7
 IsNetscape8
 IsMozilla
 IsFirefox
 IsSafari
 IsIE
 IsIE5Mac
 IsIE4Mac
 IsIE5Win
 IsIE55Win
 IsIE6Win
 IsIE4Win
 IsOpera
 IsOpera4
 IsOpera5
 IsOpera6
 IsOpera7
 IsOpera8
 IsKonqueror
 IsOmniWeb
 IsCamino 
 IsUnknownBrowser
 UpLevelDom
 AllCollection
 Layers
 Focus
 StandardMode
 HasImagesArray
 HasAnchorsArray 
 DocumentClear
 AppendChild
 InnerWidth
 HasComputedStyle
 HasCurrentStyle 
 HasFilters
 HasStatus
 Name
 Codename
 BrowserVersion
 Platform
 JavaEnabled 
 ScreenWidth
 ScreenHeight
 AgentString
 Init
 DebugBrowser
 DebugOS
 DebugFeatures
*/

if (typeof(RadBrowserUtils)== "undefined")
{

    // class definition BEGIN
    var RadBrowserUtils = 
    {
        // fields region
        Version: "1.0.0",
        IsInitialized : false,
        // OS properties
        IsOsWindows : false,
        IsOsLinux : false,
        IsOsUnix : false,
        IsOsMac : false,
        IsUnknownOS : false,
        // Browser types
        IsNetscape4 : false,
        IsNetscape6 : false,
        IsNetscape6Plus : false,
        IsNetscape7 : false,
        IsNetscape8 : false,
        IsMozilla : false,
        IsFirefox : false,
        IsSafari : false,
        IsIE : false,
        IsIEMac : false,
        IsIE5Mac : false,
        IsIE4Mac : false,
        IsIE5Win : false,
        IsIE55Win : false,
        IsIE6Win : false,
        IsIE4Win : false,
        IsOpera : false,
        IsOpera4 : false,
        IsOpera5 : false,
        IsOpera6 : false,
        IsOpera7 : false,
        IsOpera8 : false,
        IsKonqueror : false,
        IsOmniWeb : false,
        IsCamino : false,
        IsUnknownBrowser : false,
        // DHTML features
        UpLevelDom : false,
        AllCollection : false,
        Layers : false,
        Focus : false,
        StandardMode : false,
        HasImagesArray : false,
        HasAnchorsArray : false,
        DocumentClear : false,
        AppendChild : false,
        InnerWidth : false,
        HasComputedStyle : false,
        HasCurrentStyle : false,
        HasFilters : false,
        HasStatus : false,
        // browser info - internal use only
        Name : "",
        Codename : "",
        BrowserVersion : "",
        Platform : "",
        JavaEnabled : false,
        ScreenWidth : 0,
        ScreenHeight : 0,
        AgentString : "",
        // methods region
        
        // this is the public initialization method that sets up the required
        // detected variables
        Init : function()
        {
            if(window.navigator)
            {
	            this.AgentString = navigator.userAgent.toLowerCase();
	            this.Name = navigator.appName;
                this.Codename = navigator.appCodeName;
                this.BrowserVersion = navigator.appVersion.substring(0,4);
                this.Platform = navigator.platform;
                this.JavaEnabled = navigator.javaEnabled();
                this.ScreenWidth = screen.width;
                this.ScreenHeight = screen.height;
            }
            // we call the init functions here
            this.InitOs();
            this.InitFeatures();
            this.InitBrowser();
            this.IsInitialized = true;
        },
        CancelIe : function()
        {
            this.IsIE = this.IsIE6Win = this.IsIE55Win = this.IsIE5Win = this.IsIE4Win = this.IsIEMac = this.IsIE5Mac = this.IsIE4Mac = false;
        },
        CancelOpera : function()
        {
            this.IsOpera4 = this.IsOpera5 = this.IsOpera6 = this.IsOpera7 = false;
        },
        CancelMozilla : function()
        {
            this.IsFirefox = this.IsMozilla = this.IsNetscape7 = this.IsNetscape6Plus = this.IsNetscape6 = this.IsNetscape4 = false;
        },
        InitOs : function()
        {
            if((this.AgentString.indexOf("win") != -1))
            {
                this.IsOsWindows = true;
            }
            else if((this.AgentString.indexOf("mac") != -1)||(navigator.appVersion.indexOf("mac") != -1))
            {
                this.IsOsMac = true;
            }
            else if((this.AgentString.indexOf("linux") != -1))
            {
                this.IsOsLinux = true;
            }
            else if((this.AgentString.indexOf("x11") != -1))
            {
                this.IsOsUnix = true;
            }
            else
            {
                this.IsUnknownBrowser = true;
            }
        },
        InitFeatures : function()
        {
            if((document.getElementById && document.createElement))// || (document.getElementById && document.createElement && document.all)
            {
                this.UpLevelDom = true;
            }
            if(document.all)
            {
                this.AllCollection = true;
            }
            if(document.layers)
            {
                this.Layers = true;
            }
            if(window.focus)
            {
                this.Focus = true;
            }
            if(document.compatMode && document.compatMode == "CSS1Compat")
	        {
	            this.StandardMode = true;
	        }
            if(document.images)
            {
                this.HasImagesArray = true;
            }
            if(document.anchors)
            {
                this.HasAnchorsArray = true;
            }
            if(document.clear)
            {
                this.DocumentClear = true;
            }
            if(document.appendChild)
            {
                this.AppendChild = true;
            }
            if(window.innerWidth)
            {
                this.InnerWidth = true;
            }
            if(window.getComputedStyle)
            {
                this.HasComputedStyle = true;
            }
            if(document.documentElement && document.documentElement.currentStyle)
            {
                this.HasCurrentStyle = true;
            }
            else if(document.body && document.body.currentStyle)
            {
                this.HasCurrentStyle = true;
            }
            
            try
            {
                if(document.body && document.body.filters)
                {
                    this.HasFilters = true;
                }
            }
            catch(e)
            {
            }
            
            if (typeof(window.status) != "undefined") 
            {
                this.HasStatus = true;
            }
        },
        InitBrowser : function()
        {
	        if(this.AllCollection || (navigator.appName == "Microsoft Internet Explorer"))
	        {
	            this.IsIE = true;
	            if (this.IsOsWindows)
	            {
		            if(this.UpLevelDom)
		            {
			            if ((navigator.appVersion.indexOf("MSIE 6") > 0)||(document.getElementById && document.compatMode))
			            {
				            this.IsIE6Win = true;
			            }
			            else if ((navigator.appVersion.indexOf("MSIE 5.5") > 0)&& document.getElementById && !document.compatMode)
			            {
				            this.IsIE55Win = true;
				            this.IsIE6Win = true;
			            }
			            else if (document.getElementById && !document.compatMode && typeof(window.opera)=="undefined")
			            {
				            this.IsIE5Win = true;
			            }
		            }
		            else
		            {
			            this.IsIE4Win = true;
		            }
	            }
	            else if (this.IsOsMac)
	            {
		            this.IsIEMac = true;
		            if(this.UpLevelDom)
		            {
			            this.IsIE5Mac = true;
		            }
		            else
		            {
			            this.IsIE4Mac = true;
		            }
	            }
	        }
	        if (this.AgentString.indexOf('opera') != -1 && typeof(window.opera)== "undefined")
	        {
		        this.IsOpera4 = true;
		        this.IsOpera = true;
		        this.CancelIe();
	        }
	        else if (typeof(window.opera)!="undefined" && !typeof(window.print)=="undefined")
	        {
		        this.IsOpera5 = true;
		        this.IsOpera = true;
		        this.CancelIe();
	        }
	        else if (typeof(window.opera)!="undefined" && typeof(window.print)!="undefined" && typeof(document.childNodes)=="undefined" )
	        {
		        this.IsOpera6 = true;
		        this.IsOpera = true;
		        this.CancelIe();
	        }
	        else if (typeof(window.opera)!="undefined" && typeof(document.childNodes)!="undefined" )
	        {
		        this.IsOpera7 = true;
		        this.IsOpera = true;
		        this.CancelIe();
	        }
	        if (this.IsOpera7 && (this.AgentString.indexOf('8.') != -1))
	        {
                this.CancelIe();
	            this.CancelOpera();
		        this.IsOpera8 = true;
		        this.IsOpera = true;
	        }
	        if (this.AgentString.indexOf( "firefox/" ) != -1 )
	        {
	            this.CancelIe();
	            this.CancelOpera();
	            this.IsMozilla = true;
		        this.IsFirefox = true;
	        }
	        else if (navigator.product == "Gecko" && window.find)
	        {   //Netscape 6+, Mozilla and other Gecko
		        this.CancelIe();
	            this.CancelOpera();
		        this.IsMozilla = true;
	        }
	        if (navigator.vendor && navigator.vendor.indexOf("Netscape") != -1 && navigator.product == "Gecko" && window.find)
	        {   //Netscape 6+, Mozilla and other Gecko
		        this.CancelIe();
	            this.CancelOpera();
		        this.IsNetscape6Plus = true;
		        this.IsMozilla = true;
	        }
	        if (navigator.product == 'Gecko' && !window.find)
	        {   //Netscape 6, Mozilla 0.9- and reduced Gecko 
	            this.CancelIe();
	            this.CancelOpera();
		        this.IsNetscape6 = true;
	        }
	        if ((navigator.vendor && navigator.vendor.indexOf("Netscape") != -1 && navigator.product == 'Gecko' && window.find)||(this.AgentString.indexOf("netscape/7") != -1||this.AgentString.indexOf("netscape7") != -1))
	        {   //Netscape 7+, Mozilla 1+ and advanced Gecko
	            this.CancelIe();
	            this.CancelOpera();
	            this.CancelMozilla();
	            this.IsMozilla = true; 
		        this.IsNetscape7 = true;
	        }
	        if ((navigator.vendor && navigator.vendor.indexOf("Netscape") != -1 && navigator.product == 'Gecko' && window.find)||(this.AgentString.indexOf("netscape/8") != -1||this.AgentString.indexOf("netscape8") != -1))
	        {   //Netscape 8+, Mozilla 1+ and advanced Gecko
	            this.CancelIe();
	            this.CancelOpera();
	            this.CancelMozilla();
	            this.IsMozilla = true; 
		        this.IsNetscape8 = true;
	        }
	        if (navigator.vendor && navigator.vendor == "Camino")
	        {
	            this.CancelIe();
	            this.CancelOpera();
		        this.IsCamino = true;
		        this.IsMozilla = true;
	        }
	        if (((navigator.vendor && navigator.vendor == 'KDE')||(document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)))//(this.AgentString.indexOf("Konqueror")!=-1)||
	        {
	        this.CancelIe();
	        this.CancelOpera();
	        this.IsKonqueror = true;
	        }
	        if ((document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(navigator.accentColorName))
	        {
	        this.CancelIe();
	        this.CancelOpera();
	        this.IsOmniWeb = true;
	        }
	        else if (document.layers && navigator.mimeTypes['*'] )
	        {
	        this.CancelIe();
	        this.CancelOpera();
	        this.IsNetscape4 = true;
	        }
	        if((document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName))//this.IsOsMac && this.UpLevelDom && (parseInt(navigator.productSub)>=20020000)&& (navigator.vendor.indexOf("Apple Computer")!=-1)
	        {
		        this.CancelIe();
	            this.CancelOpera();
	            this.IsSafari = true;
	        }
	        else
	        {
	        IsUnknownBrowser = true;
	        }
        },
        // prints the detected browsers for test comparison
        DebugBrowser: function()
        {
            var BrowserString = "IsNetscape4 " + this.IsNetscape4 + "\n";
            BrowserString += "IsNetscape6 " + this.IsNetscape6 + "\n";
            BrowserString += "IsNetscape6Plus " + this.IsNetscape6Plus + "\n";
            BrowserString += "IsNetscape7 " + this.IsNetscape7 + "\n";
            BrowserString += "IsNetscape8 " + this.IsNetscape8 + "\n";
            BrowserString += "IsMozilla " + this.IsMozilla + "\n";
            BrowserString += "IsFirefox " + this.IsFirefox + "\n";
            BrowserString += "IsSafari " + this.IsSafari + "\n";
            BrowserString += "IsIE " + this.IsIE + "\n";
            BrowserString += "IsIEMac " + this.IsIEMac + "\n";
            BrowserString += "IsIE5Mac " + this.IsIE5Mac + "\n";
            BrowserString += "IsIE4Mac " + this.IsIE4Mac + "\n";
            BrowserString += "IsIE5Win " + this.IsIE5Win + "\n";
            BrowserString += "IsIE55Win " + this.IsIE55Win + "\n";
            BrowserString += "IsIE6Win " + this.IsIE6Win + "\n";
            BrowserString += "IsIE4Win " + this.IsIE4Win + "\n";
            BrowserString += "IsOpera " + this.IsOpera + "\n";
            BrowserString += "IsOpera4 " + this.IsOpera4 + "\n";
            BrowserString += "IsOpera5 " + this.IsOpera5 + "\n";
            BrowserString += "IsOpera6 " + this.IsOpera6 + "\n";
            BrowserString += "IsOpera7 " + this.IsOpera7 + "\n";
            BrowserString += "IsOpera8 " + this.IsOpera8 + "\n";
            BrowserString += "IsKonqueror " + this.IsKonqueror + "\n";
            BrowserString += "IsOmniWeb " + this.IsOmniWeb + "\n";
            BrowserString += "IsCamino " + this.IsCamino + "\n";
            BrowserString += "IsUnknownBrowser " + this.IsUnknownBrowser + "\n";
            alert(BrowserString);
        },
        // prints the detected operating systems for test comparison
        DebugOS: function()
        {
            var OsString = "IsOsWindows " + this.IsOsWindows + "\n";
            OsString += "IsOsLinux " + this.IsOsLinux + "\n";
            OsString += "IsOsUnix " + this.IsOsUnix + "\n";
            OsString += "IsOsMac " + this.IsOsMac + "\n";
            OsString += "IsUnknownOS " + this.IsUnknownOS + "\n";
            alert(OsString);
        },
        // prints the detected features for test comparison
        DebugFeatures: function()
        {
            var FeaturesString = "UpLevelDom " + this.UpLevelDom + "\n";
            FeaturesString += "AllCollection " + this.AllCollection + "\n";
            FeaturesString += "Layers " + this.Layers + "\n";
            FeaturesString += "Focus " + this.Focus + "\n";
            FeaturesString += "StandardMode " + this.StandardMode + "\n";
            FeaturesString += "HasImagesArray " + this.HasImagesArray + "\n";
            FeaturesString += "HasAnchorsArray " + this.HasAnchorsArray + "\n";
            FeaturesString += "DocumentClear " + this.DocumentClear + "\n";
            FeaturesString += "AppendChild " + this.AppendChild + "\n";
            FeaturesString += "InnerWidth " + this.InnerWidth + "\n";
            FeaturesString += "HasComputedStyle " + this.HasComputedStyle + "\n";
            FeaturesString += "HasCurrentStyle " + this.HasCurrentStyle + "\n";
            FeaturesString += "HasFilters " + this.HasFilters + "\n";
            FeaturesString += "HasStatus " + this.HasStatus + "\n";
            alert(FeaturesString);
        }
    }
    // class definition END

RadBrowserUtils.Init();
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.RadCalendarSelector = function(selectorType
	, rowIndex
	, colIndex
	, radCalendar
	, radCalendarView
	, domElement)
{
	this.SelectorType = selectorType;
	this.RadCalendar = radCalendar;
	this.RadCalendarView = radCalendarView;
	this.DomElement = domElement;
	this.IsSelected = false;
	
	this.RowIndex = rowIndex;
	this.ColIndex = colIndex;
	
	var thisObj = this;
}

RadCalendarNamespace.RadCalendarSelector.prototype.Dispose = function()
{
	this.disposed = true;
	
	this.DomElement = null;
	
	this.RadCalendar = null;
	this.RadCalendarView = null;
}

RadCalendarNamespace.RadCalendarSelector.prototype.MouseOver = function()
{	
	// Hover the specific row/column/view
	var mainView = document.getElementById(this.RadCalendarView.ID);

	switch (this.SelectorType)
	{
		case RadCalendarUtils.COLUMN_HEADER:
			for (var i = 0; i < this.RadCalendarView.Rows; i++)
			{	
				var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex].DayId;
				var date = RadCalendarUtils.GetDateFromId(id);
				var temp = this.RadCalendarView.RenderDays.Get(date);
				if (temp) temp.MouseOver();
			}
			break;
			
		case RadCalendarUtils.VIEW_HEADER:
			for (var i = 0; i < this.RadCalendarView.Rows; i++)
			{
				for (var j = 0; j < this.RadCalendarView.Cols; j++)
				{
					var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex + j].DayId;
					var date = RadCalendarUtils.GetDateFromId(id);
					var temp = this.RadCalendarView.RenderDays.Get(date);
					if (temp) temp.MouseOver();
				}
			}
			break;
			
		case RadCalendarUtils.ROW_HEADER:
			for (var i = 0; i < this.RadCalendarView.Cols; i++)
			{
				var id = mainView.rows[this.RowIndex].cells[this.ColIndex + i].DayId;
				var date = RadCalendarUtils.GetDateFromId(id);
				var temp = this.RadCalendarView.RenderDays.Get(date);
				if (temp) temp.MouseOver();
			}
			break;
	}
};

RadCalendarNamespace.RadCalendarSelector.prototype.MouseOut = function()
{
	// Unhover the specific row/column/view
	var mainView = document.getElementById(this.RadCalendarView.ID);
	switch (this.SelectorType)
	{	
		case RadCalendarUtils.COLUMN_HEADER:
			for (var i = 0; i < this.RadCalendarView.Rows; i++)
			{	
				var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex].DayId;
				var date = RadCalendarUtils.GetDateFromId(id);
				var temp = this.RadCalendarView.RenderDays.Get(date);
				if (temp) temp.MouseOut();
			}
			break;
		case RadCalendarUtils.VIEW_HEADER:
			for (var i = 0; i < this.RadCalendarView.Rows; i++)
			{
				for (var j = 0; j < this.RadCalendarView.Cols; j++)
				{
					var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex + j].DayId;
					var date = RadCalendarUtils.GetDateFromId(id);
					var temp = this.RadCalendarView.RenderDays.Get(date);
					if (temp) temp.MouseOut();
				}
			}
			break;
		case RadCalendarUtils.ROW_HEADER:
			for (var i = 0; i < this.RadCalendarView.Cols; i++)
			{
				var id = mainView.rows[this.RowIndex].cells[this.ColIndex + i].DayId;
				var date = RadCalendarUtils.GetDateFromId(id);
				var temp = this.RadCalendarView.RenderDays.Get(date);
				if (temp) temp.MouseOut();
			}
			break;
	}
};

RadCalendarNamespace.RadCalendarSelector.prototype.Click = function()
{
    switch (this.SelectorType)
	{
		case RadCalendarUtils.COLUMN_HEADER:	
		    var evt = {	            
	            DomElement : this.DomElement,
	            ColIndex : this.ColIndex
	          };
	          		    
		    if (this.RadCalendar.RaiseEvent("OnColumnHeaderClick", evt) == false)
	        {
		        return;
	        }                              
		    break;
		case RadCalendarUtils.ROW_HEADER:
		    var evt = {
	            DomElement : this.DomElement,	            
	            RowIndex : this.RowIndex
	          };
		    if (this.RadCalendar.RaiseEvent("OnRowHeaderClick", evt) == false)
	        {
		        return;
	        }     		                                   
		    break;
		case RadCalendarUtils.VIEW_HEADER:	
		     var evt = {
	            DomElement : this.DomElement
	          };			    	
		    if (this.RadCalendar.RaiseEvent("OnViewSelectorClick", evt) == false)
	        {
		        return;
	        }     		                                   
		    break; 
    }
	
	if (this.RadCalendar.EnableMultiSelect)
	{   
		var mainView = document.getElementById(this.RadCalendarView.ID);
		//if there is a cell, which is not selected, the selector.IsSelected=false (select every cell), otherwise is true (unselect every cell)                
        this.IsSelected = true;   
                
		switch (this.SelectorType)
		{
			case RadCalendarUtils.COLUMN_HEADER:			    
			    for (var j = 0; j < this.RadCalendarView.Rows; j++)
				{	
					var id = mainView.rows[this.RowIndex + j].cells[this.ColIndex].DayId;
					var date = RadCalendarUtils.GetDateFromId(id);
					var temp = this.RadCalendarView.RenderDays.Get(date);
					if (!temp)
						continue;
					if(temp.IsSelected == false)
                    {
                        this.IsSelected = !this.IsSelected;
                        break;
                    }										
				}
			
				for (var i = 0; i < this.RadCalendarView.Rows; i++)
				{	
					var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex].DayId;
					var date = RadCalendarUtils.GetDateFromId(id);
					var temp = this.RadCalendarView.RenderDays.Get(date);
					if (!temp)
						continue;
					if (this.IsSelected)
					{
						if (temp.IsSelected)
						{
							temp.Select(false, true);
						}
					}
					else
					{
						if (!temp.IsSelected)
						{
							temp.Select(true, true);
						}
					}
				}
				break;
				
			case RadCalendarUtils.VIEW_HEADER:	
			   	
			    for (var i = 0; i < this.RadCalendarView.Rows; i++)
				{
					for (var j = 0; j < this.RadCalendarView.Cols; j++)
					{
						var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex + j].DayId;
						var date = RadCalendarUtils.GetDateFromId(id);
						var temp = this.RadCalendarView.RenderDays.Get(date);
						if (!temp)
							continue;
						if(temp.IsSelected == false)
                        {
                            this.IsSelected = !this.IsSelected;     
                            break;
                        }		
					}							
					if(this.IsSelected == false)			
					{
					    break;
					}
				}
				
				for (var i = 0; i < this.RadCalendarView.Rows; i++)
				{
					for (var j = 0; j < this.RadCalendarView.Cols; j++)
					{
						var id = mainView.rows[this.RowIndex + i].cells[this.ColIndex + j].DayId;
						var date = RadCalendarUtils.GetDateFromId(id);
						var temp = this.RadCalendarView.RenderDays.Get(date);
						if (!temp)
							continue;
						if (this.IsSelected)
						{
							if (temp.IsSelected)
							{
								temp.Select(false, true);
							}
						}
						else
						{
							if (!temp.IsSelected)
							{
								temp.Select(true, true);
							}
						}
					}
				}
				break;
				
			case RadCalendarUtils.ROW_HEADER:			   
			    for (var j = 0; j < this.RadCalendarView.Cols; j++)
			    {				    
				    var id = mainView.rows[this.RowIndex].cells[this.ColIndex + j].DayId;
				    var date = RadCalendarUtils.GetDateFromId(id);
				    var temp = this.RadCalendarView.RenderDays.Get(date);
				    if (!temp)
					    continue;	
                    if(temp.IsSelected == false)
                    {
                        this.IsSelected = !this.IsSelected;
                        break;
                    }						
			    }
			
				for (var i = 0; i < this.RadCalendarView.Cols; i++)
				{
					var id = mainView.rows[this.RowIndex].cells[this.ColIndex + i].DayId;
					var date = RadCalendarUtils.GetDateFromId(id);
					var temp = this.RadCalendarView.RenderDays.Get(date);
					if (!temp)
						continue;
					if (this.IsSelected)
					{
						if (temp.IsSelected)
						{
							temp.Select(false, true);
						}
					}
					else
					{
						if (!temp.IsSelected)
						{
							temp.Select(true, true);
						}
					}
				}
				break;			
		}

		this.RadCalendar.SerializeSelectedDates();
		this.RadCalendar.Submit("d");
	}
};;if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}



RadCalendarNamespace.RadCalendarView = function(radCalendar
	, domTable
	, id
	, cols
	, rows
	, isParentView	
	, useRowHeadersAsSelectors
	, useColumnHeadersAsSelectors
	, orientation
	, focusedDate)
{
    // private members
    this._SingleViewMatrix = domTable;
    this._ViewInMonthDate = focusedDate;
    
    this.MonthsInView = 1;
    this._MonthStartDate = null;
    this._MonthDays = null;
    this._MonthEndDate = null;
    this._ViewStartDate = null;
    this._ContentRows = rows;
    this._ContentColumns = cols;
    this._TitleContent = null;

	this.RadCalendar = radCalendar;
	this.DateTimeFormatInfo = radCalendar ? radCalendar.DateTimeFormatInfo : null;
	this.Calendar = this.DateTimeFormatInfo ? this.DateTimeFormatInfo.Calendar : null;
	
	if (!isParentView)	
		this.SetViewDateRange();
	
	this.DomTable = domTable;
	this.ID = id;
	this.Cols = cols;
	this.Rows = rows;
	this.IsMultiView = isParentView;

	if (isParentView)
		return;	// parent view has no enabled functionallity - headers/selectors, etc.
		
    if (!this.RadCalendar.Enabled)
        return;
    
	var hasHeader = false;
	var hasColumnHeader = false;
	var hasViewSelector = false;
	var hasRowHeader = false;
	this.UseRowHeadersAsSelectors = useRowHeadersAsSelectors;
	this.UseColumnHeadersAsSelectors = useColumnHeadersAsSelectors;

	var rowIndex = 0;	
	var id = domTable.rows[rowIndex].cells[0].id;
	if (id.indexOf("_hd") > -1)
	{
		hasHeader = true;		
		id = domTable.rows[++rowIndex].cells[0].id;
	}
	
	if (id.indexOf("_vs") > -1)
	{
		hasViewSelector = true;
	}
	
	if (domTable.rows[rowIndex].cells[1] && domTable.rows[rowIndex].cells[1].id.indexOf("_cs") > -1)
	{
		hasColumnHeader = true;
	}
	
	if (domTable.rows[rowIndex + 1] && domTable.rows[rowIndex + 1].cells[0].id.indexOf("_rs") > -1)
	{
		hasRowHeader = true;
	}	
	
	var startRowIndex = 0;
	var startColumnIndex = 0;

	if (hasHeader)
	{
		startRowIndex++;
	}
	
	if (hasColumnHeader || hasViewSelector)
	{
		startRowIndex++;
	}
	
	if (hasRowHeader || hasViewSelector)
	{
		startColumnIndex++;
	}

	this.StartRowIndex = startRowIndex;
	this.StartColumnIndex = startColumnIndex;
    
    var arrWeekNumbers = [];
    if (orientation == RadCalendarUtils.RENDERINROWS)				
    {	
        arrWeekNumbers = this.ComputeHeaders(rows, cols);
    }        
    
    if(orientation == RadCalendarUtils.RENDERINCOLUMNS)
    {
        arrWeekNumbers = this.ComputeHeaders(cols, rows);
    }
	    
	if (!isParentView)
	{
		this.RenderDays = new RadCalendarUtils.DateCollection();			

		for (var i = startRowIndex; i < domTable.rows.length; i++)
		{
			var row = domTable.rows[i];
			for (var j = startColumnIndex; j < row.cells.length; j++)
			{
				var currentDayCell = row.cells[j];
				if (typeof(currentDayCell.DayId) == "undefined")
				{
				    currentDayCell.DayId = "";
				}
				
				var processedDate = this.GetDate(i - startRowIndex, j - startColumnIndex, cols, rows, this._ViewStartDate);			      
				
			    var isOutOfRange = !this.RadCalendar.RangeValidation.IsDateValid(processedDate);
			    var isOtherMonth = !((this.RadCalendar.RangeValidation.CompareDates(processedDate, this._MonthStartDate) >= 0) &&
				                   (this.RadCalendar.RangeValidation.CompareDates(this._MonthEndDate, processedDate) >= 0));
			    
			    if(isOutOfRange || (isOtherMonth && !this.RadCalendar.ShowOtherMonthsDays))
				{
				    continue;
				}
								
				if (isNaN(processedDate[0]) || isNaN(processedDate[1]) || isNaN(processedDate[2]))
				{
					continue;
				}
			    
			    // Create a day object
				var dayID = currentDayCell.DayId;
				if (!dayID)
				{
				    //if (!isOutOfRange)
                    //{
                        currentDayCell.DayId = this.RadCalendar.ClientID + "_" + processedDate.join("_");
                        dayID = currentDayCell.DayId;
                    //}
				}
                
				if (!dayID)
					continue;
				
				var isSelected = (null != this.RadCalendar.Selection.SelectedDates.Get(processedDate));
				var specDay = this.RadCalendar.SpecialDays.Get(processedDate);
				
				var dayOfWeek = this.Calendar.GetDayOfWeek(processedDate);
				var isWeekend = (0 == dayOfWeek || 6 == dayOfWeek);
				
				var isToday = (specDay && specDay.Repeatable == RadCalendarUtils.RECURRING_TODAY);
				var thisMonth = (processedDate[1] == this._MonthStartDate[1]) ;
				var isDisabled = specDay ? specDay.IsDisabled : false;
				var specDayStyle = null;								
	            if (specDay)
	            {
	                var specDayID = "SpecialDayStyle_" + specDay.Date.join("_");
	                specDayStyle = specDay.ItemStyle[specDayID];
	            }

				var style = this.RadCalendar.GetItemStyle(!thisMonth, isOutOfRange, isWeekend, isSelected, isDisabled, specDayStyle);
				
				var currentCellData = [null				// RenderDay.TemplateID
					, processedDate						// RenderDay.Date
					, true								// RenderDay.IsSelectable
					, isSelected						// RenderDay.IsSelected
					, null								// RenderDay.IsDisabled
					, isToday						    // RenderDay.IsToday
					, null								// RenderDay.Repeatable
					, isWeekend							// RenderDay.IsWeekend
					, null								// RenderDay.ToolTip
					, specDay ? specDay.ItemStyle : style // RenderDay.ItemStyle
					, currentDayCell					// RenderDay.DomElement
					, this.RadCalendar					// RenderDay.RadCalendar
					, dayID								// RenderDay.ID
					, this								// RenderDay.RadCalendarView
					, i - startRowIndex					// RenderDay.DayRow
					, j - startColumnIndex				// RenderDay.DayColumn
				];
				
				var newRenderDay = new RadCalendarNamespace.RenderDay(currentCellData);
				this.RenderDays.Add(newRenderDay.Date, newRenderDay);
			}
        }
        
        
       
        // do not attach event handlers but this check must be here 
        // so that view changes function correctly with Preview Calendar
        if (this.RadCalendar.PresentationType == 2) //Preview
		    return;
        
    	var thisObj = this;
    	this.genericHandler = function(e, eventName)
    	{
    	    var target = RadCalendarUtils.FindTarget(e, thisObj.RadCalendar.ClientID);
		    if (target == null)
		    {
		        return;
		    }

		    if (target.DayId) //RenderDay cell
		    {
		        var processedDay = RadCalendarUtils.GetRenderDay(thisObj, target.DayId);    
                if (processedDay != null)
                {
                    if (eventName == "Click")
                    {
                        processedDay[eventName].apply(processedDay, [e]);
                    }
                    else
                    {
                        processedDay[eventName].apply(processedDay);
                    }
                }
		    }
		    else if (target.id != null && target.id != "")
		    {
		        if (target.id.indexOf("_cs") > -1)
                {
                    for (var i = 0; i < thisObj.ColumnHeaders.length; i++)
                    {
                        var columnHeader = thisObj.ColumnHeaders[i];
                        if (columnHeader.DomElement.id == target.id)
                        {
                            columnHeader[eventName].apply(columnHeader);
                            
                        }
                    }                    
                }
                else if (target.id.indexOf("_rs") > -1)
                {
                    for (var i = 0; i < thisObj.RowHeaders.length; i++)
                    {
                        var rowHeader = thisObj.RowHeaders[i];
                        if (rowHeader.DomElement.id == target.id)
                        {
                            rowHeader[eventName].apply(rowHeader);
                        }
                    }                    
                }
                else if (target.id.indexOf("_vs") > -1)
                {
                    thisObj.ViewSelector[eventName].apply(thisObj.ViewSelector);
                }
		    }  
    	}
    	
    	var genericHandler = this.genericHandler;
    	
		this.clickHandler = function(e)
		{
		    genericHandler(e, "Click");    
		}         
        RadHelperUtils.AttachEventListener(this.DomTable, "click", this.clickHandler);
         
        this.mouseOverHandler = function(e)
        {
		    genericHandler(e, "MouseOver");   
		}		 
		RadHelperUtils.AttachEventListener(this.DomTable, "mouseover", this.mouseOverHandler);
		 
        this.mouseOutHandler = function(e)
        {
            genericHandler(e, "MouseOut");
	    }		 
		RadHelperUtils.AttachEventListener(this.DomTable, "mouseout", this.mouseOutHandler);		 
		
	}
	
	var headerRowIndex = Math.max(startRowIndex - 1, 0);
	
	//update the week numbers of the current view	
	if (orientation == RadCalendarUtils.RENDERINCOLUMNS && hasColumnHeader)
	    for (i = 0; i < this.Cols; i++)
	    {		
	       var cell = domTable.rows[headerRowIndex].cells[startColumnIndex + i];
	       if (this.isNumber(cell.innerHTML)) //the ColumnHeaderText/Image is not set
		   {			
				cell.innerHTML = arrWeekNumbers[i];	
		   }
		   else
		   {
				break;
		   }
	    }
	    
	if (orientation == RadCalendarUtils.RENDERINROWS && hasRowHeader)
	    for (i = 0; i < this.Rows; i++)
	    {
	        var cell = domTable.rows[startRowIndex + i].cells[0]; 
	        if (this.isNumber(cell.innerHTML)) //the RowHeaderText/Image is not set
			{
				cell.innerHTML = arrWeekNumbers[i];	
			}
			else
			{
				break; //the others will be too text/image
			}
	    }
		
		
	// Attach the column header event handlers if needed
	this.ColumnHeaders = [];
	if (hasColumnHeader && this.UseColumnHeadersAsSelectors)
	{		
		for (i = 0; i < this.Cols; i++)
		{
			var cell = domTable.rows[headerRowIndex].cells[startColumnIndex + i];
			var newColumnHeader = new RadCalendarNamespace.RadCalendarSelector(RadCalendarUtils.COLUMN_HEADER
				, startRowIndex
				, startColumnIndex + i
				, this.RadCalendar
				, this
				, cell);			
		  		
			this.ColumnHeaders[i] = newColumnHeader;
		}
	}
	
	// Attach the row header event handlers if needed
	this.RowHeaders = [];
	if (hasRowHeader && this.UseRowHeadersAsSelectors)
	{
		for (i = 0; i < this.Rows; i++)
		{
			var cell = domTable.rows[startRowIndex + i].cells[0]; 
			var newRowHeader = new RadCalendarNamespace.RadCalendarSelector(RadCalendarUtils.ROW_HEADER			
				, startRowIndex + i
				, 1
				, this.RadCalendar
				, this
				, cell);
				
			this.RowHeaders[i] = newRowHeader;
		}
	}
	
	// Attach the view select event handlers if needed
	this.ViewSelector = null;
	if (hasViewSelector)
	{
		var newViewSelector = new RadCalendarNamespace.RadCalendarSelector(RadCalendarUtils.VIEW_HEADER
			, headerRowIndex + 1
			, 1
			, this.RadCalendar
			, this
			, domTable.rows[headerRowIndex].cells[0]);
					
		this.ViewSelector = newViewSelector;
	}	
}

RadCalendarNamespace.RadCalendarView.prototype.isNumber = function(a) 
{
	if (isNaN(parseInt(a)))
	  return false;
	else
	  return true;
}

RadCalendarNamespace.RadCalendarView.prototype.ComputeHeaders = function(weekNumberCount,weekDayCount)
{
    var arrWeekNumbers = [];
    var date = this._ViewStartDate;
	for (var i = 0; i < weekNumberCount; i++)
	{	
	    if (weekDayCount <= 7)
        {
            var tmpDate = this.Calendar.AddDays(date, weekDayCount - 1);            
            if (tmpDate[2] < date[2])
            {
                var firstMonthDate = [tmpDate[0], tmpDate[1], 1];
                arrWeekNumbers[arrWeekNumbers.length] = this.GetWeekOfYear(firstMonthDate);
            }
            else
            {
                arrWeekNumbers[arrWeekNumbers.length] = this.GetWeekOfYear(date);
            }                
            date = this.Calendar.AddDays(tmpDate, 1);
        }
        else
        {
            var tmpDate = this.Calendar.AddDays(date, 6);            
            if (tmpDate[2] < date[2])
            {
                var firstMonthDate = [tmpDate[0], tmpDate[1], 1];
                arrWeekNumbers[arrWeekNumbers.length] = this.GetWeekOfYear(firstMonthDate);
            }
            else
            {
                arrWeekNumbers[arrWeekNumbers.length] = this.GetWeekOfYear(date);
            }                
            date = this.Calendar.AddDays(tmpDate, weekDayCount - 6);
        }
	}
	return arrWeekNumbers;
}

RadCalendarNamespace.RadCalendarView.prototype.GetDate = function(rowIndex, columnIndex, cols, rows, firstDate)
{
    var daysToAdd;
    if(this.RadCalendar.Orientation  == RadCalendarUtils.RENDERINROWS)
    {
        daysToAdd = (cols * rowIndex) + columnIndex;
    }
    else if(this.RadCalendar.Orientation == RadCalendarUtils.RENDERINCOLUMNS)
	{
	    daysToAdd = (rows * columnIndex) + rowIndex;
	}
    var currentDate = this.Calendar.AddDays(firstDate, daysToAdd);

    return currentDate;
};



RadCalendarNamespace.RadCalendarView.prototype.Dispose = function()
{	
	if (this.disposed)
		return;
		
	this.disposed = true;
	
	if (this.RenderDays != null)
	{
		var days = this.RenderDays.GetValues();
		for (var i = 0; i < days.length; i++)
		{		
			days[i].Dispose();
		}
	
		this.RenderDays.Clear();
	}
	    
    if (this.ColumnHeaders != null)
    {
		for (var i = 0; i < this.ColumnHeaders.length; i++)
		{
			this.ColumnHeaders[i].Dispose();
		}
    }
    this.ColumnHeaders = null;
    
    if (this.RowHeaders != null)
    {
		for (var i = 0; i < this.RowHeaders.length; i++)
		{
			this.RowHeaders[i].Dispose();
		}
    }
    
    if (this.clickHandler != null)
    {
        RadHelperUtils.DetachEventListener(this.DomTable, "click", this.clickHandler);
        this.clickHandler = null;
    }
    
    if (this.mouseOverHandler != null)
    {
        RadHelperUtils.DetachEventListener(this.DomTable, "mouseover", this.mouseOverHandler);
        this.mouseOverHandler = null;
    }
    
    if (this.mouseOutHandler != null)
    {
        RadHelperUtils.DetachEventListener(this.DomTable, "mouseout", this.mouseOutHandler);
        this.mouseOutHandler = null;
    }
    
    this.genericHandler = null;
    
    this.RowHeaders = null;
	
	if (this.ViewSelector != null)
		this.ViewSelector.Dispose();
	this.ViewSelector = null;
	
    this._SingleViewMatrix = null;    
    this._ContentRows = null;
    this._ContentColumns = null;
    this.RadCalendar.RecurringDays.Clear();
	this.RadCalendar = null;
	this.Calendar = null;	
	
	this.DomTable = null;
	this.Cols = null;
	this.Rows = null;
}

RadCalendarNamespace.RadCalendarView.prototype.GetWeekOfYear = function(date)
{
	return this.Calendar.GetWeekOfYear(date
		, this.DateTimeFormatInfo.CalendarWeekRule
		, this.NumericFirstDayOfWeek());
};

RadCalendarNamespace.RadCalendarView.prototype.NumericFirstDayOfWeek = function()
{
	if (this.RadCalendar.FirstDayOfWeek != RadCalendarUtils.DEFAULT)
	{
		return this.RadCalendar.FirstDayOfWeek;
	}
	return this.DateTimeFormatInfo.FirstDayOfWeek;
};

RadCalendarNamespace.RadCalendarView.prototype.EffectiveVisibleDate = function()
{
	var date = this._ViewInMonthDate || this.RadCalendar.FocusedDate;
	return [date[0], date[1], 1];
};

RadCalendarNamespace.RadCalendarView.prototype.FirstCalendarDay = function(visibleDate)
{
    //visibleDate is the product of EffectiveVisibleDate
	var time1 = visibleDate;
	var num1 = (this.Calendar.GetDayOfWeek(time1)) - this.NumericFirstDayOfWeek();
	if (num1 <= 0)
	{
		num1 += 7;
	}
    // the date that is the beginning of the rendered calendar
	return this.Calendar.AddDays(time1, -num1);
};

RadCalendarNamespace.RadCalendarView.prototype.SetViewDateRange = function()
{
    var isMultiView = (this.RadCalendar.ViewIDs.length > 1);
    if (!isMultiView)
    {
        this._MonthStartDate = this.EffectiveVisibleDate();
    }
    else
    {
        this._MonthStartDate = this.RadCalendar.ViewsHash[this._SingleViewMatrix.id][0]; //must be this._MultiViewMatrix when we implement it on the client
	}

	this._MonthDays = this.Calendar.GetDaysInMonth(this._MonthStartDate[0], this._MonthStartDate[1]);
    this._MonthEndDate = this.Calendar.AddDays(this._MonthStartDate,this._MonthDays-1);
    this._ViewStartDate = this.FirstCalendarDay(this._MonthStartDate);
    this._ViewEndDate = this.Calendar.AddDays(this._ViewStartDate, (this._ContentRows * this._ContentColumns - 1));

	this.GetTitleContentAsString();
};

RadCalendarNamespace.RadCalendarView.prototype.GetTitleContentAsString = function()
{
	if(!this.IsMultiView)
	{
		this._TitleContent = this.DateTimeFormatInfo.FormatDate(this.EffectiveVisibleDate(), this.RadCalendar.TitleFormat);
	}
	else
	{
		this._TitleContent =  this.DateTimeFormatInfo.FormatDate(this._ViewStartDate, this.RadCalendar.TitleFormat) 
			+ this.RadCalendar.DateRangeSeparator 
			+ this.DateTimeFormatInfo.FormatDate(this._ViewEndDate, this.RadCalendar.TitleFormat);
	}
	return this._TitleContent;
};

RadCalendarNamespace.RadCalendarView.prototype.RenderDaysSingleView = function()
{
	this.SetViewDateRange();

	var effectiveVisibleDate = this.EffectiveVisibleDate();
	var firstDate = this.FirstCalendarDay(effectiveVisibleDate);	
	var viewTable = this._SingleViewMatrix;
	
    this.RenderViewDays(viewTable
		, firstDate
		, effectiveVisibleDate
		, this.RadCalendar.Orientation
		, this.StartRowIndex
		, this.StartColumnIndex);
		
	
	this.ApplyViewTable(viewTable, this.ScrollDir || 0);		
	var titleCell = document.getElementById(this.RadCalendar.TitleID);
	
	if (titleCell)
			titleCell.innerHTML = this._TitleContent;
	
    return viewTable;
};

RadCalendarNamespace.RadCalendarView.prototype.RenderViewDays = function(singleViewMatrix
	, firstDay
	, visibleDate
	, orientation
	, startRowIndex
	, startColumnIndex)
{
	var date = firstDay;	
	var row, cell;
	if(orientation == RadCalendarUtils.RENDERINROWS)
	{	
		for (var i = startRowIndex; i < singleViewMatrix.rows.length; i++)
		{
			var row = singleViewMatrix.rows[i];			
			for (var j = startColumnIndex; j < row.cells.length; j++)
			{
                cell = row.cells[j];
				this.SetCalendarCell(cell, date, i, j);
				
				date = this.Calendar.AddDays(date, 1);
			}
		}
	}
	else if(orientation == RadCalendarUtils.RENDERINCOLUMNS)
	{
		var colsCount = singleViewMatrix.rows[0].cells.length;		
		for (var i = startColumnIndex; i < colsCount; i++)
		{
			for (var j = startRowIndex; j < singleViewMatrix.rows.length; j++)
			{
                cell = singleViewMatrix.rows[j].cells[i];
				this.SetCalendarCell(cell, date, j, i);
				date = this.Calendar.AddDays(date, 1);
			}
		}
	}
};

RadCalendarNamespace.RadCalendarView.prototype.SetCalendarCell = function(cell, date, rowIndex, columnIndex)
{
	var isOutOfRange = !this.RadCalendar.RangeValidation.IsDateValid(date);
	var thisMonth = (date[1] == this._MonthStartDate[1]) ;
	
	var text = this.DateTimeFormatInfo.FormatDate(date, this.RadCalendar.CellDayFormat);
	
	var specDate = this.RadCalendar.SpecialDays.Get(date);

    if (this.RadCalendar.EnableRepeatableDaysOnClient && specDate == null)
    {	    
        var recurringMatches = RadCalendarUtils.RECURRING_NONE;
        var specDaysArray = this.RadCalendar.SpecialDays.GetValues();	    
        for (var i=0; i<specDaysArray.length; i++)
        {
            recurringMatches = specDaysArray[i].IsRecurring(date);
            if (recurringMatches != RadCalendarUtils.RECURRING_NONE)
            {
                specDate = specDaysArray[i];                
                this.RadCalendar.RecurringDays.Add(date, specDate);
                break;
            }
        }
    }

    var selDate = this.RadCalendar.Selection.SelectedDates.Get(date);
	var isSelected = false;
	if (thisMonth || (!thisMonth && this.RadCalendar.ShowOtherMonthsDays))
	{
	    if (selDate != null)
	    {
		    isSelected = true;
	    }	
	
	    if (!isOutOfRange)
	    {
	        text = "<a href='#' onclick='return false;'>" + text + "</a>";
	    }
	    else
	    {
	        text = "<span>"  + text + "</span>";
	    }
	}
	else
	{
	    text = "&#160;";
	}
	
	var dayOfWeek = this.Calendar.GetDayOfWeek(date);
	var isWeekend = (0 == dayOfWeek || 6 == dayOfWeek);
	var isDisabled = specDate ? specDate.IsDisabled : false;
	var isToday = (specDate && specDate.Repeatable == RadCalendarUtils.RECURRING_TODAY);

	cell.innerHTML = text;	
	var specDayStyle = null;
	if (specDate)
	{
	    var specDayID = "SpecialDayStyle_" + specDate.Date.join("_");
	    specDayStyle = specDate.ItemStyle[specDayID];	               
	}

	var style = this.RadCalendar.GetItemStyle(!thisMonth, isOutOfRange, isWeekend, isSelected, isDisabled, specDayStyle);
	if (style)
	{	
	    var changedDay = this.RadCalendar.DayRenderChangedDays[date.join("_")];	    
	    if (changedDay != null && (thisMonth || (!thisMonth && this.RadCalendar.ShowOtherMonthsDays)))
	    {	    
	        cell.style.cssText = RadCalendarUtils.MergeStyles(changedDay[0], style[0]); 	    	    
	        cell.className = RadCalendarUtils.MergeClassName(changedDay[1], style[1]);
	    }	
	    else
	    {
	        cell.style.cssText = style[0];
	        cell.className = style[1];
	    }	            
    }
    
	var dayID = this.RadCalendar.GetRenderDayID(date);

	cell.DayId = (!thisMonth && !this.RadCalendar.ShowOtherMonthsDays) ? "" : dayID;
	
	var newRenderDay = null;
	if (!isOutOfRange)
	{	
		var currentCellData = [null						// RenderDay.TemplateID
					, date								// RenderDay.Date
					, true								// RenderDay.IsSelectable
					, isSelected						// RenderDay.IsSelected
					, null								// RenderDay.IsDisabled
					, isToday							// RenderDay.IsToday
					, null								// RenderDay.Repeatable
					, isWeekend							// RenderDay.IsWeekend
					, null								// RenderDay.ToolTip
					, style                             // RenderDay.ItemStyle
					, cell								// RenderDay.DomElement
					, this.RadCalendar					// RenderDay.RadCalendar
					, dayID								// RenderDay.ID
					, this								// RenderDay.RadCalendarView
					, rowIndex							// RenderDay.DayRow
					, columnIndex						// RenderDay.DayColumn
				];

		newRenderDay = new RadCalendarNamespace.RenderDay(currentCellData);
		this.RenderDays.Add(newRenderDay.Date, newRenderDay);
	}
	else
	{
		if (cell.RenderDay != null)
		{
			if (cell.RenderDay.disposed == null)
				cell.RenderDay.Dispose();
				
			cell.RenderDay = null;
			this.RenderDays.Remove(date);
		}
	}
	
	var cellTitle = "";
	var specDay = this.RadCalendar.SpecialDays.Get(date);
	if (specDay != null && specDay.ToolTip != null)
	{
		cellTitle = specDay.ToolTip;
	}
	else if (typeof(this.RadCalendar.DayCellToolTipFormat) != "undefined")
	{
	    cellTitle = this.DateTimeFormatInfo.FormatDate(date, this.RadCalendar.DayCellToolTipFormat);		
	}
	
	cell.title = cellTitle;
	
	var oldCssText = cell.style.cssText;
	var oldCssClass = cell.className;
	var evt =
		{
			Cell : cell,
			Date : date,
			RenderDay : newRenderDay
		};
		
	this.RadCalendar.RaiseEvent("OnDayRender", evt);	
	evt = null;
	
	var newCssText = cell.style.cssText;
	var newCssClass = cell.className;
	
	if (oldCssText != newCssText || oldCssClass != newCssClass)
	{
	    if (this.RadCalendar.DayRenderChangedDays[date.join("_")] == null)
	    {
	        this.RadCalendar.DayRenderChangedDays[date.join("_")] = [];
	    }	    
	    this.RadCalendar.DayRenderChangedDays[date.join("_")][0] = RadCalendarUtils.MergeStyles(newCssText, oldCssText);
	    this.RadCalendar.DayRenderChangedDays[date.join("_")][1] = RadCalendarUtils.MergeClassName(newCssClass, oldCssClass);	    
	} 
};

RadCalendarNamespace.RadCalendarView.prototype.ApplyViewTable = function(newView, dir)
{
	this.RadCalendar.EnableNavigation(false);
	this.RadCalendar.EnableDateSelect = false;

	var view = this._SingleViewMatrix;
	var parent = view.parentNode;

	var width = parent.scrollWidth;
	var heigth = parent.scrollHeight;

	var outerDiv = document.createElement("DIV");
	outerDiv.style.overflow = "hidden";
	outerDiv.style.width = width + "px";
	outerDiv.style.height = heigth + "px";
	outerDiv.style.border = "0px solid red";
	
	var innerDiv = document.createElement("DIV");
	innerDiv.style.width = 2 * width + "px";
	innerDiv.style.height = heigth + "px";	
	innerDiv.style.border = "0px solid blue";	
	
	outerDiv.appendChild(innerDiv);
	
	if (view.parentNode)
		view.parentNode.removeChild(view);
		
	if (newView.parentNode)
		newView.parentNode.removeChild(newView);
		
	if (document.all)
	{
		view.style.display = "inline";
		newView.style.display = "inline";
	}
	else
	{
		view.style.setProperty("float", "left", "");
		newView.style.setProperty("float", "left", "");
	}
	
	var _dir = 0;
	if (dir > 0)
	{
		_dir = 1;
		innerDiv.appendChild(view);
		
		newView.parentNode.removeChild(newView);
		innerDiv.appendChild(newView);
	}
	else if (dir < 0)
	{
		_dir = -1;
		innerDiv.appendChild(newView);
		
		view.parentNode.removeChild(view);
		innerDiv.appendChild(view);
	}
	
	parent.appendChild(outerDiv);

	
	if (dir < 0)
	{
		outerDiv.scrollLeft = parent.offsetWidth + 10;
	}
	
	var thisView = this;
	var step = 10;
	var finishAnimation = function()
	{
		if (outerDiv.parentNode)
				outerDiv.parentNode.removeChild(outerDiv);
			
		if (innerDiv.parentNode)
			innerDiv.parentNode.removeChild(innerDiv);
		
		if (view.parentNode)
			view.parentNode.removeChild(view);				
		
		parent.appendChild(newView);
			
		thisView.RadCalendar.EnableNavigation(true);
		thisView.RadCalendar.EnableDateSelect = true;
	};
	
	var scrollFunc = function()
	{
		if ((_dir > 0 && (outerDiv.scrollLeft + outerDiv.offsetWidth) < outerDiv.scrollWidth)
			|| (_dir < 0 && outerDiv.scrollLeft > 0))
		{
			outerDiv.scrollLeft += _dir * step;
			window.setTimeout(scrollFunc, 10);
		}
		else
		{
			finishAnimation();
		}
	};
	
	var startAnimation = function()
	{
		window.setTimeout(scrollFunc, 100);
	}
	
	if (!this.RadCalendar.IsRtl() && this.RadCalendar.EnableNavigationAnimation == true)
		startAnimation();
	else
		finishAnimation();
};;if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

/*
 * RadCalendar
 */
function RadCalendar(
	formatInfoArray,
	specialDaysArray,
	clientEventsArray,
	clientData,
	viewsHash,
	monthYearNavigationSettings,
	stylesHash,
	dayRenderChangedDays,
	viewRepeatableDays)
{
	this.DisposeOldInstance(clientData);
	
	this.Initialize(
		formatInfoArray,
		specialDaysArray,
		clientEventsArray,
		clientData,
		viewsHash,
		monthYearNavigationSettings,
		stylesHash,
		dayRenderChangedDays,
		viewRepeatableDays);
};

RadCalendar.InitializeClient = function(clientID)
{
    var script = document.getElementById(clientID + "MSAjaxCreation");

    if(!script)
        return;

    var newScript = document.createElement("script");
    if (navigator.userAgent.indexOf("Safari") != -1)
    {
        newScript.innerHTML = script.innerHTML;
    }
    else
    {
        newScript.text = script.innerHTML;
    }

    document.body.appendChild(newScript);
    document.body.removeChild(newScript);

    script.parentNode.removeChild(script);
};

RadCalendar.prototype.DisposeOldInstance = function(clientData)
{
	try
	{
		var clientID = clientData[1];
		var oldCalendar = window[clientID];
		if (oldCalendar != null && !oldCalendar.tagName)
		{
			oldCalendar.Dispose();
			window[clientID] = null;
		}
	}
	catch(e)
	{}
}

RadCalendar.prototype.Initialize = function(
	formatInfoArray,
	specialDaysArray,
	clientEventsArray,
	clientData,
	viewsHash,
	monthYearNavigationSettings,
	stylesHash,
	dayRenderChangedDays,
	viewRepeatableDays)
{
	//pass the button captions for the fast month-day navigation
	this.MonthYearNavigationSettings = monthYearNavigationSettings;
	this.EnableTodayButtonSelection = (this.MonthYearNavigationSettings[4] == "False") ? false : true;
	
    //Initialize the DateTimeFormatInfo instance/property for further refferece
	this.DateTimeFormatInfo = new RadCalendarNamespace.DateTimeFormatInfo(formatInfoArray);
	// hard coded GregorianCalendar for now;
	this.DateTimeFormatInfo.Calendar = RadCalendarNamespace.GregorianCalendar;
    
    this.ProcessClientData(this, clientData);
    this.ProcessClientEvents(this, clientEventsArray);
    
    // setting additional DateTimeFormatInfo properties
	this.DateTimeFormatInfo.CalendarType = this.CalendarType;
	this.DateTimeFormatInfo.CalendarWeekRule = this.CalendarWeekRule;
	
	var i, j, TempSettings;
	
	var auxDatesHidden = this.AuxDatesHidden();
	var arrAuxDates = eval(auxDatesHidden.value);
    this.RangeMinDate = arrAuxDates[0];
    this.RangeMaxDate = arrAuxDates[1];
    this.FocusedDate = arrAuxDates[2];
	
	// Initialize the special days collection passed from the server
	this.SpecialDays = new RadCalendarUtils.DateCollection();
	for (i = 0; i < specialDaysArray.length; i++)
	{
		var rd = new RadCalendarNamespace.RenderDay(specialDaysArray[i]);
		this.SpecialDays.Add(rd.Date, rd);
	}
	
	this.ItemStyles = stylesHash;
	this.DayRenderChangedDays = dayRenderChangedDays == null ? {} : dayRenderChangedDays;
    this.RecurringDays = new RadCalendarUtils.DateCollection();

    for (var repeatableDate in viewRepeatableDays)
	{
		if( !viewRepeatableDays.hasOwnProperty(repeatableDate) )
		{
			continue;
		}
		
		var date = repeatableDate.split('_');
		var specialDate = viewRepeatableDays[repeatableDate].split('_');
		var specialDay = this.SpecialDays.Get(specialDate);
	    
	    this.RecurringDays.Add(date, specialDay);
	    
	}
	
	this.RangeValidation = new RadCalendarNamespace.RangeValidation(this.RangeMinDate, this.RangeMaxDate);
	this.Selection = new RadCalendarNamespace.Selection(this.RangeValidation, this.SpecialDays, this.RecurringDays, this.EnableMultiSelect);
    
	var viewsIDs = [];
	for (var viewId in viewsHash)
	{
		if( !viewsHash.hasOwnProperty(viewId) )
		{
			continue;
		}

	    viewsIDs[viewsIDs.length] = viewId;
	}
	
	this.TopViewID = viewsIDs[0];
	this.TitleID = this.ClientID + "_Title";
	
	var selectedDatesHidden = this.SelectedDatesHidden(); 
		
	this.Form = selectedDatesHidden.form;

	var arrSelectedDates = eval(selectedDatesHidden.value);
	for (i = 0; i < arrSelectedDates.length; i++)
	{
		this.Selection.Add(arrSelectedDates[i]);
	}

	this.LastSelectedDate = null;

	this.CalendarDomObject = document.getElementById(this.ClientID);
		
	this.ViewIDs = viewsIDs;
	this.ViewsHash = viewsHash;
	this.InitViews();

	this.EnableNavigation(this.IsNavigationEnabled());

    var calendar = this;
    this.OnLoadHandler = function()
    {
        calendar.RaiseEvent("OnLoad", null);
    }		
		
	if (typeof(this.OnLoad) == "function")
	{
	
		if (window.attachEvent)
		{
		    window.attachEvent("onload", this.OnLoadHandler);
		}
		else if (window.addEventListener)
		{
			window.addEventListener("load", this.OnLoadHandler, false);
		}
	}
	
	RadHelperUtils.AttachEventListener(window, "unload", function()
		{
			calendar.Dispose();
		});
	
	RadControlsNamespace.EventMixin.Initialize(this);
	
    this.RaiseEvent("OnInit", null);
};

RadCalendar.prototype.Dispose = function()
{	
	if (this.disposed == null)
	{
		this.disposed = true;
		this.DestroyViews();
		this.CalendarDomObject = null;
		this.Form = null;
		this.OnLoadHandler = null;
	}
};

RadCalendar.prototype.ProcessClientData = function(calendar, clientData)
{
    if(calendar)
    {
        //Initialize the client-side properties of RadCalendar with data from the server
        var propertiesCount = 0;
        calendar.PostBackCall = clientData[propertiesCount++];
        calendar.ClientID = clientData[propertiesCount++];
        calendar.Visible = clientData[propertiesCount++];
        calendar.Enabled = clientData[propertiesCount++];
        calendar.ShowColumnHeaders = clientData[propertiesCount++];
        calendar.ShowRowHeaders = clientData[propertiesCount++];
        calendar.EnableViewSelector = clientData[propertiesCount++];
        calendar.UseColumnHeadersAsSelectors = clientData[propertiesCount++];
        calendar.UseRowHeadersAsSelectors = clientData[propertiesCount++];
        calendar.ShowOtherMonthsDays = clientData[propertiesCount++];
        calendar.EnableMultiSelect = clientData[propertiesCount++];
        calendar.FocusedDateRow = clientData[propertiesCount++];
        calendar.FocusedDateColumn = clientData[propertiesCount++];
        calendar.SingleViewColumns = clientData[propertiesCount++];
        calendar.SingleViewRows = clientData[propertiesCount++];
        calendar.MultiViewColumns = clientData[propertiesCount++];
        calendar.MultiViewRows = clientData[propertiesCount++];
        calendar.FastNavigationStep = clientData[propertiesCount++];
        calendar.FirstDayOfWeek = clientData[propertiesCount++];

        calendar.Skin = clientData[propertiesCount++];
        calendar.ImagesBaseDir = clientData[propertiesCount++];
        calendar.EnableNavigationAnimation = clientData[propertiesCount++];

        calendar.SingleViewWidth = clientData[propertiesCount++];
        calendar.SingleViewHeight = clientData[propertiesCount++];
        calendar.CellDayFormat = clientData[propertiesCount++];
        calendar.CellAlign = clientData[propertiesCount++];
        calendar.CellVAlign = clientData[propertiesCount++];
        calendar.DefaultCellPadding = clientData[propertiesCount++];
        calendar.DefaultCellSpacing = clientData[propertiesCount++];

        calendar.PresentationType = clientData[propertiesCount++];
        calendar.Orientation = clientData[propertiesCount++];

        calendar.TitleAlign = clientData[propertiesCount++];
        calendar.TitleFormat = clientData[propertiesCount++];
        calendar.DayCellToolTipFormat = clientData[propertiesCount++];
        calendar.DateRangeSeparator = clientData[propertiesCount++];
        
        calendar.AutoPostBack = clientData[propertiesCount++];        
        
	    calendar.CalendarType = clientData[propertiesCount++];
	    calendar.CalendarWeekRule = clientData[propertiesCount++];
        calendar.CalendarEnableNavigation = clientData[propertiesCount++];       
        calendar.CalendarEnableMonthYearFastNavigation = clientData[propertiesCount++];
        calendar.EnableRepeatableDaysOnClient = clientData[propertiesCount++];               
    }
};
RadCalendar.prototype.ProcessClientEvents = function(calendar, clientEventsArray)
{
    if(calendar)
    {
        //Initialize the client-side event handlers with data from the server	
	    var eventsCount = 0;
	    calendar.OnInit = eval(clientEventsArray[eventsCount++]);
	    calendar.OnLoad = eval(clientEventsArray[eventsCount++]);
	    calendar.OnDateSelecting = eval(clientEventsArray[eventsCount++]);
	    calendar.OnDateSelected = eval(clientEventsArray[eventsCount++]);
	    calendar.OnDateClick = eval(clientEventsArray[eventsCount++]);
	    calendar.OnCalendarViewChanging = eval(clientEventsArray[eventsCount++]);
	    calendar.OnCalendarViewChanged = eval(clientEventsArray[eventsCount++]);  
	    calendar.OnDayRender = eval(clientEventsArray[eventsCount++]);
	    calendar.OnRowHeaderClick = eval(clientEventsArray[eventsCount++]);
	    calendar.OnColumnHeaderClick = eval(clientEventsArray[eventsCount++]);
	    calendar.OnViewSelectorClick = eval(clientEventsArray[eventsCount++]);
	}
};

RadCalendar.prototype.IsRtl = function()
{
	if (typeof(this.Rtl) == "undefined")
	{
		this.Rtl = (this.GetTextDirection() == "rtl");
	}
		
	return this.Rtl;
}

RadCalendar.prototype.GetTextDirection = function()
{
	var current = this.CalendarDomObject;
	while (current != null)
	{
		if (current.dir.toLowerCase() == "rtl")
		{
			return "rtl";
		}
		
		current = current.parentNode;
	}
	return "ltr";
}

RadCalendar.prototype.GetItemStyle = function(isOtherMonth
    , isOutOfRange
	, isWeekend
	, isSelected
	, isDisabled	
	, specDayStyle)
{    	
    var style;
	if (isOutOfRange)
	{
	    style = this.ItemStyles["OutOfRangeDayStyle"];
	}
	else if (isOtherMonth && !this.ShowOtherMonthsDays)
    {
        style = this.ItemStyles["OtherMonthDayStyle"];
    }
	else if (isSelected)
	{
	    style = this.ItemStyles["SelectedDayStyle"];
	}
	else if (specDayStyle)
	{
	    style = specDayStyle;
	}
	else if (isOtherMonth)
	{
	    style = this.ItemStyles["OtherMonthDayStyle"];
	}	
	else if (isWeekend)
	{
	    style = this.ItemStyles["WeekendDayStyle"];
	}
	else 
	{
	    style = this.ItemStyles["DayStyle"];
	}
	
	return style;
}	

RadCalendar.prototype.IsNavigationEnabled = function()
{
	if (!this.Enabled || !this.CalendarEnableNavigation)
	{
	    return false;
	}
	
	return true;
};

RadCalendar.prototype.IsMonthYearNavigationEnabled = function()
{
	if (!this.Enabled || !this.CalendarEnableMonthYearFastNavigation)
	{
	    return false;
	}
	
	return true;	
};

RadCalendar.prototype.EnableNavigation = function(enabled)
{
	enabled = (false != enabled);

	var el = document.getElementById(this.ClientID + "_FNP");
	if (el)
	{
		el.onclick = (!enabled ? null : RadCalendarUtils.AttachMethod(this.FastNavigatePrev, this));
	}
	
	el = document.getElementById(this.ClientID + "_NP");
	if (el)
	{
		el.onclick = (!enabled ? null : RadCalendarUtils.AttachMethod(this.NavigatePrev, this));
	}
	
	el = document.getElementById(this.ClientID + "_NN");
	if (el)
	{
		el.onclick = (!enabled ? null : RadCalendarUtils.AttachMethod(this.NavigateNext, this));
	}
	
	el = document.getElementById(this.ClientID + "_FNN");
	if (el)
	{
		el.onclick = (!enabled ? null : RadCalendarUtils.AttachMethod(this.FastNavigateNext, this));
	}
	
	el = document.getElementById(this.TitleID);
	if (el && this.IsMonthYearNavigationEnabled())
	{
		el.onclick = RadCalendarUtils.AttachMethod(this.ShowMonthYearFastNav, this);
		el.oncontextmenu = RadCalendarUtils.AttachMethod(this.ShowMonthYearFastNav, this);
	}
};

RadCalendar.prototype.FindRenderDay = function(date)
{
	var renderDay = null;
	for (var i = 0; i < this.CurrentViews.length; i++)
	{
		var view = this.CurrentViews[i];
		if (view.RenderDays == null)
			continue;
		renderDay = view.RenderDays.Get(date);
		if (renderDay != null)
			return renderDay;
	}
	return null;
}

RadCalendar.prototype.PerformDateSelection = function(date, selected, navigate, preventSubmit)
{
    if (this.Selection.CanSelect(date))
    {		
		if (navigate == true)
		{
			this.NavigateToDate(date);
		}
		
		var renderDay = this.FindRenderDay(date);
		
		if (selected)
		{			
			if (renderDay)
			{
				renderDay.Select(true, preventSubmit);
			}
			else
			{
				var lastSelectedDate = this.FindRenderDay(this.LastSelectedDate);
				if (lastSelectedDate && !this.EnableMultiSelect)
				{
					lastSelectedDate.PerformSelect(false);
				}
				
				this.Selection.Add(date);
				this.SerializeSelectedDates();
				
				this.LastSelectedDate = date;
			}
		}
		else
		{
			if (renderDay)
			{
				renderDay.Select(false, preventSubmit);
			}
			else
			{
				this.Selection.Remove(date);
				this.SerializeSelectedDates();
			}
		}
    }    
};

RadCalendar.prototype.GetSelectedDates = function()
{
	return this.Selection.SelectedDates.GetValues();
};

RadCalendar.prototype.SelectDate = function(date, navigate)
{
	if (this.EnableDateSelect == false)
		return false;
	
	this.PerformDateSelection(date, true, navigate);
};

RadCalendar.prototype.SelectDates = function(dates, navigate)
{
	if (false == this.EnableDateSelect)
		return false;
		
    	
	for (var i = 0; i < dates.length; i++)
	{
		this.PerformDateSelection(dates[i], true, false, false);
	}
	
	//this.Submit("d");
	this.NavigateToDate(dates[dates.length - 1]);
};

RadCalendar.prototype.UnselectDate = function(date)
{
	if (false == this.EnableDateSelect)
		return false;
		
	this.PerformDateSelection(date, false, false);
};

RadCalendar.prototype.UnselectDates = function(dates)
{
	if (false == this.EnableDateSelect)
		return false;
		
	for (var i = 0; i < dates.length; i++)
	{   
	    this.PerformDateSelection(dates[i], false, false, true);
	}

	this.Submit("d");
};

RadCalendar.prototype.DisposeView = function(viewID)
{
	for (var i = 0; i < this.CurrentViews.length; i++)
	{
		var view = this.CurrentViews[i];
		if (view.DomTable && view.DomTable.id == viewID)
		{
			view.Dispose();
			this.CurrentViews.splice(i, 1);
			return;
		}
	}
}

RadCalendar.prototype.FindView = function(viewID)
{
	var result = null;
	for (var i = 0; i < this.CurrentViews.length; i++)
	{
		var view = this.CurrentViews[i];
		if (view.DomTable.id == viewID)
		{
			result = view;
			break;
		}
	}
	return result;
}

RadCalendar.prototype.DestroyViews = function(viewIDs)
{

	if (!viewIDs)
		viewIDs = this.ViewIDs;
	
	for (var i = viewIDs.length - 1; i >= 0; i--)
	{
		this.DisposeView(viewIDs[i]);		
	}

	this.CurrentViews = null;
	this.ViewsHash = null;
}

RadCalendar.prototype.InitViews = function(viewIDs)
{
	if (!viewIDs)
		viewIDs = this.ViewIDs;
	
	this.CurrentViews = [];
	var isParentView;
	for (var i = 0; i < viewIDs.length; i++)
	{	
		isParentView = (i == 0 && viewIDs.length > 1);
		var viewID = viewIDs[i];
		
		var newView = new RadCalendarNamespace.RadCalendarView(this
			, document.getElementById(viewIDs[i])
			, viewID
			, isParentView ? this.MultiViewColumns : this.SingleViewColumns
			, isParentView ? this.MultiViewRows : this.SingleViewRows
			, isParentView
			, this.UseRowHeadersAsSelectors
			, this.UseColumnHeadersAsSelectors
			, this.Orientation);
		newView.MonthsInView = this.ViewsHash[viewID][1];
		this.DisposeView(viewIDs[i]);		
		this.CurrentViews[i] = newView;
	}

	if( (typeof(this.CurrentViews)!= "undefined") && 
	    (typeof(this.CurrentViews[0])!= "undefined") && 
	   this.CurrentViews[0].IsMultiView)
	   {
	       this.CurrentViews[0]._ViewStartDate = this.CurrentViews[0]._MonthStartDate = this.CurrentViews[1]._MonthStartDate;
           this.CurrentViews[0]._ViewEndDate = this.CurrentViews[0]._MonthEndDate = this.CurrentViews[(this.CurrentViews.length-1)]._MonthEndDate;
	   }
};

RadCalendar.prototype.SerializeSelectedDates = function()
{
	var output = "[";
	var selectedDates = this.Selection.SelectedDates.GetValues();
	for (var i = 0; i < selectedDates.length; i++)
	{	
		if (selectedDates[i])
		{		    
		    output += "[" + selectedDates[i][0] + "," + selectedDates[i][1] + "," + selectedDates[i][2] + "],";
		}
	}

	if (output.length > 1)
	{
		output = output.substring(0, output.length - 1);
	}
	output += "]";
	
	if (this.SelectedDatesHidden() != null)
		this.SelectedDatesHidden().value = output;
};

RadCalendar.prototype.SelectedDatesHidden = function()
{
	return document.getElementById(this.ClientID + "_SD");
};

RadCalendar.prototype.SerializeAuxDates = function()
{
	var output = "[[" + this.RangeMinDate + "],[" + this.RangeMaxDate + "],[" + this.FocusedDate + "]]";
	
	if (this.AuxDatesHidden() != null)
		this.AuxDatesHidden().value = output;
};

RadCalendar.prototype.AuxDatesHidden = function()
{
	return document.getElementById(this.ClientID + "_AD");
};

RadCalendar.prototype.GetPostData = function()
{
	var element;
    var postData = "";
	var eventValidationData = "";
	
    for (var i = 0; i < document.forms[0].elements.length; i++)
    {
		element = document.forms[0].elements[i];
        var tagName = element.tagName.toLowerCase();
        if (tagName == "input")
        {
			if ("__EVENTVALIDATION" == element.id)
			{
				eventValidationData = (element.name + "=" + this.EncodePostData(element.value) + "&");
				continue;
			}
			
            var type = element.type;
            if (type == "text" || type == "hidden" || type == "password" ||
                ((type == "checkbox" || type == "radio") && element.checked))
            {
                postData += element.name + "=" + this.EncodePostData(element.value) + "&";
            }
        }
        else if (tagName == "select")
        {
            var selectCount = element.childNodes.length;
            for (var j = 0; j < selectCount; j++)
            {
                var selectChild = element.childNodes[j];
                
                if (selectChild.tagName 
					&& (selectChild.tagName.toLowerCase() == "option") 
					&& (selectChild.selected == true))
                {
                    postData += element.name + "=" + this.EncodePostData(selectChild.value) + "&";
                }
            }
        }
        else if (tagName == "textarea")
        {
            postData += element.name + "=" + this.EncodePostData(element.value) + "&";
        }
    }
    
    postData += eventValidationData;    
    return postData;
};

RadCalendar.prototype.EncodePostData = function(value)
{
	if (encodeURIComponent)
    {
        return encodeURIComponent(value);
    }
    else
    {
        return escape(value);
    }
};

RadCalendar.prototype.Submit = function(eventArgument)
{
	switch (this.AutoPostBack)
	{			
		case 1:	//Server
			this.DoPostBack(eventArgument);
			break;				
		
		case 0: // Client
			this.ExecClientAction(eventArgument);
			break;
	}
};

RadCalendar.prototype.CalculateDateFromStep = function(step)
{
	/* SINGLE VIEW ONLY */
	var view = this.CurrentViews[0];
	if (!view)
		return;
		
	var date = (step < 0 ? view._MonthStartDate : view._MonthEndDate);	
	date = this.DateTimeFormatInfo.Calendar.AddDays(date, step);
    return date;
};

RadCalendar.prototype.DeserializeNavigationArgument = function(eventArgument)
{
    var args = eventArgument.split(":");
    return args;
};

RadCalendar.prototype.ExecClientAction = function(eventArgument)
{
	var args = eventArgument.split(":");
	switch (args[0])
	{
		case "d":
			break;
			
		case "n":
		    if (!this.CurrentViews[0].IsMultiView)
		    {
		        var step = parseInt(args[1], 0);
			    var type = parseInt(args[2], 0);
			
			    this.MoveByStep(step, type);
		    }
			break;
			
		case "nd":
			var date = [parseInt(args[1]), parseInt(args[2]), parseInt(args[3])];			
			this.MoveToDate(date);
			break;
	}
};

RadCalendar.prototype.MoveByStep = function(step, type)
{
	/* SINGLE VIEW ONLY */
	
	var view = this.CurrentViews[0];
	if (!view)
		return;
		
	var date = (step < 0 ? view._MonthStartDate : view._MonthEndDate);	

	date = this.DateTimeFormatInfo.Calendar.AddMonths(date, step);
	if (!this.RangeValidation.IsDateValid(date))
	{
		if (step > 0)
		{
			date = [this.RangeMaxDate[0], this.RangeMaxDate[1], this.RangeMaxDate[2]];
		}
		else
		{
		    // get the first valid date (i.e. RangeMinDate + one day)
			var firstValidDate = new Date(this.RangeMinDate[0], (this.RangeMinDate[1] - 1), (this.RangeMinDate[2] + 1))
			date = [firstValidDate.getFullYear(), (firstValidDate.getMonth() + 1), firstValidDate.getDate()];
		}
	}
	
	if (step != 0)
		this.MoveToDate(date);
};

RadCalendar.prototype.MoveToDate = function(date, forceRefresh)
{
	if (typeof(forceRefresh) == "undefined")
	{
	    forceRefresh = false;
	}
	
	/* SINGLE VIEW ONLY */
	if (!this.RangeValidation.IsDateValid(date))
	{
	    date = this.GetBoundaryDate(date);
		if (date == null)
	    {
	        alert(this.GetFastNavigation().DateIsOutOfRangeMessage);
	        return;
	    }
	}
	
	var oldFocusedDate = this.FocusedDate;
	this.FocusedDate = date;
	
	date[2] = oldFocusedDate[2] = 1; // prevent view scrolling when in the same month
	var scrollDir = this.RangeValidation.CompareDates(date, oldFocusedDate);
	if (scrollDir == 0 && !forceRefresh)
	{
		return;
	}
	
	var topViewID = this.ViewIDs[0];
	var isParentView = false;
	
	this.DisposeView(topViewID);
	
	var view = new RadCalendarNamespace.RadCalendarView(this
		, document.getElementById(topViewID)
		, topViewID
		, isParentView ? this.MultiViewColumns : this.SingleViewColumns
		, isParentView ? this.MultiViewRows : this.SingleViewRows
		, isParentView		
		, this.UseRowHeadersAsSelectors
		, this.UseColumnHeadersAsSelectors
		, this.Orientation
		, date);
	this.CurrentViews[this.CurrentViews.length] = view;
	
	view.ScrollDir = scrollDir;
	view.RenderDaysSingleView();
};

RadCalendar.prototype.CheckRequestConditions = function(eventArgument)
{
	var args = this.DeserializeNavigationArgument(eventArgument);
	var step = 0;
	var DateToNavigate = null;
	if(args[0] != "d")
	{
		if (args[0] == "n")
	    {
	        step = parseInt(args[1], 0);
	        DateToNavigate = this.CalculateDateFromStep(step);
        }
        else if (args[0] == "nd")
        {
            DateToNavigate = [parseInt(args[1]),parseInt(args[2]),parseInt(args[3])];
        }

	    if (!this.RangeValidation.IsDateValid(DateToNavigate))
	    {
	        DateToNavigate = this.GetBoundaryDate(DateToNavigate);
		    if (DateToNavigate == null)
	        {
	            alert(this.GetFastNavigation().DateIsOutOfRangeMessage);
	            return false;
	        }
	    }
	}
	
	return true;
}

RadCalendar.prototype.DoPostBack = function(eventArgument)
{
	if (this.CheckRequestConditions(eventArgument))
	{
		var postbackCall = this.PostBackCall.replace("@@", eventArgument)
		
		if (this.postbackAction != null)
		    window.clearTimeout(this.postbackAction);
		
		var calendar = this;
		this.postbackAction = window.setTimeout(function(){
		                    calendar.postbackAction = null;
		                    eval(postbackCall);
		                   }, 200);
	
	}
};

RadCalendar.prototype.NavigateToDate = function(date)
{
	if (!this.RangeValidation.IsDateValid(date))
	{
		date = this.GetBoundaryDate(date);
		if (date == null)
	    {
	        alert(this.GetFastNavigation().DateIsOutOfRangeMessage);
	        return;
	    }
	}

	var step = this.GetStepFromDate(date);	
	this.Navigate(step);	
	//this.Submit("nd:" + date.join(":"));
};

RadCalendar.prototype.GetStepFromDate = function(date)
{
	var year = date[0] - this.FocusedDate[0];
	var month = date[1] - this.FocusedDate[1];

	var step = year*12 + month;
	return step;
}

RadCalendar.prototype.GetBoundaryDate = function(date)
{
	if (!this.RangeValidation.IsDateValid(date))
	{
        if(this.IsInSameMonth(date,this.RangeMinDate))
        {
            return [this.RangeMinDate[0], this.RangeMinDate[1], this.RangeMinDate[2]];
        }
        if(this.IsInSameMonth(date,this.RangeMaxDate))
        {
            return [this.RangeMaxDate[0], this.RangeMaxDate[1], this.RangeMaxDate[2]];
        }
        return null;
	}
	return date;
};

RadCalendar.prototype.Navigate = function(step)
{
	if (this.RaiseEvent("OnCalendarViewChanging", step) == false)
	{
		return;
	}
	
	this.navStep = step;
	
	this.Submit("n:" + step);
	this.SerializeAuxDates();	
	
	this.RaiseEvent("OnCalendarViewChanged", step);
};

RadCalendar.prototype.FastNavigatePrev = function()
{
	var topView = this.FindView(this.TopViewID);
	var months = (-this.FastNavigationStep) * topView.MonthsInView;
	this.Navigate(months);
	return false;
};

RadCalendar.prototype.NavigatePrev = function()
{
	var topView = this.FindView(this.TopViewID);
	this.Navigate(-topView.MonthsInView);
	return false;
};

RadCalendar.prototype.NavigateNext = function()
{
	var topView = this.FindView(this.TopViewID);
	this.Navigate(topView.MonthsInView);
	return false;
};

RadCalendar.prototype.FastNavigateNext = function()
{
	var topView = this.FindView(this.TopViewID);
	var months = this.FastNavigationStep * topView.MonthsInView;
	this.Navigate(months);
	return false;
};

/////////////////////////////////////////////////
// Date operations
//

RadCalendar.prototype.GetRenderDayID = function(date)
{
	//d_YYYY_MM_DD
	return (this.ClientID + "_" + date.join("_"));
};

RadCalendar.prototype.IsInSameMonth = function(date1, date2)
{
	if (!date1 || date1.length != 3)
		throw new Error("Date1 must be array: [y, m, d]");
		
	if (!date2 || date2.length != 3)
		throw new Error("Date2 must be array: [y, m, d]");

	var y1 = date1[0];
	var y2 = date2[0];	
	
	if (y1 < y2) 
		return false;
	if (y1 > y2) 
		return false;
	
	var m1 = date1[1];
	var m2 = date2[1];	
	
	if (m1 < m2) 
		return false;
	if (m1 > m2) 
		return false;
	
	return true;
};

RadCalendar.prototype.GetFastNavigation = function()
{
	var fastMonthYearNav = this.MonthYearFastNav;
	if (!fastMonthYearNav)
	{
        // get the first valid date (i.e. RangeMinDate + one day)
		var firstValidJsDate = new Date(this.RangeMinDate[0], (this.RangeMinDate[1] - 1), (this.RangeMinDate[2] + 1))
		var firstValidDate = [firstValidJsDate.getFullYear(), (firstValidJsDate.getMonth() + 1), firstValidJsDate.getDate()];
	
		fastMonthYearNav = new RadCalendarNamespace.MonthYearFastNavigation(this.DateTimeFormatInfo.AbbreviatedMonthNames
			, firstValidDate
			, this.RangeMaxDate
			, this.Skin
			, this.ClientID
			, this.MonthYearNavigationSettings);
			
		this.MonthYearFastNav = fastMonthYearNav;
	}
	
	return this.MonthYearFastNav;
}

RadCalendar.prototype.ShowMonthYearFastNav = function(e)
{
	if (!e)
		e = window.event;

    this.EnableNavigation(this.IsNavigationEnabled());	
	
	if(this.IsMonthYearNavigationEnabled())
	{
	    this.GetFastNavigation().Show(this.GetPopup()
		    , RadHelperUtils.MouseEventX(e) //e.clientX
		    , RadHelperUtils.MouseEventY(e) //e.clientY
		    , this.FocusedDate[1]
		    , this.FocusedDate[0]
		    , RadCalendarUtils.AttachMethod(this.MonthYearFastNavExitFunc, this)
		    , this.ItemStyles["FastNavigationStyle"]
	    );
	}
	
	e.returnValue = false;
	e.cancelBubble = true;
	if (e.stopPropagation)
		e.stopPropagation();
	
    if (!document.all)
    {
	    window.setTimeout (function() { try { document.getElementsByTagName("INPUT")[0].focus(); } catch(ex) { } }, 1);
    }
    
	return false;
};

RadCalendar.prototype.GetPopup = function()
{
	var popup = this.Popup;
	if (!popup)
	{
		popup = new RadCalendarNamespace.Popup();
		this.Popup = popup;
	}
	return popup;	
};

RadCalendar.prototype.MonthYearFastNavExitFunc = function(year, month, date)
{
	if (!date || !this.EnableTodayButtonSelection)
	{
	    this.NavigateToDate([year, month + 1, 1]);
	}
	else // Today clicked and should select
	{
	    this.UnselectDate([year, month + 1, date]);
		this.SelectDate([year, month + 1, date], true);
    }
};

RadCalendar.prototype.GetRangeMinDate = function()
{
    return this.RangeMinDate;
}

RadCalendar.prototype.SetRangeMinDate = function(date)
{
	if (this.RangeValidation.CompareDates(date, this.RangeMaxDate) > 0)
    {
		alert("RangeMinDate should be less than the RangeMaxDate value!");
		return;
    }
    var oldMinDate = this.RangeMinDate;
    this.RangeMinDate = date;
    this.RangeValidation.RangeMinDate = date;
    this.MonthYearFastNav = null;
    
    var focusedMonthDate = [this.FocusedDate[0], this.FocusedDate[1], 1];
    if (this.RangeValidation.CompareDates(focusedMonthDate, this.RangeMinDate) <= 0 
        || this.RangeValidation.InSameMonth(focusedMonthDate, oldMinDate)
        || this.RangeValidation.InSameMonth(focusedMonthDate, this.RangeMinDate))
    {
        if (!this.RangeValidation.IsDateValid(this.FocusedDate))
        {
            var newFocusedDate = new Date();
            newFocusedDate.setFullYear(date[0], date[1] - 1, date[2] + 1);
            this.FocusedDate = [newFocusedDate.getFullYear(), newFocusedDate.getMonth() + 1, newFocusedDate.getDate()];        
        }
        
        this.MoveToDate(this.FocusedDate, true);
    }
    
    this.SerializeAuxDates(); 
    this.UpdateSelectedDates();  
}

RadCalendar.prototype.GetRangeMaxDate = function()
{
    return this.RangeMaxDate;
}

RadCalendar.prototype.SetRangeMaxDate = function(date)
{
	if (this.RangeValidation.CompareDates(date, this.RangeMinDate) < 0)
    {
		alert("RangeMaxDate should be greater than the RangeMinDate value!");
		return;
    }
    var oldMaxDate = this.RangeMaxDate;
    this.RangeMaxDate = date;
    this.RangeValidation.RangeMaxDate = date;
    this.MonthYearFastNav = null;
    
    var focusedMonthDate = [this.FocusedDate[0], this.FocusedDate[1], 1];
    if (this.RangeValidation.CompareDates(focusedMonthDate, this.RangeMaxDate) > 0
        || this.RangeValidation.InSameMonth(focusedMonthDate, oldMaxDate)
        || this.RangeValidation.InSameMonth(focusedMonthDate, this.RangeMaxDate))
    {
        if (!this.RangeValidation.IsDateValid(this.FocusedDate))
        {
            var newFocusedDate = new Date();
            newFocusedDate.setFullYear(date[0], date[1] - 1, date[2] - 1);
            this.FocusedDate = [newFocusedDate.getFullYear(), newFocusedDate.getMonth() + 1, newFocusedDate.getDate()];        
        }
        this.MoveToDate(this.FocusedDate, true);
    }
    
    this.SerializeAuxDates();
    this.UpdateSelectedDates();
}

RadCalendar.prototype.UpdateSelectedDates = function()
{
    var selectedDates = this.GetSelectedDates();
    for (var i=0; i<selectedDates.length; i++)
    {
        if (!this.RangeValidation.IsDateValid(selectedDates[i]))
        {
            this.Selection.Remove(selectedDates[i]);
        }
    }    
}

//HACK: Popup does not need to be inside RadCalendar, but customers are using it.  
//Keep the original name
if (typeof(RadCalendarNamespace.Popup) != "undefined")
{
	RadCalendar.Popup = RadCalendarNamespace.Popup;
};if (typeof(window.RadControlsNamespace) == "undefined")
{
	window.RadControlsNamespace = new Object();
};

RadControlsNamespace.AppendStyleSheet = function(callback, clientID, pathToCssFile)
{
    if (!pathToCssFile)
    {
        return;
    }

    var isGecko = window.netscape && !window.opera;
    if (!callback && isGecko)
    {
        //immediate css loading for Gecko
        document.write("<" + "link" + " rel='stylesheet' type='text/css' href='" + pathToCssFile + "' />");
    }
    else
    {
        var linkObject = document.createElement("link");
        linkObject.rel = "stylesheet";
        linkObject.type = "text/css";
        linkObject.href = pathToCssFile;
        document.getElementsByTagName("head")[0].appendChild(linkObject);
    }
};;var RadCalendarUtils = 
{
    COLUMN_HEADER	: 1,
    VIEW_HEADER	: 2,
    ROW_HEADER	: 3,

    FIRST_DAY : 0,
    FIRST_FOUR_DAY_WEEK : 2,
    FIRST_FULL_WEEK : 1,
    
    DEFAULT : 7,
    FRIDAY : 5,
    MONDAY : 1,
    SATURDAY : 6,
    SUNDAY : 0,
    THURSDAY : 4,
    TUESDAY : 2,
    WEDNESDAY : 3,

    RENDERINROWS : 1,
    RENDERINCOLUMNS : 2,
    NONE : 4,
	
	RECURRING_DAYINMONTH : 1,
	RECURRING_DAYANDMONTH: 2,    
	RECURRING_WEEK : 4,
	RECURRING_WEEKANDMONTH: 8,
	RECURRING_TODAY : 16,
	RECURRING_NONE : 32
}


RadCalendarUtils.AttachMethod = function(method, object)
{
	return function() 
	{	
		return method.apply(object, arguments); 
	};
};

RadCalendarUtils.DateCollection = function()
{
	this.Initialize();
}

RadCalendarUtils.DateCollection.prototype.Initialize = function(ItemKey)
{
   this.Container = {};
}

RadCalendarUtils.DateCollection.prototype.GetStringKey = function(itemKey)
{
	return itemKey.join("-");
}

RadCalendarUtils.DateCollection.prototype.Add = function(itemKey, inputObject)
{
    if (!itemKey || !inputObject)
    {
        return;
    }
       
    var stringKey = this.GetStringKey(itemKey);
    
    this.Container[stringKey] = inputObject;
}

RadCalendarUtils.DateCollection.prototype.Remove = function(itemKey)
{
	if(!itemKey)
	{
		return;
	}
	
	var stringKey = this.GetStringKey(itemKey);

	if(this.Container[stringKey] != null)
	{
		this.Container[stringKey] = null;
		delete this.Container[stringKey];
	}
}

RadCalendarUtils.DateCollection.prototype.Clear = function()
{
	this.Initialize();
}

RadCalendarUtils.DateCollection.prototype.Get = function(itemKey)
{
    if(!itemKey)
	{
		return;
	}
    
	var stringKey = this.GetStringKey(itemKey);
    
    if(this.Container[stringKey] != null)
    {
        return this.Container[stringKey];
    }
    else
    {
        return null;
    }
}

RadCalendarUtils.DateCollection.prototype.GetValues = function()
{
	var result = []
	for (var key in this.Container)
	{
		if (key.indexOf("-") == -1)
		    continue;
		    
		result[result.length] = this.Container[key];
	}
	return result;
}

RadCalendarUtils.DateCollection.prototype.Count = function()
{
    return this.GetValues().length;
}

RadCalendarUtils.GetDateFromId = function (id)
{
	var arr = id.split("_");
	if (arr.length < 2)
		return null;
		
	var date = [ parseInt(arr[arr.length - 3])
				, parseInt(arr[arr.length - 2])
				, parseInt(arr[arr.length - 1]) ];	

	return date;		
}

RadCalendarUtils.GetRenderDay = function(thisObj, dayId)
{
    var processedDate = RadCalendarUtils.GetDateFromId(dayId);
    var processedDay = thisObj.RenderDays.Get(processedDate);
    
    return processedDay;
}

RadCalendarUtils.FindTarget = function(e, clientID) 
{ 
    var target; 
    
    if (e && e.target) 
    { 
        target = e.target; 
    } 
    else if (window.event && window.event.srcElement) 
    { 
        target = window.event.srcElement; 
    }

    if (!target) 
    { 
        return null; 
    } 
    if (target.tagName == null && target.nodeType == 3 && (navigator.userAgent.match(/Safari/)))
    {
        target = target.parentNode;
    }
    while (target != null && target.tagName.toLowerCase() != 'body')
    {      
        if (target.tagName.toLowerCase() == 'td' && 
            RadCalendarUtils.FindTableElement(target) != null && 
            RadCalendarUtils.FindTableElement(target).id.indexOf(clientID) != -1)
        {
            break;
        }
        
        target = target.parentNode; 
    }
    
    if (target.tagName == null || target.tagName.toLowerCase() != 'td')
    { 
        return null; 
    } 
    
    return target;
}

RadCalendarUtils.FindTableElement = function(htmlElement)
{
    while (htmlElement != null && htmlElement.tagName.toLowerCase() != 'table')
    {
        htmlElement = htmlElement.parentNode;
    }
    
    return htmlElement;
}

RadCalendarUtils.GetElementPosition = function(el) 
{  
    var parent = null;
    var pos = {x: 0, y: 0};
    var box;

    if (el.getBoundingClientRect) 
    { 
		// IE
        box = el.getBoundingClientRect();
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

        pos.x = box.left + scrollLeft - 2;
        pos.y = box.top + scrollTop - 2;
        
        return pos;
    }
    else if (document.getBoxObjectFor) 
    { 
		// gecko
        box = document.getBoxObjectFor(el);
        pos.x = box.x - 2;
        pos.y = box.y - 2;
    }
    else 
    { 
		// safari/opera
        pos.x = el.offsetLeft;
        pos.y = el.offsetTop;
        parent = el.offsetParent;
        if (parent != el)
        {
			while (parent) 
			{
				pos.x += parent.offsetLeft;
				pos.y += parent.offsetTop;
				parent = parent.offsetParent;
			}
        }
    }


	if (window.opera)
	{
		parent = el.offsetParent;
		
		while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
		{
			pos.x -= parent.scrollLeft;
			pos.y -= parent.scrollTop;
			parent = parent.offsetParent;
		}
	}
	else
	{
		parent = el.parentNode; 
		while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
		{
			pos.x -= parent.scrollLeft;
			pos.y -= parent.scrollTop;

			parent = parent.parentNode;
		}
    }

	return pos;
};

RadCalendarUtils.MergeStyles = function(dayRenderStyle, defaultCellStyle)
{
    if (dayRenderStyle.lastIndexOf(";", dayRenderStyle.length) != dayRenderStyle.length - 1)
    {
        dayRenderStyle += ";";
    }
    
    var defaultStyleAttributes = defaultCellStyle.split(";");
    var resultStyle = dayRenderStyle;
    // omit the last array element (empty string from splitting)   
    for (var i=0; i < defaultStyleAttributes.length - 1; i++)
    {        
        var splitAttributes = defaultStyleAttributes[i].split(":");
        if (dayRenderStyle.indexOf(splitAttributes[0]) == -1)
        {
            resultStyle += defaultStyleAttributes[i] + ";";
        }
    }
        
    return resultStyle;
}

RadCalendarUtils.MergeClassName = function (newClassName, defaultClassName)
{	
	var p = defaultClassName.split(" ");
	if (p.length == 1 && p[0] == "")
	{
		p = [];
	}

	var l = p.length;
	for (var i = 0; i < l; i++)
	{
		if (p[i] == newClassName)
		{
			return defaultClassName;
		}
	}
	p[p.length] = newClassName;	
	return p.join(" ");
};;function RadDate()
{	
	this.Year	= 0;
	this.Month	= 0;
	this.Date	= 0;
	
	switch (arguments.length)
	{
		case 0:
			break;
			
		case 1:
			var date = arguments[0];
			if (date.getDate)
			{	
				// js Date object
				this.Year = date.getFullYear();
				this.Month = date.getMonth() + 1;
				this.Date = date.getDate();
			}			
			else if (date.CompareTo)
			{
				// RadDate
				this.Year	= date.Year;
				this.Month	= date.Month;
				this.Date	= date.Date;
			}
			else if (3 == date.length)
			{
				// array
				this.Year	= date[0];
				this.Month	= date[1];
				this.Date	= date[2];
			}
			else
			{
				throw { description : "RadDate error: Unsupported input format" };
			}
			break;
			
		case 3:
			// new RadDate(year, month, date)
			this.Year	= arguments[0];
			this.Month	= arguments[1];
			this.Date	= arguments[2];
			break;
			
		default:
			throw { description : "RadDate error: Unsupported input format" };
			break;
	}
	return this;
}

//	Returns:
//		< 0 : this instance is less then date
//		= 0	: this instance is equal to date
//		> 0 : this instance is greater then date
RadDate.prototype.CompareTo = function(date)
{
	if (!date || !date.CompareTo)
		return 1;
			
	var y1 = this.Year;
	var y2 = date.Year;	
	
	if (y1 < y2) 
		return -1;
	if (y1 > y2) 
		return 1;
	
	var m1 = this.Month;
	var m2 = date.Month;	
	
	if (m1 < m2) 
		return -1;
	if (m1 > m2) 
		return 1;
	
	var d1 = this.Date;
	var d2 = date.Date;
	
	if (d1 < d2) 
		return -1;		
	if (d1 > d2) 
		return 1;
	
	return 0;
};

RadDate.prototype.Equals = function(date)
{
	return (0 == this.CompareTo(date));
};

// Returns true if this instance is in [minDate, maxDate]
RadDate.prototype.IsInRange = function(minDate, maxDate)
{
	return (this.CompareTo(minDate) >= 0 
			&& this.CompareTo(maxDate) <= 0);
};

RadDate.prototype.ToString = function()
{
	if (0 == arguments.length)
	{
		return (this.Year + "-" + this.Month + "-" + this.Date);
	}
};

// Returns "d_yyyy_mm_dd"
RadDate.prototype.ToIDString = function()
{
	return ("d_" + this.Year + "_" + this.Month + "_" + this.Date);
};

RadDate.prototype.Add = function()
{
	switch (arguments.length)
	{
		case 1:
			var value = arguments[0];
			if (3 == value.length)
			{
				this.Year += value[0];
				this.Month += value[1];
				this.Date += value[2];
			}
			break;
			
		case 3:
			this.Year += arguments[0];
			this.Month += arguments[1];
			this.Date += arguments[2];
			break;
	}
	return this;
};

RadDate.prototype.Subtract = function()
{
	switch (arguments.length)
	{
		case 1:
			var value = arguments[0];
			if (3 == value.length)
			{
				this.Year -= value[0];
				this.Month -= value[1];
				this.Date -= value[2];
			}
			break;
			
		case 3:
			this.Year -= arguments[0];
			this.Month -= arguments[1];
			this.Date -= arguments[2];
			break;
	}
	return this;
};

RadDate.prototype.FormatDate = function(formatInfo)
{
};;if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

function RadDatePicker(clientID)
{
	RadDatePicker.DisposeOldInstance(clientID);
	this.ClientID = clientID;
}

RadDatePicker.InitializeDateInput = function(datePicker)
{
    if (datePicker != null && datePicker.InitializeDateInput != null)
    {
        datePicker.InitializeDateInput();
    }
}

RadDatePicker.DisposeOldInstance = function(clientID)
{
	try
	{
		var oldInstance = window[clientID];
		if (oldInstance != null && !oldInstance.tagName)
		{
			oldInstance.Dispose();
			window[clientID] = null;
		}
	}
	catch(e)
	{}
}

RadDatePicker.PopupInstances = {};
RadDatePicker.prototype = 
{
    Initialize : function(configurationObject)
    {
	    this.LoadConfiguration(configurationObject);
	    this.SetUpJavascriptDates();
    	
	    this.SetUpClientEvents();
	    RadControlsNamespace.EventMixin.Initialize(this);
    	
        this.InitializeDateInput();
        
        if (navigator.userAgent.match(/Safari/))
        {
            var calendarWrapper = document.getElementById(this.CalendarID + "_wrapper");
            calendarWrapper.style.display = "";
            calendarWrapper.style.visibility = "hidden";
            calendarWrapper.style.position = "absolute";
            calendarWrapper.style.left = "-1000px";
        }
    		
	    this.CalendarSelectionInProgress = false;
	    this.InputSelectionInProgress = false;
    	
	    var picker = this;
	    RadHelperUtils.AttachEventListener(window, "unload", function()
		    {
			    try
			    {
			        picker.Dispose();
			    }
			    catch(e)
			    {
			    }
		    });
    },
    
    InitializeDateInput : function()
    {
        if (this.DateInput != null)
            return;

        var childInput = window[this.DateInputID];
        if (childInput != null && childInput.Owner == null)
        {
            childInput.Owner = this;
            
	        this.SetValidationInput();
	        this.SetDateInput();
	        this.InitializePopupButton();
	    }
    },

    Dispose : function()
    {
	    if (!this.disposed)
	    {
		    this.disposed = true;
    		
		    if (this.selectedAction != null)
	            window.clearTimeout(this.selectedAction);
    		
		    if (this.PopupInstance != null)
		    {
			    this.PopupInstance.Hide();
			    this.PopupInstance = null;
		    }
    		
		    for (var clientEvent in this.ClientEvents)
		    {
			    this[clientEvent] = null;
		    }
		    this.ClientEvents = null;
    		
		    this.ValidationInput = null;
    		
		    this.DateInput = null;
    		
		    var popupImage = this.popupImage()
		    if (popupImage != null)
		    {
			    popupImage.onmouseover = null;
			    popupImage.onmouseout = null;
		    }
    		
		    if (this.PopupButton != null)
		    {
			    this.PopupButton.onmouseover = null;
			    this.PopupButton.onmouseout = null;
			    this.PopupButton.onclick = null;
    			
			    this.PopupButton = null;
		    }
    		
		    if (this.Calendar != null)
			    this.Calendar.Dispose();
		    this.Calendar = null;
	    }
    },

    SetUpJavascriptDates : function()
    {
	    this.MinDate = new Date(this.MinDate[0], this.MinDate[1] - 1, this.MinDate[2]);
	    this.MaxDate = new Date(this.MaxDate[0], this.MaxDate[1] - 1, this.MaxDate[2]);
	    this.FocusedDate = new Date(this.FocusedDate[0], this.FocusedDate[1] - 1, this.FocusedDate[2]); 
    },

    LoadConfiguration : function (configurationObject)
    {
        for (var property in configurationObject)
        {
            this[property] = configurationObject[property];
        }
    },

    SetUpClientEvents : function()
    {
	    for (var clientEvent in this.ClientEvents)
        {
		    if (!this.ClientEvents.hasOwnProperty(clientEvent) )
		    {
			    continue;
		    }
		    else if (clientEvent == "TypingTimeOut")
		    {
		        this.TypingTimeOut = this.ClientEvents[clientEvent];
		        continue;
		    }
    		
		    this[clientEvent] = eval(this.ClientEvents[clientEvent]);
        }
    },

    SetValidationInput : function()
    {
	    this.ValidationInput = document.getElementById(this.ClientID);
    },

    SetDateInput : function()
    {
	    this.DateInput = window[this.DateInputID];
	    var picker = this;

	    this.DateInput.AttachEvent("OnValueChanged", 
	                                function(source, args)
		                            { 
			                            picker.OnDateInputDateChanged(source, args);

			                            if (picker.selectedAction != null)
                                            window.clearTimeout(picker.selectedAction);
                                		 
                                        var selectionTimeout = picker.TypingTimeOut; 
                                        if (picker.CalendarSelectionInProgress || picker.ProgramaticSelectionInProgress)
                                        {
                                            selectionTimeout = 0;
                                        }
                                        
                                        picker.selectedAction = window.setTimeout(function()
                                                                                  {
                                                                                      picker.selectedAction = null;
                                                                                      picker.RaiseEvent("OnDateSelected", args);		
                                                                                  }, selectionTimeout);
		                            });
    },

    SetCalendar : function(calendarID)
    {
	    if (calendarID != null)
		    this.CalendarID = calendarID;
    		
	    this.Calendar = window[this.CalendarID];
    	
	    var picker = this;
	    this.Calendar.OnDateSelected = function(calendarInstance, renderDay)
		    {
			    picker.CalendarDateSelected(renderDay);
		    };
    },

    GetCalendar : function()
    {
	    if (this.Calendar == null)
		    this.SetCalendar();
	    return this.Calendar;
    },

    GetPopupContainer : function()
    {
	    if (this.PopupContainer == null)
		    this.PopupContainer = document.getElementById(this.PopupContainerID);
	    return this.PopupContainer;
    },

    popupImage : function()
    {
	    var popupImage = null;
    	
	    if (this.PopupButton != null)
	    {
		    var images = this.PopupButton.getElementsByTagName("img");
		    if (images.length > 0)
			    popupImage = images[0];
	    }
    	
	    return popupImage;
    },

    InitializePopupButton : function()
    {
	    this.PopupButton = document.getElementById(this.PopupControlID);
	    if (this.PopupButton != null)
	    {
		    this.AttachPopupButtonEvents();
	    }
    },

    AttachPopupButtonEvents : function()
    {
	    var popupImage = this.popupImage();
	    var picker = this;
	    if (popupImage != null)
	    {
		    if (!this.HasEventHandlerAttribute("onmouseover"))
		    {
			    popupImage.onmouseover = function() 
				    {
					    this.src = picker.PopupButtonSettings.ResolvedHoverImageUrl;
				    };
		    }
    				
		    if (!this.HasEventHandlerAttribute("onmouseout"))		
		    {
			    popupImage.onmouseout = function() 
				    {
					    this.src = picker.PopupButtonSettings.ResolvedImageUrl;
				    };
		    }
	    }
    	
	    if (!this.HasEventHandlerAttribute("onclick"))		
	    {
		    this.PopupButton.onclick = function() 
			    {
				    picker.TogglePopup();
				    return false;
			    };
	    }
    },

    HasEventHandlerAttribute : function(eventName)
    {
	    return this.PopupButton.getAttribute(eventName);
    },

    GetTextBox : function()
    {
	    return document.getElementById(this.DateInputID + "_text");
    },

    popup : function()
    {
	    var currentPopup = RadDatePicker.PopupInstances[this.CalendarID];
    	
	    if (!currentPopup)
        {
            currentPopup = new RadCalendar.Popup();
            RadDatePicker.PopupInstances[this.CalendarID] = currentPopup;
        }
        
        return currentPopup;
    },

    GetPopupVisibleControls : function()
    {
	    var excludeList = [this.GetTextBox(), this.GetPopupContainer()];
        if (this.PopupButton != null)
        {
		    excludeList[excludeList.length] = this.PopupButton;
        }
        return excludeList;
    },

    TogglePopup : function()
    {
	    if (this.IsPopupVisible())
	    {
		    this.HidePopup();
	    }
	    else
	    {		
		    this.ShowPopup();
	    }
	    return false;
    },

    IsPopupVisible : function()
    {
	    return this.popup().IsVisible() && 
			    (this.popup().Opener == this);
    },

    ShowPopup : function(x, y)
    {   
	    this.SetCalendar();
    	   
	    if (this.IsPopupVisible())
		    return;
    				
	    var textbox = this.GetTextBox();
    	
	    if (typeof(x) == "undefined" || typeof(y) == "undefined")
	    {
		    var pos = this.GetElementPosition(textbox);
		    x = pos.x;
		    y = pos.y + textbox.offsetHeight;
	    }
    		
	    this.popup().ExcludeFromHiding = this.GetPopupVisibleControls();

	    this.HidePopup();
    	
	    var synchronizeCalendar = true;
	    if (this.RaiseEvent("OnPopupUpdating", null) == false)
	    {
		    synchronizeCalendar = false;		
	    }

	    this.popup().Opener = this;
	    this.popup().Show(x, y, this.GetPopupContainer());

	    if (synchronizeCalendar == true)
	    {
		    var inputDate = this.DateInput.GetDate();
		    if (this.IsEmpty())
		    {
			    this.FocusCalendar();
		    }
		    else
		    {
			    this.SetCalendarDate(inputDate);
		    }
	    }
    },

    // even in a try / catch block there is a "Permission denied to set property XULElement.selectedIndex" exception in Mozilla
    //FocusFirstSelectableDay : function()
    //{
    //    var popupElement = this.GetPopupContainer();
    //    var links = popupElement.getElementsByTagName('A');
    //    var firstLink = links[0];
    //    for (var i = 0; i < links.length; i++)
    //    {
    //        //focus on the first day of the month
    //        var dayNumber = parseInt(links[i].innerHTML);
    //        if (!isNaN(dayNumber))
    //        {
    //            firstLink = links[i];
    //            break;
    //        }
    //    }
    //    
    //    window.setTimeout(function()
    //        {
    //            try{
    //            firstLink.focus();
    //            }
    //            catch(e){}
    //        }, 0);   
    //},

    IsEmpty : function()
    {
	    return this.DateInput.IsEmpty();
    },

    HidePopup : function()
    {
	    if (this.popup().IsVisible())
	    {
		    this.popup().Hide();
		    this.popup().Opener = null;
		    this.GetCalendar().UnselectDates(this.GetCalendar().GetSelectedDates());		
	    }
    },

    SetDate : function(newDate)
    {
	    this.ProgramaticSelectionInProgress = true;
	    this.DateInput.SetDate(newDate);
	    this.ProgramaticSelectionInProgress = false;
    },

    GetDate : function()
    {
	    return this.DateInput.GetDate();
    },

    GetElementDimensions : function(element)
    {
	    var left = element.style.left;
	    var display = element.style.display;

	    element.style.left = "-10000px";
	    element.style.display = "";

	    var height = element.offsetHeight;
	    var width  = element.offsetWidth;
    	
	    element.style.left = left;
	    element.style.display = display;

	    return {width : width, height : height};
    },

    CalendarDateSelected : function(renderDay)
    {     
	    if (this.InputSelectionInProgress == true)// || renderDay.IsSelected == false)
		    return;
    		    
        if (renderDay.IsSelected)
        {
            var date = this.GetJavaScriptDate(renderDay.Date);
            
            this.CalendarSelectionInProgress = true;
            this.SetInputDate(date);
            this.CalendarSelectionInProgress = false;
        }
        
        if (this.Calendar.MonthYearFastNav && this.Calendar.MonthYearFastNav.Popup.IsVisible())
		    this.Calendar.MonthYearFastNav.Popup.Hide(false);
        
	    this.HidePopup();
    },
    
    SetInputDate : function(date)
    {
        this.DateInput.SetDate(date);
    },
    
    GetJavaScriptDate : function(dateArray)
    {
        var date = new Date();
        date.setFullYear(dateArray[0], dateArray[1] - 1, dateArray[2]);
        
        return date;
    },

    OnDateInputDateChanged : function(dateInput, args)
    {
	    this.SetValidatorDate(args.NewDate);
    	
	    if (!this.IsPopupVisible())
	    {	    
		    return;
	    }
    	
	    if (this.IsEmpty())
	    {
		    this.FocusCalendar();
	    }
	    else if (!this.CalendarSelectionInProgress)
	    {	
		    this.SetCalendarDate(args.NewDate);
	    }
    },

    FocusCalendar : function()
    {
	    this.Calendar.UnselectDates(this.Calendar.GetSelectedDates());
	    var focusedDateAsArray = [this.FocusedDate.getFullYear(), this.FocusedDate.getMonth() + 1, this.FocusedDate.getDate()];
	    this.Calendar.NavigateToDate(focusedDateAsArray);	
    },

    SetValidatorDate : function(newDate)
    {
        var validationValue = "";
        if (newDate != null)
        {
	        var month = (newDate.getMonth() + 1).toString();
	        if (month.length == 1)
		        month = "0" + month;
        		
	        var day = newDate.getDate().toString();
	        if (day.length == 1)
		        day = "0" + day;
        	
            validationValue = newDate.getFullYear() + "-" + month + "-" + day;
        }
        
        this.ValidationInput.value = validationValue;
    },

    GetElementPosition : function(el) 
    {
        return RadCalendarUtils.GetElementPosition(el);
    },

    SetCalendarDate : function(newDate)
    {
	    var dateParts = 
		    [
			    newDate.getFullYear(), 
			    newDate.getMonth() + 1, 
			    newDate.getDate()
		    ];
    	
	    this.SetCalendar();
	    var shouldNavigate = (this.Calendar.FocusedDate[1] != dateParts[1]) ||
							    (this.Calendar.FocusedDate[0] != dateParts[0]);
        
        this.InputSelectionInProgress = true;
        this.Calendar.UnselectDates(this.Calendar.GetSelectedDates());
        this.Calendar.SelectDate(dateParts, shouldNavigate);
        this.InputSelectionInProgress = false;
    },

    GetMinDate : function()
    {
        return this.MinDate;
    },

    SetMinDate : function(newDate)
    {
        var inputWasEmpty = false;
        if (this.IsEmpty())
        {
            inputWasEmpty = true;
        }

        this.MinDate = newDate;
        this.DateInput.SetMinDate(newDate);

        if (inputWasEmpty || (this.GetDate() < this.MinDate))
        {
            this.DateInput.Clear();
        }
        
        var newDateAsArray = [newDate.getFullYear(), (newDate.getMonth() + 1), newDate.getDate()];
        this.GetCalendar().SetRangeMinDate(newDateAsArray);    
    },

    GetMaxDate : function()
    {
        return this.MaxDate;
    },

    SetMaxDate : function(newDate)
    {
        this.MaxDate = newDate;
        this.DateInput.SetMaxDate(newDate);
        
        if (this.GetDate() > this.MaxDate)
        {
            this.SetDate(this.MaxDate);
        }
        
        var newDateAsArray = [newDate.getFullYear(), (newDate.getMonth() + 1), newDate.getDate()];
        this.GetCalendar().SetRangeMaxDate(newDateAsArray);
    }
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

//inspired by Yahoo UI
//inheritance sequence:
// 1. fully declare base class prototype
// 2. declare the subclass constructor
// 3. call Extend(subclass, baseclass)
RadCalendarNamespace.Extend = function(subClass, baseClass)
{
    var F = function() {};
    F.prototype = baseClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
    subClass.base = baseClass.prototype;
    if (baseClass.prototype.constructor == Object.prototype.constructor)
    {
        baseClass.prototype.constructor = baseClass;
    }
}

function RadDateTimePicker(clientID)
{
    RadDateTimePicker.base.constructor.call(this, clientID);
}

RadCalendarNamespace.Extend(RadDateTimePicker, RadDatePicker);

RadDateTimePicker.InitializeDateInput = function(dateTimePicker)
{
    if (dateTimePicker != null && dateTimePicker.InitializeDateInput != null)
    {
        dateTimePicker.InitializeDateInput();
    }
}

RadDateTimePicker.prototype.Dispose = function()
{
	if (!this.disposed)
	{
	    RadDateTimePicker.base.Dispose.call(this);

        if (this.TimePopupInstance != null)
		{
			this.TimePopupInstance.Hide();
			this.TimePopupInstance = null;
		}
		
        var timePopupImage = this.timePopupImage()
		if (timePopupImage != null)
		{
			timePopupImage.onmouseover = null;
			timePopupImage.onmouseout = null;
		}
		
		if (this.TimePopupButton != null)
		{
			this.TimePopupButton.onmouseover = null;
			this.TimePopupButton.onmouseout = null;
			this.TimePopupButton.onclick = null;
			
			this.TimePopupButton  = null;
		}
	}
}

RadDateTimePicker.prototype.SetTimeView = function(timeViewID)
{
	if (timeViewID != null)
		this.TimeViewID = timeViewID;
		
	this.TimeView = window[this.TimeViewID];
	var picker = this;
	this.TimeView.OnClientTimeSelecting = function()
	{
	    picker.TimeViewTimeSelected();
	};
}

RadDateTimePicker.prototype.GetTimeView = function()
{
	if (this.TimeView == null)
		this.SetTimeView();
	return this.TimeView;
}

RadDateTimePicker.prototype.GetTimePopupContainer = function()
{
	if (this.TimePopupContainer == null)
		this.TimePopupContainer = document.getElementById(this.TimePopupContainerID);
	return this.TimePopupContainer;
}

RadDateTimePicker.prototype.timePopupImage = function()
{
	var timePopupImage = null;
	
	if (this.TimePopupButton != null)
	{
		var images = this.TimePopupButton.getElementsByTagName("img");
		if (images.length > 0)
			timePopupImage = images[0];
	}
	
	return timePopupImage;
}

RadDateTimePicker.prototype.InitializePopupButton = function()
{
	RadDateTimePicker.base.InitializePopupButton.call(this);
	
    this.TimePopupButton = document.getElementById(this.TimePopupControlID);
	if (this.TimePopupButton != null)
	{
		this.AttachTimePopupButtonEvents();
	}
}

RadDateTimePicker.prototype.AttachTimePopupButtonEvents = function()
{
	var timePopupImage = this.timePopupImage();
	var picker = this;
	if (timePopupImage != null)
	{
		if (!this.HasTimeEventHandlerAttribute("onmouseover"))
		{
			timePopupImage.onmouseover = function() 
				{
					this.src = picker.TimePopupButtonSettings.ResolvedHoverImageUrl;
				};
		}
				
		if (!this.HasTimeEventHandlerAttribute("onmouseout"))		
		{
			timePopupImage.onmouseout = function() 
				{
					this.src = picker.TimePopupButtonSettings.ResolvedImageUrl;
				};
		}
	}
	
	if (!this.HasTimeEventHandlerAttribute("onclick"))		
	{
	 
		this.TimePopupButton.onclick = function() 
			{
			   
				picker.ToggleTimePopup();
				return false;
			};
	}
}

RadDateTimePicker.prototype.HasTimeEventHandlerAttribute = function(eventName)
{
	return this.TimePopupButton.getAttribute(eventName);
}

RadDateTimePicker.TimePopupInstances = {};

RadDateTimePicker.prototype.timepopup = function()
{
	var currentTimePopup = RadDateTimePicker.TimePopupInstances[this.TimeViewID];
	
	if (!currentTimePopup)
    {
        currentTimePopup = new RadCalendar.Popup();
        RadDateTimePicker.TimePopupInstances[this.TimeViewID] = currentTimePopup;
    }
    
    return currentTimePopup;
}

RadDateTimePicker.prototype.GetTimePopupVisibleControls = function()
{
	var excludeList = [this.GetTextBox(), this.GetPopupContainer()];
    if (this.TimePopupButton != null)
    {
		excludeList[excludeList.length] = this.TimePopupButton;
    }
    return excludeList;
}

RadDateTimePicker.prototype.ToggleTimePopup = function()
{
	if (this.IsTimePopupVisible())
	{
		this.HideTimePopup();
	}
	else
	{		
		this.ShowTimePopup();
	}
	return false;
}

RadDateTimePicker.prototype.IsTimePopupVisible = function()
{
	return this.timepopup().IsVisible() && 
			(this.timepopup().Opener == this);
}

RadDateTimePicker.prototype.ShowTimePopup = function(x, y)
{   
	this.SetTimeView();
	if (this.IsTimePopupVisible())
		return;
    
	var textbox = this.GetTextBox();
	
	
	if (typeof(x) == "undefined" || typeof(y) == "undefined")
	{
		var pos = RadCalendarUtils.GetElementPosition(textbox);
		x = pos.x;
		y = pos.y + textbox.offsetHeight;
	}
	
		
	this.timepopup().ExcludeFromHiding = this.GetTimePopupVisibleControls();
	this.HideTimePopup();
	
	this.timepopup().Opener = this;
	this.timepopup().Show(x, y, this.GetTimePopupContainer());
}

RadDateTimePicker.prototype.HideTimePopup = function()
{
	if (this.timepopup().IsVisible())
	{
		this.timepopup().Hide();
		this.timepopup().Opener = null;
	}
}

RadDateTimePicker.prototype.TimeViewTimeSelected = function()
{
    this.HideTimePopup();
}

// overrides a base class method
RadDateTimePicker.prototype.GetJavaScriptDate = function(dateArray)
{
    var oldDate = this.DateInput.GetDate();
    
    var hours = 0;
    var minutes = 0;
    var seconds = 0;
    var milliseconds = 0;
    if (oldDate != null)
    {
        hours = oldDate.getHours();
        minutes = oldDate.getMinutes();
        seconds = oldDate.getSeconds();
        milliseconds = oldDate.getMilliseconds();
    }
 
    var date = new Date(
                    dateArray[0], 
                    dateArray[1] - 1, 
                    dateArray[2], 
                    hours, 
                    minutes, 
                    seconds,
                    milliseconds);
                    
    return date;
}

RadDateTimePicker.prototype.SetValidatorDate = function(newDate)
{
    var validationValue = "";
	if (newDate != null)
	{
	    var month = (newDate.getMonth() + 1).toString();
	    if (month.length == 1)
		    month = "0" + month;
    		
	    var day = newDate.getDate().toString();
	    if (day.length == 1)
		    day = "0" + day;
    		
        var minutes = newDate.getMinutes().toString();
	    if (minutes.length == 1)
		    minutes = "0" + minutes;
    		
        var hours = newDate.getHours().toString();
	    if (hours.length == 1)
		    hours = "0" + hours;
    		
        var seconds = newDate.getSeconds().toString();
	    if (seconds.length == 1)
		    seconds = "0" + seconds;						
    	
        validationValue = newDate.getFullYear() 
                                    + "-" + month 
                                    + "-" + day
                                    + "-" + hours
                                    + "-" + minutes
                                    + "-" + seconds;
    }
    
    this.ValidationInput.value = validationValue;
}

RadDateTimePicker.prototype.SetInputDate = function(date)
{
    //AutoPostBackControl = None || AutoPostBackControl = TimeView
    if ((this.AutoPostBackControl == 0)     
        || (this.AutoPostBackControl == 2))
    {
        var cancelPostBack = function()
            {
                return false; 
            };
        
        this.DateInput.AttachEvent("OnValueChanged", cancelPostBack);
        RadDateTimePicker.base.SetInputDate.call(this, date);
        this.DateInput.DetachEvent("OnValueChanged", cancelPostBack);
    }
    else
    {
        RadDateTimePicker.base.SetInputDate.call(this, date);
    }  
};if (typeof(RadHelperUtils)== "undefined")
{
    var RadHelperUtils = 
    {    
        IsDefined : function(checkedElement) 
        {
            if((typeof(checkedElement)!="undefined")&&(checkedElement!=null)) 
            {
                return true;
            }
            return false;
        },
		
        StringStartsWith : function(inputString, stringToken)
        {
            if (typeof(stringToken) != "string")
	        {
		        return false;
	        }
	        return (0 == inputString.indexOf(stringToken));
        },

        AttachEventListener : function(eventElement, eventName, eventHandler)
        {
	        var compatibleEventName = RadHelperUtils.CompatibleEventName(eventName);
	        
	        if (typeof(eventElement.addEventListener)!= "undefined")
	        {
		        eventElement.addEventListener(compatibleEventName, eventHandler, false);//true
	        }
	        else if (eventElement.attachEvent)
	        {
		        eventElement.attachEvent(compatibleEventName, eventHandler);
	        }
	        else
	        {
				eventElement["on" + eventName] = eventHandler;
	        }
        },
        
        DetachEventListener : function(eventElement, eventName, eventHandler)
        {
	        var compatibleEventName = RadHelperUtils.CompatibleEventName(eventName);
	        if (typeof(eventElement.removeEventListener)!= "undefined")
	        {
		        eventElement.removeEventListener(compatibleEventName, eventHandler, false);//true
	        }	        
	        else if (eventElement.detachEvent)
	        {
		        eventElement.detachEvent(compatibleEventName, eventHandler);
	        }
	        else
	        {
				eventElement["on" + eventName] = null;
	        }
        },
        
        CompatibleEventName : function(eventName)
        {
	        eventName = eventName.toLowerCase();
	        if (document.addEventListener)
	        {
		        if (RadHelperUtils.StringStartsWith(eventName, "on"))
		            return eventName.substr(2);
		        else
		            return eventName;
	        }
	        else if (document.attachEvent && ! RadHelperUtils.StringStartsWith(eventName, "on"))
	        {
		        return "on" + eventName;
	        }
	        else
	        {
		        return eventName;
	        }
        },
        
        MouseEventX : function(processedEvent)
        {
	        if (processedEvent.pageX)
	        {
		        return processedEvent.pageX;
	        }
	        else if (processedEvent.clientX)
	        {
		        if (RadBrowserUtils.StandardMode)
		        {
			        return (processedEvent.clientX + document.documentElement.scrollLeft);
		        }
		        return (processedEvent.clientX + document.body.scrollLeft);
	        }
        },
        
        MouseEventY : function(processedEvent)
        {
	        if (processedEvent.pageY)
	        {
		        return processedEvent.pageY;
	        }
	        else if (processedEvent.clientY)
	        {
		        if (RadBrowserUtils.StandardMode)
		        {
			        return (processedEvent.clientY + document.documentElement.scrollTop);
		        }
		        return (processedEvent.clientY + document.body.scrollTop);
	        }
        },
		
        IframePlaceholder : function(inputElement,scenario) 
        {
                var IframeShim = document.createElement("IFRAME");
                IframeShim.src="javascript:false;";
                if (RadHelperUtils.IsDefined(scenario))
                {
                    switch(scenario) 
                    {
                        case 0:
                            IframeShim.src="javascript:void(0);";
            	            break;
                        case 1:
                            IframeShim.src="about:blank";
            	            break;
                        case 2:
                            IframeShim.src="blank.htm";
            	            break;
                    }
                }
                IframeShim.frameBorder = 0;
                IframeShim.style.position = "absolute";
                IframeShim.style.display = "none";
                IframeShim.style.left = "-500px";
                IframeShim.style.top = "-2000px";

                IframeShim.style.height = RadHelperUtils.ElementHeight(inputElement) + "px";
                
                var elementWidth = 0;
                elementWidth = RadHelperUtils.ElementWidth(inputElement);

	            IframeShim.style.width = elementWidth + "px";


                IframeShim.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
                IframeShim.allowTransparency = false;
                return inputElement.parentNode.insertBefore(IframeShim, inputElement);
        },
        
        ProcessIframe : function(domElement, visible, desiredX, desiredY)
        {
            if ( document.readyState == 'complete'&&
                    ( RadBrowserUtils.IsIE55Win || 
                    RadBrowserUtils.IsIE6Win )
                )
                {
                     if(!(RadHelperUtils.IsDefined(domElement)))
                     return;
                    if (!RadHelperUtils.IsDefined(domElement.iframeShim))  
                    {
                        domElement.iframeShim = RadHelperUtils.IframePlaceholder(domElement);
                    }
                    domElement.iframeShim.style.top = (RadHelperUtils.IsDefined(desiredY))? (desiredY + "px") : domElement.style.top; // 
                    domElement.iframeShim.style.left = (RadHelperUtils.IsDefined(desiredX))? (desiredX + "px") : domElement.style.left ;//+ "px"
                    domElement.iframeShim.style.zIndex = (domElement.style.zIndex - 1);
                       
                    RadHelperUtils.ChangeDisplay(domElement.iframeShim, visible);
                }
        },
        
        ChangeDisplay : function(container,visibillityFlag)
        {
            var obj = RadHelperUtils.GetStyleObj(container);
            if(visibillityFlag != null && visibillityFlag == true) 
            {
	            obj.display = '';
            }
            else if(visibillityFlag != null && visibillityFlag == false) 
            {
	            obj.display  = 'none';
            }
            return obj.display;
        },
        
        GetStyleObj : function(inputElement)
        { 
            if (!RadHelperUtils.IsDefined(inputElement)) 
            {
                return null;
            }
	        if (inputElement.style)
	        {
		        return inputElement.style;
	        }
	        else
	        {
		        return inputElement;
	        }
        },
        
        ElementWidth : function(inputElement) 
        {
	        if (!inputElement)
	        {
		        return 0;
	        }
	        if(RadHelperUtils.IsDefined(inputElement.style)) 
	        {
	            if (RadBrowserUtils.StandardMode && 
	                ( RadBrowserUtils.IsIE55Win || RadBrowserUtils.IsIE6Win ) 
	                )//element.currentStyle
	            {	
	            	if (RadHelperUtils.IsDefined(inputElement.offsetWidth) && inputElement.offsetWidth != 0) 
	                {
	                    return inputElement.offsetWidth;
	                }			
	            }
	            if (RadHelperUtils.IsDefined(inputElement.style.pixelWidth) && inputElement.style.pixelWidth != 0) 
	            {
	                var realWidth = inputElement.style.pixelWidth;
	            	if (RadHelperUtils.IsDefined(inputElement.offsetWidth) && inputElement.offsetWidth != 0) 
	                {
	                    realWidth =  (realWidth < inputElement.offsetWidth)? inputElement.offsetWidth : realWidth;
	                }
	                return realWidth;
	            }
	        }
	        if(RadHelperUtils.IsDefined(inputElement.offsetWidth)) 
	        {
		        return inputElement.offsetWidth;
	        }
	        return 0;
        },
        
        ElementHeight : function(inputElement) 
        {
            if (!inputElement)
            {
	            return 0;
            }
            if(RadHelperUtils.IsDefined(inputElement.style)) 
	        {
	            if (RadHelperUtils.IsDefined(inputElement.style.pixelHeight) && inputElement.style.pixelHeight != 0) 
	            {
	                return inputElement.style.pixelHeight;
	            }
	        }
            if(inputElement.offsetHeight)
            {
                return inputElement.offsetHeight;
            }
            return 0;
        }
    }
    // class definition END
    RadHelperUtils.GetElementByID = function (element, id)
	{
		var res = null;
		for (var i = 0; i < element.childNodes.length; i++)
		{
			if(!element.childNodes[i].id)
				continue;

			if(element.childNodes[i].id == id)
			{
				res = element.childNodes[i];
			}
		}
		
		return res;
	}
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

function RadTimeView(clientID, configurationObject, stylesHash)
{
    RadTimeView.DisposeOldInstance(clientID);
    this.ClientID = clientID;
    this.Initialize(configurationObject, stylesHash);     
}

RadTimeView.prototype.Initialize = function(configurationObject, stylesHash)
{
    this.ItemStyles = stylesHash;
	this.LoadConfiguration(configurationObject);
	this.DivElement = document.getElementById(this.ClientID);
    this.StartTime = RadTimeView.deserializerTime(this.StartTime);
    this.EndTime = RadTimeView.deserializerTime(this.EndTime);
    this.Interval = RadTimeView.deserializerTime(this.Interval);
	
    var thisObj = this;
    this.TimeMatrix = RadTimeView.setTimeMatrix(thisObj);
    this["OnClientTimeSelected"] = eval(this.OnClientTimeSelected);
    this["OnClientTimeSelecting"]  = "";
    this.tempStyle = null;
    RadControlsNamespace.EventMixin.Initialize(this);
    
    if (navigator.userAgent.match(/Safari/))
    {
        var timeView = document.getElementById(this.ClientID);
        timeView.style.display = "";
        timeView.style.visibility = "hidden";
        timeView.style.position = "absolute";
        timeView.style.left = "-1000px";
    }
                 
    var thisObj = this;
    
    this.genericHandler = function(e, eventName)
    {
        var target = RadCalendarUtils.FindTarget(e, thisObj.ClientID); 
        
        if (target == null)
        {
            return;
        }  
        if (eventName == "Click")
        {        
            var cellIndex = target.cellIndex;
            if (navigator.userAgent.match(/Safari/))
            {
                var trElement = target.parentNode;
                var i;
                for (i = 0; i < trElement.cells.length; i++)
                {
                    if (trElement.cells[i] == target)
                    {
                        cellIndex = i;
                    }
                }
            }
            var newTime = RadTimeView.findTime(target.parentNode.rowIndex, cellIndex, thisObj);
            
            if (newTime != null)
            {
                RadTimeView.mouseOut(thisObj, target);
                var args = {oldTime: "", newTime: ""};
                args.oldTime = thisObj.GetTime();
                thisObj.SetTime(newTime.getHours(), newTime.getMinutes(), newTime.getSeconds());
                args.newTime = thisObj.GetTime();
                if ((!args.oldTime)
                        || (args.oldTime.getTime() != args.newTime.getTime()))
                {
                    thisObj.RaiseEvent("OnClientTimeSelecting", args);            
                    thisObj.RaiseEvent("OnClientTimeSelected", args);
                }
            }
        }
        else if (eventName == "MouseOver")
        {
            RadTimeView.mouseOver(thisObj, target);
        }
        else if (eventName == "MouseOut")
        {
            RadTimeView.mouseOut(thisObj, target);
        }
    }
    
    var genericHandler = this.genericHandler;
    
	this.clickHandler = function(e)
	{
	    genericHandler(e, "Click");    
	}      
    RadHelperUtils.AttachEventListener(this.DivElement, "click", this.clickHandler); 
    
    this.mouseOverHandler = function(e)
    {
	    genericHandler(e, "MouseOver");   
	}		 
	RadHelperUtils.AttachEventListener(this.DivElement, "mouseover", this.mouseOverHandler);
	 
    this.mouseOutHandler = function(e)
    {
        genericHandler(e, "MouseOut");
    }		 
	RadHelperUtils.AttachEventListener(this.DivElement, "mouseout", this.mouseOutHandler);
	
	RadControlsNamespace.EventMixin.Initialize(this);
	var thisObj = this;
	
	var picker = this;
	RadHelperUtils.AttachEventListener(window, "unload", function()
		{
			try
			{
			    thisObj.Dispose();
			}
			catch(e)
			{
			}
		});
}


RadTimeView.prototype.LoadConfiguration = function (configurationObject)
{
    for (var property in configurationObject)
    {
        this[property] = configurationObject[property];
    }
}


RadTimeView.prototype.SetTime = function(hours, minutes, seconds)
{
    var datePicker = window[this.OwnerDataPickerID];
    var date = datePicker.GetDate(); 
    if (!date)
        date = new Date();
    date.setHours(hours);
    date.setMinutes(minutes);
    date.setSeconds(seconds);
    
    //AutoPostBackControl = Both || AutoPostBackControl = TimeView
    if ((datePicker.AutoPostBackControl != 1)     
        && (datePicker.AutoPostBackControl != 2))
    {
        var cancelPostBack = function()
            {
                return false; 
            };
        
        datePicker.DateInput.AttachEvent("OnValueChanged", cancelPostBack);
        datePicker.SetDate(date);
        datePicker.DateInput.DetachEvent("OnValueChanged", cancelPostBack);
    }
    else
    {
        datePicker.SetDate(date);
    }
}

RadTimeView.prototype.GetTime = function()
{
    var datePicker = window[this.OwnerDataPickerID];
    return datePicker.GetDate(); 
}

RadTimeView.DisposeOldInstance = function(clientID)
{
    try
    {
        var oldTimePicker = window[clientID];
        if (TimePicker != null)
        {
            oldTimePicker.Dispose();
	        window[clientID] = null;
        }
    }
    catch(e)
    {}
}

RadTimeView.prototype.Dispose = function()
{	
    var prop;
    for (prop in this)
    {
        prop = null;
    }
}


RadTimeView.FindTableElement = function(htmlElement)
{   
    var tables = htmlElement.getElementsByTagName("table");
    if (tables.length > 0)
    {
        return tables[0];
    }
    return null;
}

RadTimeView.findTime = function(rowIndex, colIndex, obj)
{
    var time = obj.TimeMatrix[rowIndex][colIndex];
    if (time != null)
    {
        return time;
    }
    return null;
}


RadTimeView.setTimeMatrix = function(obj)
{
    var i = 0;
    var timeArray = new Array(obj.ItemsCount);
    var startTime = obj.StartTime;

    while (startTime < obj.EndTime)
    {        
        //var deys = startTime.getDay();
        var hours = startTime.getHours();
        var minutes = startTime.getMinutes();
        var seconds = startTime.getSeconds();
        var milliseconds = startTime.getMilliseconds();
        
        var t = new Date(startTime.getYear(), startTime.getMonth(), startTime.getDate(), startTime.getHours(), startTime.getMinutes(), startTime.getSeconds(), startTime.getMilliseconds())
        timeArray[i] = t;
        i++;
        
        //startTime.setDate(hours + obj.Interval.getDate());
        startTime.setHours(hours + obj.Interval.getHours());
        startTime.setMinutes(minutes + obj.Interval.getMinutes());
        startTime.setSeconds(seconds + obj.Interval.getSeconds());
        startTime.setMilliseconds(milliseconds + obj.Interval.getMilliseconds());
    }
    
    var tableElement = RadTimeView.FindTableElement(obj.DivElement);
    var tableRowLength = tableElement.rows.length;
    var times = new Array(tableRowLength);
    for (i = 0; i < tableRowLength; i++)
    {
        times[i] = new Array(obj.Columns);
        var j;
        for (j = 0; j < obj.Columns; j++)
        {
            times[i][j] = null;
        }
    }
    var n = 0;
    var m = 0;
    if (obj.ShowHeader)
    {
        n = 1;
    }
    
    for (i = 0; i < timeArray.length; i++)
    {
        times[n][m] = timeArray[i];
        m++;
        
        if (m == obj.Columns)
        {
            m = 0;
            n ++;
        }           
    }
    
    return times;
}

RadTimeView.deserializerTime = function(serializerTime)
{    
    var date = new Date(1990, 1, serializerTime[0], serializerTime[1], serializerTime[2], serializerTime[3], serializerTime[4]);
    return date;
}

RadTimeView.mouseOver = function(sender, tdElement)
{
    var style = new Array(2);
    style[0] = tdElement.style.cssText;
    style[1] = tdElement.className;
    sender.tempStyle = style;
    
    tdElement.style.cssText = sender.ItemStyles["TimeOverStyle"][0];    
    tdElement.className = sender.ItemStyles["TimeOverStyle"][1];
}

RadTimeView.mouseOut = function(sender, tdElement)
{
    if (sender.tempStyle == null)
    {
        return;
    }
    tdElement.style.cssText = sender.tempStyle[0];
    tdElement.className = sender.tempStyle[1];
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.RangeValidation = function(rangeMinDate, rangeMaxDate)
{
	this.RangeMinDate = rangeMinDate;
	this.RangeMaxDate = rangeMaxDate;
}

RadCalendarNamespace.RangeValidation.prototype.IsDateValid = function(date)
{
	return (this.CompareDates(this.RangeMinDate, date) <= 0
			&& this.CompareDates(date, this.RangeMaxDate) <= 0);
};

RadCalendarNamespace.RangeValidation.prototype.CompareDates = function(date1, date2)
{
	if (!date1 || date1.length != 3)
		throw new Error("Date1 must be array: [y, m, d]");
		
	if (!date2 || date2.length != 3)
		throw new Error("Date2 must be array: [y, m, d]");

	var y1 = date1[0];
	var y2 = date2[0];	
	
	if (y1 < y2) 
		return -1;
	if (y1 > y2) 
		return 1;
	
	var m1 = date1[1];
	var m2 = date2[1];	
	
	if (m1 < m2) 
		return -1;
	if (m1 > m2) 
		return 1;
	
	var d1 = date1[2];
	var d2 = date2[2];
	
	if (d1 < d2) 
		return -1;		
	if (d1 > d2) 
		return 1;
	
	return 0;
};

RadCalendarNamespace.RangeValidation.prototype.InSameMonth = function(date1, date2)
{
    return ((date1[0] == date2[0]) && (date1[1] == date2[1]));
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.RenderDay = function(data)
{
    if (typeof(data) != "undefined")
    {
        var i = 0;        
        this.TemplateID			        = data[i++];
        this.Date			            = data[i++];
        this.IsSelectable			    = data[i++];
        this.IsSelected			        = data[i++];
        this.IsDisabled			        = data[i++];
        this.IsToday			        = data[i++];
        this.Repeatable			        = data[i++];
        this.IsWeekend			        = data[i++];
		this.ToolTip					= data[i++];
		this.ItemStyle                  = data[i++];

        // runtime properties when rendering.        
        this.DomElement					= data[i++];
        this.RadCalendar				= data[i++];
        this.ID							= data[i++];
        this.RadCalendarView			= data[i++];
        this.DayRow						= data[i++];
        this.DayColumn					= data[i++]; 
    }
}

RadCalendarNamespace.RenderDay.prototype.Dispose = function()
{
	this.disposed = true;
	
    if (this.DomElement)
    {
		this.DomElement.DayId = "";
        this.DomElement.RenderDay = null;
    }
    
    this.DomElement					= null;
    this.RadCalendar				= null;
    this.RadCalendarView			= null;
    this.DayRow						= null;
    this.DayColumn					= null;
}

RadCalendarNamespace.RenderDay.prototype.MouseOver = function()
{
    if (!this.ApplyHoverBehavior())
        return;
   
    var dayOverStyle = this.RadCalendar.ItemStyles["DayOverStyle"];
    this.DomElement.className = dayOverStyle[1];
    this.DomElement.style.cssText = dayOverStyle[0];    
};

RadCalendarNamespace.RenderDay.prototype.MouseOut = function()
{
    if (!this.ApplyHoverBehavior())
        return;
    
    var defaultStyle = this.GetDefaultItemStyle();
    this.DomElement.className = defaultStyle[1];
    this.DomElement.style.cssText = defaultStyle[0];
};

RadCalendarNamespace.RenderDay.prototype.Click = function(e)
{
	var evt = {
	            RenderDay : this,
	            DomEvent : e
	          };
	          
	if (this.RadCalendar.RaiseEvent("OnDateClick", evt) == false)
	{
		return;
	}

	this.Select(!this.IsSelected);
};

RadCalendarNamespace.RenderDay.prototype.Select = function(select, preventSubmit)
{
	if (!this.RadCalendar.Selection.CanSelect(this.Date))
	    return;
		
	if (null == select)
		select = true;

	if (this.RadCalendar.EnableMultiSelect)
	{
		// Invert the current selection
		this.PerformSelect(select);
	}
	else
	{
		var selectionCanceled = false;
		if (select)
        {
			
			var dayToUnselect = this.RadCalendar.FindRenderDay(this.RadCalendar.LastSelectedDate);
			if (dayToUnselect && dayToUnselect != this)
			{
				selectionCanceled = (false == dayToUnselect.Select(false));
			}
            
            var selectedDates = this.RadCalendar.Selection.SelectedDates.GetValues();
            for(var i = 0; i < selectedDates.length; i++)
            {
                if(selectedDates[i])
                {
                    var dayToUnselect = this.RadCalendar.FindRenderDay(selectedDates[i]);
			        if (dayToUnselect && dayToUnselect != this)
			        {
				        selectionCanceled = (false == dayToUnselect.Select(false,true));
			        }
                }
            }
        }	
		
		var selectionCanceledFromEvent = false;
		if (!selectionCanceled)
		{   
			var returnValue = this.PerformSelect(select);
			if (typeof(returnValue) != "undefined")
			{
			    selectionCanceledFromEvent = !returnValue;
			}
			
			this.RadCalendar.LastSelectedDate = (this.IsSelected ? this.Date : null);
		}
	}
	
	this.RadCalendar.SerializeSelectedDates();
	
  	if (!preventSubmit && !selectionCanceledFromEvent)
	{
		this.RadCalendar.Submit("d");
	}
	
};

RadCalendarNamespace.RenderDay.prototype.PerformSelect = function(select)
{
	if (null == select)
		select = true;

	if (this.IsSelected != select)
	{	
	    var evt = {
	                RenderDay : this,
	                IsSelecting : select
	              };

		if (this.RadCalendar.RaiseEvent("OnDateSelecting", evt) == false)
		{
			return false;
		}
		
		this.IsSelected = select;
		
		var cellStyle = this.GetDefaultItemStyle();
		if (cellStyle)
		{		       
               this.DomElement.className = cellStyle[1];
               this.DomElement.style.cssText = cellStyle[0];
		}
		
		if (select)
		{		
			this.RadCalendar.Selection.Add(this.Date);
		}
		else
		{
			this.RadCalendar.Selection.Remove(this.Date);
		}
		
		this.RadCalendar.RaiseEvent("OnDateSelected", this);
	}	
};

RadCalendarNamespace.RenderDay.prototype.GetDefaultItemStyle = function()
{
	var thisMonth = (this.Date[1] == this.RadCalendarView._MonthStartDate[1]);
	var specDate = this.RadCalendar.SpecialDays.Get(this.Date);
	
	if (specDate == null && 
	    this.RadCalendar.RecurringDays.Get(this.Date) != null)
	{
	    specDate = this.RadCalendar.RecurringDays.Get(this.Date);
	}
	
	var style = null;
	
	if (this.IsSelected)
	{
	    style = this.RadCalendar.ItemStyles["SelectedDayStyle"];
	    
	    return style;
	}
	else if (specDate)
	{
	    var specDayID = "SpecialDayStyle_" + specDate.Date.join("_");
	    style = specDate.ItemStyle[specDayID];	  	    
	    if(style[0] == "" && style[1] == "")
	    {
	        style = this.RadCalendar.ItemStyles["DayStyle"];
	    }	    
	}
	else if (!thisMonth) //otherMonth day
	{
	    style = this.RadCalendar.ItemStyles["OtherMonthDayStyle"];
	}	
	else if (this.IsWeekend)
	{
	    style = this.RadCalendar.ItemStyles["WeekendDayStyle"];
	}
	else 
	{
	    style = this.RadCalendar.ItemStyles["DayStyle"];
	}
		
	var changedDay = this.RadCalendar.DayRenderChangedDays[this.Date.join("_")];
	var changedStyle = [];
	if (changedDay != null)
	{	    
	    changedStyle[0] = RadCalendarUtils.MergeStyles(changedDay[0], style[0]); 	    	    
	    changedStyle[1] = RadCalendarUtils.MergeClassName(changedDay[1], style[1]);
	    return changedStyle;
	}	
	
	return style;
}

RadCalendarNamespace.RenderDay.prototype.ApplyHoverBehavior = function()
{
    //cannot get rid of cell's DayId on first load but in some cases (i.e. disabled days) no hover behavior should be applied 
    var specDate = this.RadCalendar.SpecialDays.Get(this.Date);
    if (specDate && !specDate.IsSelectable)
    {
        return false;
    }
    
    if (this.RadCalendar.EnableRepeatableDaysOnClient)
    {	    
        var recurringMatches = RadCalendarUtils.RECURRING_NONE;
        var specDaysArray = this.RadCalendar.SpecialDays.GetValues();	    
        for (var i=0; i < specDaysArray.length; i++)
        {
            recurringMatches = specDaysArray[i].IsRecurring(this.Date);
            if (recurringMatches != RadCalendarUtils.RECURRING_NONE)
            {
                specDate = specDaysArray[i];                
                if (!specDate.IsSelectable)
                {
                    return false;
                }
            }
        }
    }
    
    return true;
}

RadCalendarNamespace.RenderDay.prototype.IsRecurring = function (compareDate)
{
    if (this.Repeatable != RadCalendarUtils.RECURRING_NONE)
    {
        switch (this.Repeatable)
        {
            case RadCalendarUtils.RECURRING_DAYINMONTH:
            {
                if (compareDate[2] == this.Date[2])
                {
                    return this.Repeatable;
                }
                break;
            }
            case RadCalendarUtils.RECURRING_TODAY:
            {
                var today = new Date();
                if ((compareDate[0] == today.getFullYear()) && 
                    (compareDate[1] == (today.getMonth() + 1)) && 
                    (compareDate[2] == today.getDate()))
                    {
                        return this.Repeatable;
                    }
                break;
            }
            case RadCalendarUtils.RECURRING_DAYANDMONTH:
            {
                if((compareDate[1] == this.Date[1]) &&
                   (compareDate[2] == this.Date[2]))        
                   {
                        return this.Repeatable;
                   }
                break;
            }
            case RadCalendarUtils.RECURRING_WEEKANDMONTH:
            {
                var compareFirstDate = new Date();
                compareFirstDate.setFullYear(compareDate[0], (compareDate[1] - 1), compareDate[2]);
                
                var compareSecondDate = new Date();
                compareSecondDate.setFullYear(this.Date[0], (this.Date[1] - 1), this.Date[2]);
                
                if ((compareFirstDate.getDay() == compareSecondDate.getDay()) && (compareDate[1] == this.Date[1]))
                {
                    return this.Repeatable;
                }
                break;
            }
            case RadCalendarUtils.RECURRING_WEEK:
            {
                var compareFirstDate = new Date();
                compareFirstDate.setFullYear(compareDate[0], (compareDate[1] - 1), compareDate[2]);
                
                var compareSecondDate = new Date();
                compareSecondDate.setFullYear(this.Date[0], (this.Date[1] - 1), this.Date[2]);
                
                if (compareFirstDate.getDay() == compareSecondDate.getDay())
                {
                    return this.Repeatable;
                }
                break;
            }   
            default: break;
        }
    }
    return RadCalendarUtils.RECURRING_NONE;
};if (typeof(window["RadCalendarNamespace"]) == "undefined")
{
	window["RadCalendarNamespace"] = {};
}

RadCalendarNamespace.Selection = function(rangeValidation, specialDays, recurringDays, enableMultiSelect)
{
	this.SpecialDays = specialDays;
    this.RecurringDays = recurringDays;
	this.EnableMultiSelect = enableMultiSelect;
		
	this.SelectedDates = new RadCalendarUtils.DateCollection();
	this.RangeValidation = rangeValidation;	
}

RadCalendarNamespace.Selection.prototype.CanSelect = function(date)
{
	if (!this.RangeValidation.IsDateValid(date))
		return false;
	
	var specialDay = this.SpecialDays.Get(date);		
	if (specialDay != null)
		return specialDay.IsSelectable != 0;
    else 
    {    
        var recurringDay = this.RecurringDays.Get(date);
        if (recurringDay != null)
            return recurringDay.IsSelectable != 0;
        else
		    return true;    
    }	
}

RadCalendarNamespace.Selection.prototype.Add = function(date)
{
	if (!this.CanSelect(date))
		return;
	
	if (!this.EnableMultiSelect)
	{
		this.SelectedDates.Clear();
	}
	
	this.SelectedDates.Add(date, date);
}

RadCalendarNamespace.Selection.prototype.Remove = function(date)
{
	this.SelectedDates.Remove(date);
};