/* START MicrosoftAjax.js */
//----------------------------------------------------------
// Copyright (C) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------
// MicrosoftAjax.js
Function.__typeName="Function";Function.__class=true;Function.createCallback=function(b,a){return function(){var e=arguments.length;if(e>0){var d=[];for(var c=0;c<e;c++)d[c]=arguments[c];d[e]=a;return b.apply(this,d)}return b.call(this,a)}};Function.createDelegate=function(a,b){return function(){return b.apply(a,arguments)}};Function.emptyFunction=Function.emptyMethod=function(){};Function._validateParams=function(e,c){var a;a=Function._validateParameterCount(e,c);if(a){a.popStackFrame();return a}for(var b=0;b<e.length;b++){var d=c[Math.min(b,c.length-1)],f=d.name;if(d.parameterArray)f+="["+(b-c.length+1)+"]";a=Function._validateParameter(e[b],d,f);if(a){a.popStackFrame();return a}}return null};Function._validateParameterCount=function(e,a){var c=a.length,d=0;for(var b=0;b<a.length;b++)if(a[b].parameterArray)c=Number.MAX_VALUE;else if(!a[b].optional)d++;if(e.length<d||e.length>c){var f=Error.parameterCount();f.popStackFrame();return f}return null};Function._validateParameter=function(c,a,h){var b,g=a.type,l=!!a.integer,k=!!a.domElement,m=!!a.mayBeNull;b=Function._validateParameterType(c,g,l,k,m,h);if(b){b.popStackFrame();return b}var e=a.elementType,f=!!a.elementMayBeNull;if(g===Array&&typeof c!=="undefined"&&c!==null&&(e||!f)){var j=!!a.elementInteger,i=!!a.elementDomElement;for(var d=0;d<c.length;d++){var n=c[d];b=Function._validateParameterType(n,e,j,i,f,h+"["+d+"]");if(b){b.popStackFrame();return b}}}return null};Function._validateParameterType=function(b,c,k,j,h,d){var a;if(typeof b==="undefined")if(h)return null;else{a=Error.argumentUndefined(d);a.popStackFrame();return a}if(b===null)if(h)return null;else{a=Error.argumentNull(d);a.popStackFrame();return a}if(c&&c.__enum){if(typeof b!=="number"){a=Error.argumentType(d,Object.getType(b),c);a.popStackFrame();return a}if(b%1===0){var e=c.prototype;if(!c.__flags||b===0){for(var g in e)if(e[g]===b)return null}else{var i=b;for(var g in e){var f=e[g];if(f===0)continue;if((f&b)===f)i-=f;if(i===0)return null}}}a=Error.argumentOutOfRange(d,b,String.format(Sys.Res.enumInvalidValue,b,c.getName()));a.popStackFrame();return a}if(j&&b!==window&&b!==document&&!(window.HTMLElement&&b instanceof HTMLElement)&&typeof b.nodeName!=="string"){a=Error.argument(d,Sys.Res.argumentDomElement);a.popStackFrame();return a}if(c&&!c.isInstanceOfType(b)){a=Error.argumentType(d,Object.getType(b),c);a.popStackFrame();return a}if(c===Number&&k)if(b%1!==0){a=Error.argumentOutOfRange(d,b,Sys.Res.argumentInteger);a.popStackFrame();return a}return null};Error.__typeName="Error";Error.__class=true;Error.create=function(d,b){var a=new Error(d);a.message=d;if(b)for(var c in b)a[c]=b[c];a.popStackFrame();return a};Error.argument=function(a,c){var b="Sys.ArgumentException: "+(c?c:Sys.Res.argument);if(a)b+="\n"+String.format(Sys.Res.paramName,a);var d=Error.create(b,{name:"Sys.ArgumentException",paramName:a});d.popStackFrame();return d};Error.argumentNull=function(a,c){var b="Sys.ArgumentNullException: "+(c?c:Sys.Res.argumentNull);if(a)b+="\n"+String.format(Sys.Res.paramName,a);var d=Error.create(b,{name:"Sys.ArgumentNullException",paramName:a});d.popStackFrame();return d};Error.argumentOutOfRange=function(c,a,d){var b="Sys.ArgumentOutOfRangeException: "+(d?d:Sys.Res.argumentOutOfRange);if(c)b+="\n"+String.format(Sys.Res.paramName,c);if(typeof a!=="undefined"&&a!==null)b+="\n"+String.format(Sys.Res.actualValue,a);var e=Error.create(b,{name:"Sys.ArgumentOutOfRangeException",paramName:c,actualValue:a});e.popStackFrame();return e};Error.argumentType=function(d,c,b,e){var a="Sys.ArgumentTypeException: ";if(e)a+=e;else if(c&&b)a+=String.format(Sys.Res.argumentTypeWithTypes,c.getName(),b.getName());else a+=Sys.Res.argumentType;if(d)a+="\n"+String.format(Sys.Res.paramName,d);var f=Error.create(a,{name:"Sys.ArgumentTypeException",paramName:d,actualType:c,expectedType:b});f.popStackFrame();return f};Error.argumentUndefined=function(a,c){var b="Sys.ArgumentUndefinedException: "+(c?c:Sys.Res.argumentUndefined);if(a)b+="\n"+String.format(Sys.Res.paramName,a);var d=Error.create(b,{name:"Sys.ArgumentUndefinedException",paramName:a});d.popStackFrame();return d};Error.format=function(a){var c="Sys.FormatException: "+(a?a:Sys.Res.format),b=Error.create(c,{name:"Sys.FormatException"});b.popStackFrame();return b};Error.invalidOperation=function(a){var c="Sys.InvalidOperationException: "+(a?a:Sys.Res.invalidOperation),b=Error.create(c,{name:"Sys.InvalidOperationException"});b.popStackFrame();return b};Error.notImplemented=function(a){var c="Sys.NotImplementedException: "+(a?a:Sys.Res.notImplemented),b=Error.create(c,{name:"Sys.NotImplementedException"});b.popStackFrame();return b};Error.parameterCount=function(a){var c="Sys.ParameterCountException: "+(a?a:Sys.Res.parameterCount),b=Error.create(c,{name:"Sys.ParameterCountException"});b.popStackFrame();return b};Error.prototype.popStackFrame=function(){if(typeof this.stack==="undefined"||this.stack===null||typeof this.fileName==="undefined"||this.fileName===null||typeof this.lineNumber==="undefined"||this.lineNumber===null)return;var a=this.stack.split("\n"),c=a[0],e=this.fileName+":"+this.lineNumber;while(typeof c!=="undefined"&&c!==null&&c.indexOf(e)===-1){a.shift();c=a[0]}var d=a[1];if(typeof d==="undefined"||d===null)return;var b=d.match(/@(.*):(\d+)$/);if(typeof b==="undefined"||b===null)return;this.fileName=b[1];this.lineNumber=parseInt(b[2]);a.shift();this.stack=a.join("\n")};if(!window)this.window=this;window.Type=Function;window.__rootNamespaces=[];window.__registeredTypes={};Type.prototype.callBaseMethod=function(a,d,b){var c=this.getBaseMethod(a,d);if(!b)return c.apply(a);else return c.apply(a,b)};Type.prototype.getBaseMethod=function(d,c){var b=this.getBaseType();if(b){var a=b.prototype[c];return a instanceof Function?a:null}return null};Type.prototype.getBaseType=function(){return typeof this.__baseType==="undefined"?null:this.__baseType};Type.prototype.getInterfaces=function(){var a=[],b=this;while(b){var c=b.__interfaces;if(c)for(var d=0,f=c.length;d<f;d++){var e=c[d];if(!Array.contains(a,e))a[a.length]=e}b=b.__baseType}return a};Type.prototype.getName=function(){return typeof this.__typeName==="undefined"?"":this.__typeName};Type.prototype.implementsInterface=function(d){this.resolveInheritance();var c=d.getName(),a=this.__interfaceCache;if(a){var e=a[c];if(typeof e!=="undefined")return e}else a=this.__interfaceCache={};var b=this;while(b){var f=b.__interfaces;if(f)if(Array.indexOf(f,d)!==-1)return a[c]=true;b=b.__baseType}return a[c]=false};Type.prototype.inheritsFrom=function(b){this.resolveInheritance();var a=this.__baseType;while(a){if(a===b)return true;a=a.__baseType}return false};Type.prototype.initializeBase=function(a,b){this.resolveInheritance();if(this.__baseType)if(!b)this.__baseType.apply(a);else this.__baseType.apply(a,b);return a};Type.prototype.isImplementedBy=function(a){if(typeof a==="undefined"||a===null)return false;var b=Object.getType(a);return !!(b.implementsInterface&&b.implementsInterface(this))};Type.prototype.isInstanceOfType=function(b){if(typeof b==="undefined"||b===null)return false;if(b instanceof this)return true;var a=Object.getType(b);return !!(a===this)||a.inheritsFrom&&a.inheritsFrom(this)||a.implementsInterface&&a.implementsInterface(this)};Type.prototype.registerClass=function(c,b,d){this.prototype.constructor=this;this.__typeName=c;this.__class=true;if(b){this.__baseType=b;this.__basePrototypePending=true}if(!window.__classes)window.__classes={};window.__classes[c.toUpperCase()]=this;if(d){this.__interfaces=[];for(var a=2;a<arguments.length;a++){var e=arguments[a];this.__interfaces.push(e)}}return this};Type.prototype.registerInterface=function(a){this.prototype.constructor=this;this.__typeName=a;this.__interface=true;return this};Type.prototype.resolveInheritance=function(){if(this.__basePrototypePending){var b=this.__baseType;b.resolveInheritance();for(var a in b.prototype){var c=b.prototype[a];if(!this.prototype[a])this.prototype[a]=c}delete this.__basePrototypePending}};Type.getRootNamespaces=function(){return Array.clone(window.__rootNamespaces)};Type.isClass=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__class};Type.isInterface=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__interface};Type.isNamespace=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__namespace};Type.parse=function(typeName,ns){var fn;if(ns){if(!window.__classes)return null;fn=window.__classes[ns.getName().toUpperCase()+"."+typeName.toUpperCase()];return fn||null}if(!typeName)return null;if(!Type.__htClasses)Type.__htClasses={};fn=Type.__htClasses[typeName];if(!fn){fn=eval(typeName);Type.__htClasses[typeName]=fn}return fn};Type.registerNamespace=function(f){var d=window,c=f.split(".");for(var b=0;b<c.length;b++){var e=c[b],a=d[e];if(!a){a=d[e]={};if(b===0)window.__rootNamespaces[window.__rootNamespaces.length]=a;a.__namespace=true;a.__typeName=c.slice(0,b+1).join(".");a.getName=function(){return this.__typeName}}d=a}};Object.__typeName="Object";Object.__class=true;Object.getType=function(b){var a=b.constructor;if(!a||typeof a!=="function"||!a.__typeName||a.__typeName==="Object")return Object;return a};Object.getTypeName=function(a){return Object.getType(a).getName()};Boolean.__typeName="Boolean";Boolean.__class=true;Boolean.parse=function(b){var a=b.trim().toLowerCase();if(a==="false")return false;if(a==="true")return true};Date.__typeName="Date";Date.__class=true;Date._appendPreOrPostMatch=function(e,b){var d=0,a=false;for(var c=0,g=e.length;c<g;c++){var f=e.charAt(c);switch(f){case "'":if(a)b.append("'");else d++;a=false;break;case "\\":if(a)b.append("\\");a=!a;break;default:b.append(f);a=false;break}}return d};Date._expandFormat=function(a,b){if(!b)b="F";if(b.length===1)switch(b){case "d":return a.ShortDatePattern;case "D":return a.LongDatePattern;case "t":return a.ShortTimePattern;case "T":return a.LongTimePattern;case "F":return a.FullDateTimePattern;case "M":case "m":return a.MonthDayPattern;case "s":return a.SortableDateTimePattern;case "Y":case "y":return a.YearMonthPattern;default:throw Error.format(Sys.Res.formatInvalidString)}return b};Date._expandYear=function(c,a){if(a<100){var b=(new Date).getFullYear();a+=b-b%100;if(a>c.Calendar.TwoDigitYearMax)return a-100}return a};Date._getParseRegExp=function(b,e){if(!b._parseRegExp)b._parseRegExp={};else if(b._parseRegExp[e])return b._parseRegExp[e];var c=Date._expandFormat(b,e);c=c.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g,"\\\\$1");var a=new Sys.StringBuilder("^"),j=[],f=0,i=0,h=Date._getTokenRegExp(),d;while((d=h.exec(c))!==null){var l=c.slice(f,d.index);f=h.lastIndex;i+=Date._appendPreOrPostMatch(l,a);if(i%2===1){a.append(d[0]);continue}switch(d[0]){case "dddd":case "ddd":case "MMMM":case "MMM":a.append("(\\D+)");break;case "tt":case "t":a.append("(\\D*)");break;case "yyyy":a.append("(\\d{4})");break;case "fff":a.append("(\\d{3})");break;case "ff":a.append("(\\d{2})");break;case "f":a.append("(\\d)");break;case "dd":case "d":case "MM":case "M":case "yy":case "y":case "HH":case "H":case "hh":case "h":case "mm":case "m":case "ss":case "s":a.append("(\\d\\d?)");break;case "zzz":a.append("([+-]?\\d\\d?:\\d{2})");break;case "zz":case "z":a.append("([+-]?\\d\\d?)");break}Array.add(j,d[0])}Date._appendPreOrPostMatch(c.slice(f),a);a.append("$");var k=a.toString().replace(/\s+/g,"\\s+"),g={"regExp":k,"groups":j};b._parseRegExp[e]=g;return g};Date._getTokenRegExp=function(){return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g};Date.parseLocale=function(a){return Date._parse(a,Sys.CultureInfo.CurrentCulture,arguments)};Date.parseInvariant=function(a){return Date._parse(a,Sys.CultureInfo.InvariantCulture,arguments)};Date._parse=function(g,c,h){var e=false;for(var a=1,i=h.length;a<i;a++){var f=h[a];if(f){e=true;var b=Date._parseExact(g,f,c);if(b)return b}}if(!e){var d=c._getDateTimeFormats();for(var a=0,i=d.length;a<i;a++){var b=Date._parseExact(g,d[a],c);if(b)return b}}return null};Date._parseExact=function(s,y,j){s=s.trim();var m=j.dateTimeFormat,v=Date._getParseRegExp(m,y),x=(new RegExp(v.regExp)).exec(s);if(x!==null){var w=v.groups,f=null,c=null,h=null,g=null,d=0,n=0,o=0,e=0,k=null,r=false;for(var p=0,z=w.length;p<z;p++){var a=x[p+1];if(a)switch(w[p]){case "dd":case "d":h=Date._parseInt(a);if(h<1||h>31)return null;break;case "MMMM":c=j._getMonthIndex(a);if(c<0||c>11)return null;break;case "MMM":c=j._getAbbrMonthIndex(a);if(c<0||c>11)return null;break;case "M":case "MM":var c=Date._parseInt(a)-1;if(c<0||c>11)return null;break;case "y":case "yy":f=Date._expandYear(m,Date._parseInt(a));if(f<0||f>9999)return null;break;case "yyyy":f=Date._parseInt(a);if(f<0||f>9999)return null;break;case "h":case "hh":d=Date._parseInt(a);if(d===12)d=0;if(d<0||d>11)return null;break;case "H":case "HH":d=Date._parseInt(a);if(d<0||d>23)return null;break;case "m":case "mm":n=Date._parseInt(a);if(n<0||n>59)return null;break;case "s":case "ss":o=Date._parseInt(a);if(o<0||o>59)return null;break;case "tt":case "t":var u=a.toUpperCase();r=u===m.PMDesignator.toUpperCase();if(!r&&u!==m.AMDesignator.toUpperCase())return null;break;case "f":e=Date._parseInt(a)*100;if(e<0||e>999)return null;break;case "ff":e=Date._parseInt(a)*10;if(e<0||e>999)return null;break;case "fff":e=Date._parseInt(a);if(e<0||e>999)return null;break;case "dddd":g=j._getDayIndex(a);if(g<0||g>6)return null;break;case "ddd":g=j._getAbbrDayIndex(a);if(g<0||g>6)return null;break;case "zzz":var q=a.split(/:/);if(q.length!==2)return null;var i=Date._parseInt(q[0]);if(i<-12||i>13)return null;var l=Date._parseInt(q[1]);if(l<0||l>59)return null;k=i*60+(a.startsWith("-")?-l:l);break;case "z":case "zz":var i=Date._parseInt(a);if(i<-12||i>13)return null;k=i*60;break}}var b=new Date;if(f===null)f=b.getFullYear();if(c===null)c=b.getMonth();if(h===null)h=b.getDate();b.setFullYear(f,c,h);if(b.getDate()!==h)return null;if(g!==null&&b.getDay()!==g)return null;if(r&&d<12)d+=12;b.setHours(d,n,o,e);if(k!==null){var t=b.getMinutes()-(k+b.getTimezoneOffset());b.setHours(b.getHours()+parseInt(t/60),t%60)}return b}};Date._parseInt=function(a){return parseInt(a.replace(/^[\s0]+(\d+)$/,"$1"))};Date.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Date.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Date.prototype._toFormattedString=function(e,h){if(!e||e.length===0||e==="i")if(h&&h.name.length>0)return this.toLocaleString();else return this.toString();var d=h.dateTimeFormat;e=Date._expandFormat(d,e);var a=new Sys.StringBuilder,b;function c(a){if(a<10)return "0"+a;return a.toString()}function g(a){if(a<10)return "00"+a;if(a<100)return "0"+a;return a.toString()}var j=0,i=Date._getTokenRegExp();for(;true;){var l=i.lastIndex,f=i.exec(e),k=e.slice(l,f?f.index:e.length);j+=Date._appendPreOrPostMatch(k,a);if(!f)break;if(j%2===1){a.append(f[0]);continue}switch(f[0]){case "dddd":a.append(d.DayNames[this.getDay()]);break;case "ddd":a.append(d.AbbreviatedDayNames[this.getDay()]);break;case "dd":a.append(c(this.getDate()));break;case "d":a.append(this.getDate());break;case "MMMM":a.append(d.MonthNames[this.getMonth()]);break;case "MMM":a.append(d.AbbreviatedMonthNames[this.getMonth()]);break;case "MM":a.append(c(this.getMonth()+1));break;case "M":a.append(this.getMonth()+1);break;case "yyyy":a.append(this.getFullYear());break;case "yy":a.append(c(this.getFullYear()%100));break;case "y":a.append(this.getFullYear()%100);break;case "hh":b=this.getHours()%12;if(b===0)b=12;a.append(c(b));break;case "h":b=this.getHours()%12;if(b===0)b=12;a.append(b);break;case "HH":a.append(c(this.getHours()));break;case "H":a.append(this.getHours());break;case "mm":a.append(c(this.getMinutes()));break;case "m":a.append(this.getMinutes());break;case "ss":a.append(c(this.getSeconds()));break;case "s":a.append(this.getSeconds());break;case "tt":a.append(this.getHours()<12?d.AMDesignator:d.PMDesignator);break;case "t":a.append((this.getHours()<12?d.AMDesignator:d.PMDesignator).charAt(0));break;case "f":a.append(g(this.getMilliseconds()).charAt(0));break;case "ff":a.append(g(this.getMilliseconds()).substr(0,2));break;case "fff":a.append(g(this.getMilliseconds()));break;case "z":b=this.getTimezoneOffset()/60;a.append((b>=0?"+":"-")+Math.floor(Math.abs(b)));break;case "zz":b=this.getTimezoneOffset()/60;a.append((b>=0?"+":"-")+c(Math.floor(Math.abs(b))));break;case "zzz":b=this.getTimezoneOffset()/60;a.append((b>=0?"+":"-")+c(Math.floor(Math.abs(b)))+d.TimeSeparator+c(Math.abs(this.getTimezoneOffset()%60)));break}}return a.toString()};Number.__typeName="Number";Number.__class=true;Number.parseLocale=function(a){return Number._parse(a,Sys.CultureInfo.CurrentCulture)};Number.parseInvariant=function(a){return Number._parse(a,Sys.CultureInfo.InvariantCulture)};Number._parse=function(g,f){var a=g.trim();if(a.match(/infinity/i)!==null)return parseFloat(a);if(a.match(/^0x[a-f0-9]+$/i)!==null)return parseInt(a);var d=f.numberFormat,b=d.NumberDecimalSeparator,c=d.NumberGroupSeparator,e=new RegExp("^[+-]?[\\d\\"+c+"]*\\"+b+"?\\d*([eE][+-]?\\d+)?$");if(!a.match(e))return Number.NaN;a=a.split(c).join("");a=a.replace(b,".");return parseFloat(a)};Number.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Number.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Number.prototype._toFormattedString=function(d,j){if(!d||d.length===0||d==="i")if(j&&j.name.length>0)return this.toLocaleString();else return this.toString();var q=["n %","n%","%n"],p=["-n %","-n%","-%n"],r=["(n)","-n","- n","n-","n -"],o=["$n","n$","$ n","n $"],n=["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"];function i(p,k,j,l,o){var e=j[0],g=1,c=p.toString(),a="",m="",i=c.split(".");if(i.length>1){c=i[0];a=i[1];var h=a.split(/e/i);if(h.length>1){a=h[0];m="e"+h[1]}}if(k>0){var f=a.length-k;if(f>0)a=a.slice(0,k);else if(f<0)for(var n=0;n<Math.abs(f);n++)a+="0";a=o+a}else a="";a+=m;var b=c.length-1,d="";while(b>=0){if(e===0||e>b)if(d.length>0)return c.slice(0,b+1)+l+d+a;else return c.slice(0,b+1)+a;if(d.length>0)d=c.slice(b-e+1,b+1)+l+d;else d=c.slice(b-e+1,b+1);b-=e;if(g<j.length){e=j[g];g++}}return c.slice(0,b+1)+l+d+a}var a=j.numberFormat,e=Math.abs(this);if(!d)d="D";var b=-1;if(d.length>1)b=parseInt(d.slice(1));var c;switch(d.charAt(0)){case "d":case "D":c="n";if(b!==-1){var g=""+e,k=b-g.length;if(k>0)for(var m=0;m<k;m++)g="0"+g;e=g}if(this<0)e=-e;break;case "c":case "C":if(this<0)c=n[a.CurrencyNegativePattern];else c=o[a.CurrencyPositivePattern];if(b===-1)b=a.CurrencyDecimalDigits;e=i(Math.abs(this),b,a.CurrencyGroupSizes,a.CurrencyGroupSeparator,a.CurrencyDecimalSeparator);break;case "n":case "N":if(this<0)c=r[a.NumberNegativePattern];else c="n";if(b===-1)b=a.NumberDecimalDigits;e=i(Math.abs(this),b,a.NumberGroupSizes,a.NumberGroupSeparator,a.NumberDecimalSeparator);break;case "p":case "P":if(this<0)c=p[a.PercentNegativePattern];else c=q[a.PercentPositivePattern];if(b===-1)b=a.PercentDecimalDigits;e=i(Math.abs(this),b,a.PercentGroupSizes,a.PercentGroupSeparator,a.PercentDecimalSeparator);break;default:throw Error.format(Sys.Res.formatBadFormatSpecifier)}var l=/n|\$|-|%/g,f="";for(;true;){var s=l.lastIndex,h=l.exec(c);f+=c.slice(s,h?h.index:c.length);if(!h)break;switch(h[0]){case "n":f+=e;break;case "$":f+=a.CurrencySymbol;break;case "-":f+=a.NegativeSign;break;case "%":f+=a.PercentSymbol;break}}return f};RegExp.__typeName="RegExp";RegExp.__class=true;Array.__typeName="Array";Array.__class=true;Array.add=Array.enqueue=function(a,b){a[a.length]=b};Array.addRange=function(a,b){a.push.apply(a,b)};Array.clear=function(a){a.length=0};Array.clone=function(a){if(a.length===1)return [a[0]];else return Array.apply(null,a)};Array.contains=function(a,b){return Array.indexOf(a,b)>=0};Array.dequeue=function(a){return a.shift()};Array.forEach=function(b,e,d){for(var a=0,f=b.length;a<f;a++){var c=b[a];if(typeof c!=="undefined")e.call(d,c,a,b)}};Array.indexOf=function(d,e,a){if(typeof e==="undefined")return -1;var c=d.length;if(c!==0){a=a-0;if(isNaN(a))a=0;else{if(isFinite(a))a=a-a%1;if(a<0)a=Math.max(0,c+a)}for(var b=a;b<c;b++)if(typeof d[b]!=="undefined"&&d[b]===e)return b}return -1};Array.insert=function(a,b,c){a.splice(b,0,c)};Array.parse=function(value){if(!value)return [];return eval(value)};Array.remove=function(b,c){var a=Array.indexOf(b,c);if(a>=0)b.splice(a,1);return a>=0};Array.removeAt=function(a,b){a.splice(b,1)};String.__typeName="String";String.__class=true;String.prototype.endsWith=function(a){return this.substr(this.length-a.length)===a};String.prototype.startsWith=function(a){return this.substr(0,a.length)===a};String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")};String.prototype.trimEnd=function(){return this.replace(/\s+$/,"")};String.prototype.trimStart=function(){return this.replace(/^\s+/,"")};String.format=function(){return String._toFormattedString(false,arguments)};String.localeFormat=function(){return String._toFormattedString(true,arguments)};String._toFormattedString=function(l,j){var c="",e=j[0];for(var a=0;true;){var f=e.indexOf("{",a),d=e.indexOf("}",a);if(f<0&&d<0){c+=e.slice(a);break}if(d>0&&(d<f||f<0)){c+=e.slice(a,d+1);a=d+2;continue}c+=e.slice(a,f);a=f+1;if(e.charAt(a)==="{"){c+="{";a++;continue}if(d<0)break;var h=e.substring(a,d),g=h.indexOf(":"),k=parseInt(g<0?h:h.substring(0,g))+1,i=g<0?"":h.substring(g+1),b=j[k];if(typeof b==="undefined"||b===null)b="";if(b.toFormattedString)c+=b.toFormattedString(i);else if(l&&b.localeFormat)c+=b.localeFormat(i);else if(b.format)c+=b.format(i);else c+=b.toString();a=d+1}return c};Type.registerNamespace("Sys");Sys.IDisposable=function(){};Sys.IDisposable.prototype={};Sys.IDisposable.registerInterface("Sys.IDisposable");Sys.StringBuilder=function(a){this._parts=typeof a!=="undefined"&&a!==null&&a!==""?[a.toString()]:[];this._value={};this._len=0};Sys.StringBuilder.prototype={append:function(a){this._parts[this._parts.length]=a},appendLine:function(a){this._parts[this._parts.length]=typeof a==="undefined"||a===null||a===""?"\r\n":a+"\r\n"},clear:function(){this._parts=[];this._value={};this._len=0},isEmpty:function(){if(this._parts.length===0)return true;return this.toString()===""},toString:function(a){a=a||"";var b=this._parts;if(this._len!==b.length){this._value={};this._len=b.length}var d=this._value;if(typeof d[a]==="undefined"){if(a!=="")for(var c=0;c<b.length;)if(typeof b[c]==="undefined"||b[c]===""||b[c]===null)b.splice(c,1);else c++;d[a]=this._parts.join(a)}return d[a]}};Sys.StringBuilder.registerClass("Sys.StringBuilder");if(!window.XMLHttpRequest)window.XMLHttpRequest=function(){var b=["Msxml2.XMLHTTP","Microsoft.XMLHTTP"];for(var a=0;a<b.length;a++)try{var c=new ActiveXObject(b[a]);return c}catch(d){}return null};Sys.Browser={};Sys.Browser.InternetExplorer={};Sys.Browser.Firefox={};Sys.Browser.Safari={};Sys.Browser.Opera={};Sys.Browser.agent=null;Sys.Browser.hasDebuggerStatement=false;Sys.Browser.name=navigator.appName;Sys.Browser.version=parseFloat(navigator.appVersion);if(navigator.userAgent.indexOf(" MSIE ")>-1){Sys.Browser.agent=Sys.Browser.InternetExplorer;Sys.Browser.version=parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" Firefox/")>-1){Sys.Browser.agent=Sys.Browser.Firefox;Sys.Browser.version=parseFloat(navigator.userAgent.match(/Firefox\/(\d+\.\d+)/)[1]);Sys.Browser.name="Firefox";Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" Safari/")>-1){Sys.Browser.agent=Sys.Browser.Safari;Sys.Browser.version=parseFloat(navigator.userAgent.match(/Safari\/(\d+\.\d+)/)[1]);Sys.Browser.name="Safari"}else if(navigator.userAgent.indexOf("Opera/")>-1)Sys.Browser.agent=Sys.Browser.Opera;Type.registerNamespace("Sys.UI");Sys._Debug=function(){};Sys._Debug.prototype={_appendConsole:function(a){if(typeof Debug!=="undefined"&&Debug.writeln)Debug.writeln(a);if(window.console&&window.console.log)window.console.log(a);if(window.opera)window.opera.postError(a);if(window.debugService)window.debugService.trace(a)},_appendTrace:function(b){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value+=b+"\n"},assert:function(c,a,b){if(!c){a=b&&this.assert.caller?String.format(Sys.Res.assertFailedCaller,a,this.assert.caller):String.format(Sys.Res.assertFailed,a);if(confirm(String.format(Sys.Res.breakIntoDebugger,a)))this.fail(a)}},clearTrace:function(){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value=""},fail:function(message){this._appendConsole(message);if(Sys.Browser.hasDebuggerStatement)eval("debugger")},trace:function(a){this._appendConsole(a);this._appendTrace(a)},traceDump:function(a,b){var c=this._traceDump(a,b,true)},_traceDump:function(a,c,f,b,d){c=c?c:"traceDump";b=b?b:"";if(a===null){this.trace(b+c+": null");return}switch(typeof a){case "undefined":this.trace(b+c+": Undefined");break;case "number":case "string":case "boolean":this.trace(b+c+": "+a);break;default:if(Date.isInstanceOfType(a)||RegExp.isInstanceOfType(a)){this.trace(b+c+": "+a.toString());break}if(!d)d=[];else if(Array.contains(d,a)){this.trace(b+c+": ...");return}Array.add(d,a);if(a==window||a===document||window.HTMLElement&&a instanceof HTMLElement||typeof a.nodeName==="string"){var k=a.tagName?a.tagName:"DomElement";if(a.id)k+=" - "+a.id;this.trace(b+c+" {"+k+"}")}else{var i=Object.getTypeName(a);this.trace(b+c+(typeof i==="string"?" {"+i+"}":""));if(b===""||f){b+="    ";var e,j,l,g,h;if(Array.isInstanceOfType(a)){j=a.length;for(e=0;e<j;e++)this._traceDump(a[e],"["+e+"]",f,b,d)}else for(g in a){h=a[g];if(!Function.isInstanceOfType(h))this._traceDump(h,g,f,b,d)}}}Array.remove(d,a)}}};Sys._Debug.registerClass("Sys._Debug");Sys.Debug=new Sys._Debug;Sys.Debug.isDebug=false;function Sys$Enum$parse(c,e){var a,b,i;if(e){a=this.__lowerCaseValues;if(!a){this.__lowerCaseValues=a={};var g=this.prototype;for(var f in g)a[f.toLowerCase()]=g[f]}}else a=this.prototype;if(!this.__flags){i=e?c.toLowerCase():c;b=a[i.trim()];if(typeof b!=="number")throw Error.argument("value",String.format(Sys.Res.enumInvalidValue,c,this.__typeName));return b}else{var h=(e?c.toLowerCase():c).split(","),j=0;for(var d=h.length-1;d>=0;d--){var k=h[d].trim();b=a[k];if(typeof b!=="number")throw Error.argument("value",String.format(Sys.Res.enumInvalidValue,c.split(",")[d].trim(),this.__typeName));j|=b}return j}}function Sys$Enum$toString(c){if(typeof c==="undefined"||c===null)return this.__string;var d=this.prototype,a;if(!this.__flags||c===0){for(a in d)if(d[a]===c)return a}else{var b=this.__sortedValues;if(!b){b=[];for(a in d)b[b.length]={key:a,value:d[a]};b.sort(function(a,b){return a.value-b.value});this.__sortedValues=b}var e=[],g=c;for(a=b.length-1;a>=0;a--){var h=b[a],f=h.value;if(f===0)continue;if((f&c)===f){e[e.length]=h.key;g-=f;if(g===0)break}}if(e.length&&g===0)return e.reverse().join(", ")}return ""}Type.prototype.registerEnum=function(c,b){for(var a in this.prototype)this[a]=this.prototype[a];this.__typeName=c;this.parse=Sys$Enum$parse;this.__string=this.toString();this.toString=Sys$Enum$toString;this.__flags=b;this.__enum=true};Type.isEnum=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__enum};Type.isFlags=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__flags};Sys.EventHandlerList=function(){this._list={}};Sys.EventHandlerList.prototype={addHandler:function(b,a){Array.add(this._getEvent(b,true),a)},removeHandler:function(c,b){var a=this._getEvent(c);if(!a)return;Array.remove(a,b)},getHandler:function(b){var a=this._getEvent(b);if(!a||a.length===0)return null;a=Array.clone(a);if(!a._handler)a._handler=function(c,d){for(var b=0,e=a.length;b<e;b++)a[b](c,d)};return a._handler},_getEvent:function(a,b){if(!this._list[a]){if(!b)return null;this._list[a]=[]}return this._list[a]}};Sys.EventHandlerList.registerClass("Sys.EventHandlerList");Sys.EventArgs=function(){};Sys.EventArgs.registerClass("Sys.EventArgs");Sys.EventArgs.Empty=new Sys.EventArgs;Sys.CancelEventArgs=function(){Sys.CancelEventArgs.initializeBase(this);this._cancel=false};Sys.CancelEventArgs.prototype={get_cancel:function(){return this._cancel},set_cancel:function(a){this._cancel=a}};Sys.CancelEventArgs.registerClass("Sys.CancelEventArgs",Sys.EventArgs);Sys.INotifyPropertyChange=function(){};Sys.INotifyPropertyChange.prototype={};Sys.INotifyPropertyChange.registerInterface("Sys.INotifyPropertyChange");Sys.PropertyChangedEventArgs=function(a){Sys.PropertyChangedEventArgs.initializeBase(this);this._propertyName=a};Sys.PropertyChangedEventArgs.prototype={get_propertyName:function(){return this._propertyName}};Sys.PropertyChangedEventArgs.registerClass("Sys.PropertyChangedEventArgs",Sys.EventArgs);Sys.INotifyDisposing=function(){};Sys.INotifyDisposing.prototype={};Sys.INotifyDisposing.registerInterface("Sys.INotifyDisposing");Sys.Component=function(){if(Sys.Application)Sys.Application.registerDisposableObject(this)};Sys.Component.prototype={_id:null,_initialized:false,_updating:false,get_events:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_id:function(){return this._id},set_id:function(a){this._id=a},get_isInitialized:function(){return this._initialized},get_isUpdating:function(){return this._updating},add_disposing:function(a){this.get_events().addHandler("disposing",a)},remove_disposing:function(a){this.get_events().removeHandler("disposing",a)},add_propertyChanged:function(a){this.get_events().addHandler("propertyChanged",a)},remove_propertyChanged:function(a){this.get_events().removeHandler("propertyChanged",a)},beginUpdate:function(){this._updating=true},dispose:function(){if(this._events){var a=this._events.getHandler("disposing");if(a)a(this,Sys.EventArgs.Empty)}delete this._events;Sys.Application.unregisterDisposableObject(this);Sys.Application.removeComponent(this)},endUpdate:function(){this._updating=false;if(!this._initialized)this.initialize();this.updated()},initialize:function(){this._initialized=true},raisePropertyChanged:function(b){if(!this._events)return;var a=this._events.getHandler("propertyChanged");if(a)a(this,new Sys.PropertyChangedEventArgs(b))},updated:function(){}};Sys.Component.registerClass("Sys.Component",null,Sys.IDisposable,Sys.INotifyPropertyChange,Sys.INotifyDisposing);function Sys$Component$_setProperties(a,i){var d,j=Object.getType(a),e=j===Object||j===Sys.UI.DomElement,h=Sys.Component.isInstanceOfType(a)&&!a.get_isUpdating();if(h)a.beginUpdate();for(var c in i){var b=i[c],f=e?null:a["get_"+c];if(e||typeof f!=="function"){var k=a[c];if(!b||typeof b!=="object"||e&&!k)a[c]=b;else Sys$Component$_setProperties(k,b)}else{var l=a["set_"+c];if(typeof l==="function")l.apply(a,[b]);else if(b instanceof Array){d=f.apply(a);for(var g=0,m=d.length,n=b.length;g<n;g++,m++)d[m]=b[g]}else if(typeof b==="object"&&Object.getType(b)===Object){d=f.apply(a);Sys$Component$_setProperties(d,b)}}}if(h)a.endUpdate()}function Sys$Component$_setReferences(c,b){for(var a in b){var e=c["set_"+a],d=$find(b[a]);e.apply(c,[d])}}var $create=Sys.Component.create=function(h,f,d,c,g){var a=g?new h(g):new h,b=Sys.Application,i=b.get_isCreatingComponents();a.beginUpdate();if(f)Sys$Component$_setProperties(a,f);if(d)for(var e in d)a["add_"+e](d[e]);b._createdComponents[b._createdComponents.length]=a;if(a.get_id())b.addComponent(a);if(i)if(c)b._addComponentToSecondPass(a,c);else a.endUpdate();else{if(c)Sys$Component$_setReferences(a,c);a.endUpdate()}return a};Sys.UI.MouseButton=function(){throw Error.notImplemented()};Sys.UI.MouseButton.prototype={leftButton:0,middleButton:1,rightButton:2};Sys.UI.MouseButton.registerEnum("Sys.UI.MouseButton");Sys.UI.Key=function(){throw Error.notImplemented()};Sys.UI.Key.prototype={backspace:8,tab:9,enter:13,esc:27,space:32,pageUp:33,pageDown:34,end:35,home:36,left:37,up:38,right:39,down:40,del:127};Sys.UI.Key.registerEnum("Sys.UI.Key");Sys.UI.DomEvent=function(c){var a=c;this.rawEvent=a;this.altKey=a.altKey;if(typeof a.button!=="undefined")this.button=typeof a.which!=="undefined"?a.button:a.button===4?Sys.UI.MouseButton.middleButton:a.button===2?Sys.UI.MouseButton.rightButton:Sys.UI.MouseButton.leftButton;if(a.type==="keypress")this.charCode=a.charCode||a.keyCode;else if(a.keyCode&&a.keyCode===46)this.keyCode=127;else this.keyCode=a.keyCode;this.clientX=a.clientX;this.clientY=a.clientY;this.ctrlKey=a.ctrlKey;this.target=a.target?a.target:a.srcElement;if(this.target){var b=Sys.UI.DomElement.getLocation(this.target);this.offsetX=typeof a.offsetX!=="undefined"?a.offsetX:window.pageXOffset+(a.clientX||0)-b.x;this.offsetY=typeof a.offsetY!=="undefined"?a.offsetY:window.pageYOffset+(a.clientY||0)-b.y}this.screenX=a.screenX;this.screenY=a.screenY;this.shiftKey=a.shiftKey;this.type=a.type};Sys.UI.DomEvent.prototype={preventDefault:function(){if(this.rawEvent.preventDefault)this.rawEvent.preventDefault();else if(window.event)window.event.returnValue=false},stopPropagation:function(){if(this.rawEvent.stopPropagation)this.rawEvent.stopPropagation();else if(window.event)window.event.cancelBubble=true}};Sys.UI.DomEvent.registerClass("Sys.UI.DomEvent");var $addHandler=Sys.UI.DomEvent.addHandler=function(a,d,e){if(!a._events)a._events={};var c=a._events[d];if(!c)a._events[d]=c=[];var b;if(a.addEventListener){b=function(b){return e.call(a,new Sys.UI.DomEvent(b))};a.addEventListener(d,b,false)}else if(a.attachEvent){b=function(){return e.call(a,new Sys.UI.DomEvent(window.event))};a.attachEvent("on"+d,b)}c[c.length]={handler:e,browserHandler:b}},$addHandlers=Sys.UI.DomEvent.addHandlers=function(e,d,c){for(var b in d){var a=d[b];if(c)a=Function.createDelegate(c,a);$addHandler(e,b,a)}},$clearHandlers=Sys.UI.DomEvent.clearHandlers=function(a){if(a._events){var e=a._events;for(var b in e){var d=e[b];for(var c=d.length-1;c>=0;c--)$removeHandler(a,b,d[c].handler)}a._events=null}},$removeHandler=Sys.UI.DomEvent.removeHandler=function(a,e,f){var d=null,c=a._events[e],d=null;for(var b=0,g=c.length;b<g;b++)if(c[b].handler===f){d=c[b].browserHandler;break}if(a.removeEventListener)a.removeEventListener(e,d,false);else if(a.detachEvent)a.detachEvent("on"+e,d);c.splice(b,1)};Sys.IContainer=function(){};Sys.IContainer.prototype={};Sys.IContainer.registerInterface("Sys.IContainer");Sys._ScriptLoader=function(){this._scriptsToLoad=null;this._scriptLoadedDelegate=Function.createDelegate(this,this._scriptLoadedHandler)};Sys._ScriptLoader.prototype={dispose:function(){this._stopLoading();if(this._events)delete this._events;this._scriptLoadedDelegate=null},loadScripts:function(a,c,d,b){this._loading=true;this._allScriptsLoadedCallback=c;this._scriptLoadFailedCallback=d;this._scriptLoadTimeoutCallback=b;if(a>0)this._timeoutCookie=window.setTimeout(Function.createDelegate(this,this._scriptLoadTimeoutHandler),a*1000);this._loadScriptsInternal()},notifyScriptLoaded:function(){if(!this._loading)return;this._currentTask._notified++;if(Sys.Browser.agent===Sys.Browser.Safari)if(this._currentTask._notified===1)window.setTimeout(Function.createDelegate(this,function(){this._scriptLoadedHandler(this._currentTask.get_scriptElement(),true)}),0)},queueCustomScriptTag:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,a)},queueScriptBlock:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{text:a})},queueScriptReference:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{src:a})},_createScriptElement:function(c){var a=document.createElement("SCRIPT");a.type="text/javascript";for(var b in c)a[b]=c[b];return a},_loadScriptsInternal:function(){if(this._scriptsToLoad&&this._scriptsToLoad.length>0){var b=Array.dequeue(this._scriptsToLoad),a=this._createScriptElement(b);if(a.text&&Sys.Browser.agent===Sys.Browser.Safari){a.innerHTML=a.text;delete a.text}if(typeof b.src==="string"){this._currentTask=new Sys._ScriptLoaderTask(a,this._scriptLoadedDelegate);this._currentTask.execute()}else{document.getElementsByTagName("HEAD")[0].appendChild(a);Sys._ScriptLoader._clearScript(a);this._loadScriptsInternal()}}else{var c=this._allScriptsLoadedCallback;this._stopLoading();if(c)c(this)}},_raiseError:function(a){var c=this._scriptLoadFailedCallback,b=this._currentTask.get_scriptElement();this._stopLoading();if(c)c(this,b,a);else throw Sys._ScriptLoader._errorScriptLoadFailed(b.src,a)},_scriptLoadedHandler:function(a,b){if(b&&this._currentTask._notified)if(this._currentTask._notified>1)this._raiseError(true);else{Array.add(Sys._ScriptLoader._getLoadedScripts(),a.src);this._currentTask.dispose();this._currentTask=null;this._loadScriptsInternal()}else this._raiseError(false)},_scriptLoadTimeoutHandler:function(){var a=this._scriptLoadTimeoutCallback;this._stopLoading();if(a)a(this)},_stopLoading:function(){if(this._timeoutCookie){window.clearTimeout(this._timeoutCookie);this._timeoutCookie=null}if(this._currentTask){this._currentTask.dispose();this._currentTask=null}this._scriptsToLoad=null;this._loading=null;this._allScriptsLoadedCallback=null;this._scriptLoadFailedCallback=null;this._scriptLoadTimeoutCallback=null}};Sys._ScriptLoader.registerClass("Sys._ScriptLoader",null,Sys.IDisposable);Sys._ScriptLoader.getInstance=function(){var a=Sys._ScriptLoader._activeInstance;if(!a)a=Sys._ScriptLoader._activeInstance=new Sys._ScriptLoader;return a};Sys._ScriptLoader.isScriptLoaded=function(b){var a=document.createElement("script");a.src=b;return Array.contains(Sys._ScriptLoader._getLoadedScripts(),a.src)};Sys._ScriptLoader.readLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){var b=Sys._ScriptLoader._referencedScripts=[],c=document.getElementsByTagName("SCRIPT");for(i=c.length-1;i>=0;i--){var d=c[i],a=d.src;if(a.length)if(!Array.contains(b,a))Array.add(b,a)}}};Sys._ScriptLoader._clearScript=function(a){if(!Sys.Debug.isDebug)a.parentNode.removeChild(a)};Sys._ScriptLoader._errorScriptLoadFailed=function(b,d){var a;if(d)a=Sys.Res.scriptLoadMultipleCallbacks;else a=Sys.Res.scriptLoadFailed;var e="Sys.ScriptLoadFailedException: "+String.format(a,b),c=Error.create(e,{name:"Sys.ScriptLoadFailedException","scriptUrl":b});c.popStackFrame();return c};Sys._ScriptLoader._getLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){Sys._ScriptLoader._referencedScripts=[];Sys._ScriptLoader.readLoadedScripts()}return Sys._ScriptLoader._referencedScripts};Sys._ScriptLoaderTask=function(b,a){this._scriptElement=b;this._completedCallback=a;this._notified=0};Sys._ScriptLoaderTask.prototype={get_scriptElement:function(){return this._scriptElement},dispose:function(){if(this._disposed)return;this._disposed=true;this._removeScriptElementHandlers();Sys._ScriptLoader._clearScript(this._scriptElement);this._scriptElement=null},execute:function(){this._addScriptElementHandlers();document.getElementsByTagName("HEAD")[0].appendChild(this._scriptElement)},_addScriptElementHandlers:function(){this._scriptLoadDelegate=Function.createDelegate(this,this._scriptLoadHandler);if(Sys.Browser.agent!==Sys.Browser.InternetExplorer){this._scriptElement.readyState="loaded";$addHandler(this._scriptElement,"load",this._scriptLoadDelegate)}else $addHandler(this._scriptElement,"readystatechange",this._scriptLoadDelegate);this._scriptErrorDelegate=Function.createDelegate(this,this._scriptErrorHandler);$addHandler(this._scriptElement,"error",this._scriptErrorDelegate)},_removeScriptElementHandlers:function(){if(this._scriptLoadDelegate){var a=this.get_scriptElement();if(Sys.Browser.agent!==Sys.Browser.InternetExplorer)$removeHandler(a,"load",this._scriptLoadDelegate);else $removeHandler(a,"readystatechange",this._scriptLoadDelegate);$removeHandler(a,"error",this._scriptErrorDelegate);this._scriptErrorDelegate=null;this._scriptLoadDelegate=null}},_scriptErrorHandler:function(){if(this._disposed)return;this._completedCallback(this.get_scriptElement(),false)},_scriptLoadHandler:function(){if(this._disposed)return;var a=this.get_scriptElement();if(a.readyState!=="loaded"&&a.readyState!=="complete")return;var b=this;window.setTimeout(function(){b._completedCallback(a,true)},0)}};Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask",null,Sys.IDisposable);Sys.ApplicationLoadEventArgs=function(b,a){Sys.ApplicationLoadEventArgs.initializeBase(this);this._components=b;this._isPartialLoad=a};Sys.ApplicationLoadEventArgs.prototype={get_components:function(){return this._components},get_isPartialLoad:function(){return this._isPartialLoad}};Sys.ApplicationLoadEventArgs.registerClass("Sys.ApplicationLoadEventArgs",Sys.EventArgs);Sys._Application=function(){Sys._Application.initializeBase(this);this._disposableObjects=[];this._components={};this._createdComponents=[];this._secondPassComponents=[];this._unloadHandlerDelegate=Function.createDelegate(this,this._unloadHandler);this._loadHandlerDelegate=Function.createDelegate(this,this._loadHandler);Sys.UI.DomEvent.addHandler(window,"unload",this._unloadHandlerDelegate);Sys.UI.DomEvent.addHandler(window,"load",this._loadHandlerDelegate)};Sys._Application.prototype={_creatingComponents:false,_disposing:false,get_isCreatingComponents:function(){return this._creatingComponents},add_load:function(a){this.get_events().addHandler("load",a)},remove_load:function(a){this.get_events().removeHandler("load",a)},add_init:function(a){if(this._initialized)a(this,Sys.EventArgs.Empty);else this.get_events().addHandler("init",a)},remove_init:function(a){this.get_events().removeHandler("init",a)},add_unload:function(a){this.get_events().addHandler("unload",a)},remove_unload:function(a){this.get_events().removeHandler("unload",a)},addComponent:function(a){this._components[a.get_id()]=a},beginCreateComponents:function(){this._creatingComponents=true},dispose:function(){if(!this._disposing){this._disposing=true;if(window.pageUnload)window.pageUnload(this,Sys.EventArgs.Empty);var c=this.get_events().getHandler("unload");if(c)c(this,Sys.EventArgs.Empty);var b=Array.clone(this._disposableObjects);for(var a=0,e=b.length;a<e;a++)b[a].dispose();Array.clear(this._disposableObjects);Sys.UI.DomEvent.removeHandler(window,"unload",this._unloadHandlerDelegate);if(this._loadHandlerDelegate){Sys.UI.DomEvent.removeHandler(window,"load",this._loadHandlerDelegate);this._loadHandlerDelegate=null}var d=Sys._ScriptLoader.getInstance();if(d)d.dispose();Sys._Application.callBaseMethod(this,"dispose")}},endCreateComponents:function(){var b=this._secondPassComponents;for(var a=0,d=b.length;a<d;a++){var c=b[a].component;Sys$Component$_setReferences(c,b[a].references);c.endUpdate()}this._secondPassComponents=[];this._creatingComponents=false},findComponent:function(b,a){return a?Sys.IContainer.isInstanceOfType(a)?a.findComponent(b):a[b]||null:Sys.Application._components[b]||null},getComponents:function(){var a=[],b=this._components;for(var c in b)a[a.length]=b[c];return a},initialize:function(){if(!this._initialized&&!this._initializing){this._initializing=true;window.setTimeout(Function.createDelegate(this,this._doInitialize),0)}},notifyScriptLoaded:function(){var a=Sys._ScriptLoader.getInstance();if(a)a.notifyScriptLoaded()},registerDisposableObject:function(a){if(!this._disposing)this._disposableObjects[this._disposableObjects.length]=a},raiseLoad:function(){var b=this.get_events().getHandler("load"),a=new Sys.ApplicationLoadEventArgs(Array.clone(this._createdComponents),!this._initializing);if(b)b(this,a);if(window.pageLoad)window.pageLoad(this,a);this._createdComponents=[]},removeComponent:function(b){var a=b.get_id();if(a)delete this._components[a]},unregisterDisposableObject:function(a){if(!this._disposing)Array.remove(this._disposableObjects,a)},_addComponentToSecondPass:function(b,a){this._secondPassComponents[this._secondPassComponents.length]={component:b,references:a}},_doInitialize:function(){Sys._Application.callBaseMethod(this,"initialize");var a=this.get_events().getHandler("init");if(a){this.beginCreateComponents();a(this,Sys.EventArgs.Empty);this.endCreateComponents()}this.raiseLoad();this._initializing=false},_loadHandler:function(){if(this._loadHandlerDelegate){Sys.UI.DomEvent.removeHandler(window,"load",this._loadHandlerDelegate);this._loadHandlerDelegate=null}this.initialize()},_unloadHandler:function(){this.dispose()}};Sys._Application.registerClass("Sys._Application",Sys.Component,Sys.IContainer);Sys.Application=new Sys._Application;var $find=Sys.Application.findComponent;Type.registerNamespace("Sys.Net");Sys.Net.WebRequestExecutor=function(){this._webRequest=null;this._resultObject=null};Sys.Net.WebRequestExecutor.prototype={get_webRequest:function(){return this._webRequest},_set_webRequest:function(a){this._webRequest=a},get_started:function(){throw Error.notImplemented()},get_responseAvailable:function(){throw Error.notImplemented()},get_timedOut:function(){throw Error.notImplemented()},get_aborted:function(){throw Error.notImplemented()},get_responseData:function(){throw Error.notImplemented()},get_statusCode:function(){throw Error.notImplemented()},get_statusText:function(){throw Error.notImplemented()},get_xml:function(){throw Error.notImplemented()},get_object:function(){if(!this._resultObject)this._resultObject=Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData());return this._resultObject},executeRequest:function(){throw Error.notImplemented()},abort:function(){throw Error.notImplemented()},getResponseHeader:function(){throw Error.notImplemented()},getAllResponseHeaders:function(){throw Error.notImplemented()}};Sys.Net.WebRequestExecutor.registerClass("Sys.Net.WebRequestExecutor");window.XMLDOM=function(d){if(!window.DOMParser){var c=["Msxml2.DOMDocument.3.0","Msxml2.DOMDocument"];for(var b=0;b<c.length;b++)try{var a=new ActiveXObject(c[b]);a.async=false;a.loadXML(d);a.setProperty("SelectionLanguage","XPath");return a}catch(f){}return null}else try{var e=new window.DOMParser;return e.parseFromString(d,"text/xml")}catch(f){return null}return null};Sys.Net.XMLHttpExecutor=function(){Sys.Net.XMLHttpExecutor.initializeBase(this);var a=this;this._xmlHttpRequest=null;this._webRequest=null;this._responseAvailable=false;this._timedOut=false;this._timer=null;this._aborted=false;this._started=false;this._onReadyStateChange=function(){if(a._xmlHttpRequest.readyState===4){a._clearTimer();a._responseAvailable=true;a._webRequest.completed(Sys.EventArgs.Empty);if(a._xmlHttpRequest!=null){a._xmlHttpRequest.onreadystatechange=Function.emptyMethod;a._xmlHttpRequest=null}}};this._clearTimer=function(){if(a._timer!=null){window.clearTimeout(a._timer);a._timer=null}};this._onTimeout=function(){if(!a._responseAvailable){a._clearTimer();a._timedOut=true;a._xmlHttpRequest.onreadystatechange=Function.emptyMethod;a._xmlHttpRequest.abort();a._webRequest.completed(Sys.EventArgs.Empty);a._xmlHttpRequest=null}}};Sys.Net.XMLHttpExecutor.prototype={get_timedOut:function(){return this._timedOut},get_started:function(){return this._started},get_responseAvailable:function(){return this._responseAvailable},get_aborted:function(){return this._aborted},executeRequest:function(){this._webRequest=this.get_webRequest();var c=this._webRequest.get_body(),a=this._webRequest.get_headers();this._xmlHttpRequest=new XMLHttpRequest;this._xmlHttpRequest.onreadystatechange=this._onReadyStateChange;var e=this._webRequest.get_httpVerb();this._xmlHttpRequest.open(e,this._webRequest.getResolvedUrl(),true);if(a)for(var b in a){var f=a[b];if(typeof f!=="function")this._xmlHttpRequest.setRequestHeader(b,f)}if(e.toLowerCase()==="post"){if(a===null||!a["Content-Type"])this._xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");if(!c)c=""}var d=this._webRequest.get_timeout();if(d>0)this._timer=window.setTimeout(Function.createDelegate(this,this._onTimeout),d);this._xmlHttpRequest.send(c);this._started=true},getResponseHeader:function(b){var a;try{a=this._xmlHttpRequest.getResponseHeader(b)}catch(c){}if(!a)a="";return a},getAllResponseHeaders:function(){return this._xmlHttpRequest.getAllResponseHeaders()},get_responseData:function(){return this._xmlHttpRequest.responseText},get_statusCode:function(){return this._xmlHttpRequest.status},get_statusText:function(){return this._xmlHttpRequest.statusText},get_xml:function(){var a=this._xmlHttpRequest.responseXML;if(!a||!a.documentElement){a=new XMLDOM(this._xmlHttpRequest.responseText);if(!a||!a.documentElement)return null}else if(navigator.userAgent.indexOf("MSIE")!==-1)a.setProperty("SelectionLanguage","XPath");if(a.documentElement.namespaceURI==="http://www.mozilla.org/newlayout/xml/parsererror.xml"&&a.documentElement.tagName==="parsererror")return null;if(a.documentElement.firstChild&&a.documentElement.firstChild.tagName==="parsererror")return null;return a},abort:function(){if(this._aborted||this._responseAvailable||this._timedOut)return;this._aborted=true;this._clearTimer();if(this._xmlHttpRequest&&!this._responseAvailable){this._xmlHttpRequest.onreadystatechange=Function.emptyMethod;this._xmlHttpRequest.abort();this._xmlHttpRequest=null;var a=this._webRequest._get_eventHandlerList().getHandler("completed");if(a)a(this,Sys.EventArgs.Empty)}}};Sys.Net.XMLHttpExecutor.registerClass("Sys.Net.XMLHttpExecutor",Sys.Net.WebRequestExecutor);Sys.Net._WebRequestManager=function(){this._this=this;this._defaultTimeout=0;this._defaultExecutorType="Sys.Net.XMLHttpExecutor"};Sys.Net._WebRequestManager.prototype={add_invokingRequest:function(a){this._get_eventHandlerList().addHandler("invokingRequest",a)},remove_invokingRequest:function(a){this._get_eventHandlerList().removeHandler("invokingRequest",a)},add_completedRequest:function(a){this._get_eventHandlerList().addHandler("completedRequest",a)},remove_completedRequest:function(a){this._get_eventHandlerList().removeHandler("completedRequest",a)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_defaultTimeout:function(){return this._defaultTimeout},set_defaultTimeout:function(a){this._defaultTimeout=a},get_defaultExecutorType:function(){return this._defaultExecutorType},set_defaultExecutorType:function(a){this._defaultExecutorType=a},executeRequest:function(webRequest){var executor=webRequest.get_executor();if(!executor){var failed=false;try{var executorType=eval(this._defaultExecutorType);executor=new executorType}catch(a){failed=true}webRequest.set_executor(executor)}if(executor.get_aborted())return;var evArgs=new Sys.Net.NetworkRequestEventArgs(webRequest),handler=this._get_eventHandlerList().getHandler("invokingRequest");if(handler)handler(this,evArgs);if(!evArgs.get_cancel())executor.executeRequest()}};Sys.Net._WebRequestManager.registerClass("Sys.Net._WebRequestManager");Sys.Net.WebRequestManager=new Sys.Net._WebRequestManager;Sys.Net.NetworkRequestEventArgs=function(a){Sys.Net.NetworkRequestEventArgs.initializeBase(this);this._webRequest=a};Sys.Net.NetworkRequestEventArgs.prototype={get_webRequest:function(){return this._webRequest}};Sys.Net.NetworkRequestEventArgs.registerClass("Sys.Net.NetworkRequestEventArgs",Sys.CancelEventArgs);Sys.Net.WebRequest=function(){this._url="";this._headers={};this._body=null;this._userContext=null;this._httpVerb=null;this._executor=null;this._invokeCalled=false;this._timeout=0};Sys.Net.WebRequest.prototype={add_completed:function(a){this._get_eventHandlerList().addHandler("completed",a)},remove_completed:function(a){this._get_eventHandlerList().removeHandler("completed",a)},completed:function(b){var a=Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest");if(a)a(this._executor,b);a=this._get_eventHandlerList().getHandler("completed");if(a)a(this._executor,b)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_url:function(){return this._url},set_url:function(a){this._url=a},get_headers:function(){return this._headers},get_httpVerb:function(){if(this._httpVerb===null){if(this._body===null)return "GET";return "POST"}return this._httpVerb},set_httpVerb:function(a){this._httpVerb=a},get_body:function(){return this._body},set_body:function(a){this._body=a},get_userContext:function(){return this._userContext},set_userContext:function(a){this._userContext=a},get_executor:function(){return this._executor},set_executor:function(a){this._executor=a;this._executor._set_webRequest(this)},get_timeout:function(){if(this._timeout===0)return Sys.Net.WebRequestManager.get_defaultTimeout();return this._timeout},set_timeout:function(a){this._timeout=a},getResolvedUrl:function(){return Sys.Net.WebRequest._resolveUrl(this._url)},invoke:function(){Sys.Net.WebRequestManager.executeRequest(this);this._invokeCalled=true}};Sys.Net.WebRequest._resolveUrl=function(b,a){if(b&&b.indexOf("://")!==-1)return b;if(!a||a.length===0){var c=document.getElementsByTagName("base")[0];if(c&&c.href&&c.href.length>0)a=c.href;else a=document.URL}var d=a.indexOf("?");if(d!==-1)a=a.substr(0,d);a=a.substr(0,a.lastIndexOf("/")+1);if(!b||b.length===0)return a;if(b.charAt(0)==="/"){var e=a.indexOf("://"),g=a.indexOf("/",e+3);return a.substr(0,g)+b}else{var f=a.lastIndexOf("/");return a.substr(0,f+1)+b}};Sys.Net.WebRequest._createQueryString=function(d,b){if(!b)b=encodeURIComponent;var a=new Sys.StringBuilder,f=0;for(var c in d){var e=d[c];if(typeof e==="function")continue;var g=Sys.Serialization.JavaScriptSerializer.serialize(e);if(f!==0)a.append("&");a.append(c);a.append("=");a.append(b(g));f++}return a.toString()};Sys.Net.WebRequest._createUrl=function(a,b){if(!b)return a;var d=Sys.Net.WebRequest._createQueryString(b);if(d.length>0){var c="?";if(a&&a.indexOf("?")!==-1)c="&";return a+c+d}else return a};Sys.Net.WebRequest.registerClass("Sys.Net.WebRequest");Sys.Net.WebServiceProxy=function(){};Sys.Net.WebServiceProxy.prototype={set_timeout:function(a){this._timeout=a},get_timeout:function(){return this._timeout},set_defaultUserContext:function(a){this._userContext=a},get_defaultUserContext:function(){return this._userContext},set_defaultSucceededCallback:function(a){this._succeeded=a},get_defaultSucceededCallback:function(){return this._succeeded},set_defaultFailedCallback:function(a){this._failed=a},get_defaultFailedCallback:function(){return this._failed},set_path:function(a){this._path=a},get_path:function(){return this._path},_invoke:function(d,e,g,f,c,b,a){if(c===null||typeof c==="undefined")c=this.get_defaultSucceededCallback();if(b===null||typeof b==="undefined")b=this.get_defaultFailedCallback();if(a===null||typeof a==="undefined")a=this.get_defaultUserContext();return Sys.Net.WebServiceProxy.invoke(d,e,g,f,c,b,a,this.get_timeout())}};Sys.Net.WebServiceProxy.registerClass("Sys.Net.WebServiceProxy");Sys.Net.WebServiceProxy.invoke=function(k,a,j,d,i,c,f,h){var b=new Sys.Net.WebRequest;b.get_headers()["Content-Type"]="application/json; charset=utf-8";if(!d)d={};var g=d;if(!j||!g)g={};b.set_url(Sys.Net.WebRequest._createUrl(k+"/"+a,g));var e=null;if(!j){e=Sys.Serialization.JavaScriptSerializer.serialize(d);if(e==="{}")e=""}b.set_body(e);b.add_completed(l);if(h&&h>0)b.set_timeout(h);b.invoke();function l(d){if(d.get_responseAvailable()){var e=d.get_statusCode(),b=null;try{var j=d.getResponseHeader("Content-Type");if(j.startsWith("application/json"))b=d.get_object();else if(j.startsWith("text/xml"))b=d.get_xml();else b=d.get_responseData()}catch(m){}var k=d.getResponseHeader("jsonerror"),g=k==="true";if(g)b=new Sys.Net.WebServiceError(false,b.Message,b.StackTrace,b.ExceptionType);if(e<200||e>=300||g){if(c){if(!b||!g)b=new Sys.Net.WebServiceError(false,String.format(Sys.Res.webServiceFailedNoMsg,a),"","");b._statusCode=e;c(b,f,a)}}else if(i)i(b,f,a)}else{var h;if(d.get_timedOut())h=String.format(Sys.Res.webServiceTimedOut,a);else h=String.format(Sys.Res.webServiceFailedNoMsg,a);if(c)c(new Sys.Net.WebServiceError(d.get_timedOut(),h,"",""),f,a)}}return b};Sys.Net.WebServiceProxy._generateTypedConstructor=function(a){return function(b){if(b)for(var c in b)this[c]=b[c];this.__type=a}};Sys.Net.WebServiceError=function(c,d,b,a){this._timedOut=c;this._message=d;this._stackTrace=b;this._exceptionType=a;this._statusCode=-1};Sys.Net.WebServiceError.prototype={get_timedOut:function(){return this._timedOut},get_statusCode:function(){return this._statusCode},get_message:function(){return this._message},get_stackTrace:function(){return this._stackTrace},get_exceptionType:function(){return this._exceptionType}};Sys.Net.WebServiceError.registerClass("Sys.Net.WebServiceError");Type.registerNamespace("Sys.Services");Sys.Services._ProfileService=function(){Sys.Services._ProfileService.initializeBase(this);this.properties={}};Sys.Services._ProfileService.DefaultWebServicePath="";Sys.Services._ProfileService.prototype={_defaultFailedCallback:null,_defaultLoadCompletedCallback:null,_defaultSaveCompletedCallback:null,_path:"",_timeout:0,get_defaultFailedCallback:function(){return this._defaultFailedCallback},set_defaultFailedCallback:function(a){this._defaultFailedCallback=a},get_defaultLoadCompletedCallback:function(){return this._defaultLoadCompletedCallback},set_defaultLoadCompletedCallback:function(a){this._defaultLoadCompletedCallback=a},get_defaultSaveCompletedCallback:function(){return this._defaultSaveCompletedCallback},set_defaultSaveCompletedCallback:function(a){this._defaultSaveCompletedCallback=a},get_path:function(){return this._path},set_path:function(a){if(!a||!a.length)a="";this._path=a},get_timeout:function(){return this._timeout},set_timeout:function(a){this._timeout=a},load:function(b,d,e,f){var c={},a;if(!b)a="GetAllPropertiesForCurrentUser";else{a="GetPropertiesForCurrentUser";c={properties:this._clonePropertyNames(b)}}this._invoke(this._get_path(),a,false,c,Function.createDelegate(this,this._onLoadComplete),Function.createDelegate(this,this._onLoadFailed),[d,e,f])},save:function(d,a,c,e){var b=this._flattenProperties(d,this.properties);this._invoke(this._get_path(),"SetPropertiesForCurrentUser",false,{values:b},Function.createDelegate(this,this._onSaveComplete),Function.createDelegate(this,this._onSaveFailed),[a,c,e])},_clonePropertyNames:function(e){var c=[],d={};for(var b=0;b<e.length;b++){var a=e[b];if(!d[a]){Array.add(c,a);d[a]=true}}return c},_flattenProperties:function(a,h,i){var b={},e,d;if(a&&a.length===0)return b;for(var c in h){e=h[c];d=i?i+"."+c:c;if(Sys.Services.ProfileGroup.isInstanceOfType(e)){var g=this._flattenProperties(a,e,d);for(var f in g){var j=g[f];b[f]=j}}else if(!a||Array.indexOf(a,d)!==-1)b[d]=e}return b},_get_path:function(){var a=this.get_path();if(!a.length)a=Sys.Services._ProfileService.DefaultWebServicePath;if(!a||!a.length)throw Error.invalidOperation(Sys.Res.servicePathNotSet);return a},_onLoadComplete:function(a,f,g){if(typeof a!=="object")throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType,g,"Object"));var d=this._unflattenProperties(a);for(var b in d)this.properties[b]=d[b];var c=f[0],e=c?c:this._defaultLoadCompletedCallback;if(e)e(a.length,f[2],"Sys.Services.ProfileService.load")},_onLoadFailed:function(d,c){var a=c[1],b=a?a:this._defaultFailedCallback;if(b)b(d,c[2],"Sys.Services.ProfileService.load")},_onSaveComplete:function(d,c,f){if(typeof d!=="number")throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType,f,"Number"));var a=c[0],e=c[2],b=a?a:this._defaultSaveCompletedCallback;if(b)b(d,e,"Sys.Services.ProfileService.save")},_onSaveFailed:function(e,c){var a=c[1],d=c[2],b=a?a:this._defaultFailedCallback;if(b)b(e,d,"Sys.Services.ProfileService.save")},_unflattenProperties:function(e){var c={},d,f,h=0;for(var a in e){h++;f=e[a];d=a.indexOf(".");if(d!==-1){var g=a.substr(0,d);a=a.substr(d+1);var b=c[g];if(!b||!Sys.Services.ProfileGroup.isInstanceOfType(b)){b=new Sys.Services.ProfileGroup;c[g]=b}b[a]=f}else c[a]=f}e.length=h;return c}};Sys.Services._ProfileService.registerClass("Sys.Services._ProfileService",Sys.Net.WebServiceProxy);Sys.Services.ProfileService=new Sys.Services._ProfileService;Sys.Services.ProfileGroup=function(a){if(a)for(var b in a)this[b]=a[b]};Sys.Services.ProfileGroup.registerClass("Sys.Services.ProfileGroup");Sys.Services._AuthenticationService=function(){Sys.Services._AuthenticationService.initializeBase(this)};Sys.Services._AuthenticationService.DefaultWebServicePath="";Sys.Services._AuthenticationService.prototype={_defaultFailedCallback:null,_defaultLoginCompletedCallback:null,_defaultLogoutCompletedCallback:null,_path:"",_timeout:0,_authenticated:false,get_defaultFailedCallback:function(){return this._defaultFailedCallback},set_defaultFailedCallback:function(a){this._defaultFailedCallback=a},get_defaultLoginCompletedCallback:function(){return this._defaultLoginCompletedCallback},set_defaultLoginCompletedCallback:function(a){this._defaultLoginCompletedCallback=a},get_defaultLogoutCompletedCallback:function(){return this._defaultLogoutCompletedCallback},set_defaultLogoutCompletedCallback:function(a){this._defaultLogoutCompletedCallback=a},get_isLoggedIn:function(){return this._authenticated},get_path:function(){return this._path},set_path:function(a){if(!a||!a.length)a="";this._path=a},get_timeout:function(){return this._timeout},set_timeout:function(a){this._timeout=a},login:function(c,b,a,h,f,d,e,g){this._invoke(this._get_path(),"Login",false,{userName:c,password:b,createPersistentCookie:a},Function.createDelegate(this,this._onLoginComplete),Function.createDelegate(this,this._onLoginFailed),[c,b,a,f,d,e,g])},logout:function(c,a,b,d){this._invoke(this._get_path(),"Logout",false,{},Function.createDelegate(this,this._onLogoutComplete),Function.createDelegate(this,this._onLogoutFailed),[c,a,b,d])},_get_path:function(){var a=this.get_path();if(!a.length)a=Sys.Services._AuthenticationService.DefaultWebServicePath;if(!a||!a.length)throw Error.invalidOperation(Sys.Res.servicePathNotSet);return a},_onLoginComplete:function(f,c,g){if(typeof f!=="boolean")throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType,g,"Boolean"));var b=c[3],d=c[4],e=c[6],a=d?d:this._defaultLoginCompletedCallback;if(f){this._authenticated=true;if(a)a(true,e,"Sys.Services.AuthenticationService.login");if(typeof b!=="undefined"&&b!==null)window.location.href=b}else if(a)a(false,e,"Sys.Services.AuthenticationService.login")},_onLoginFailed:function(d,c){var a=c[5],b=a?a:this._defaultFailedCallback;if(b)b(d,c[6],"Sys.Services.AuthenticationService.login")},_onLogoutComplete:function(g,a,f){if(g!==null)throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType,f,"null"));var c=a[0],b=a[1],e=a[3],d=b?b:this._defaultLogoutCompletedCallback;this._authenticated=false;if(d)d(null,e,"Sys.Services.AuthenticationService.logout");if(!c)window.location.reload();else window.location.href=c},_onLogoutFailed:function(d,c){var a=c[2],b=a?a:this._defaultFailedCallback;if(b)b(d,c[3],"Sys.Services.AuthenticationService.logout")},_setAuthenticated:function(a){this._authenticated=a}};Sys.Services._AuthenticationService.registerClass("Sys.Services._AuthenticationService",Sys.Net.WebServiceProxy);Sys.Services.AuthenticationService=new Sys.Services._AuthenticationService;Type.registerNamespace("Sys.Serialization");Sys.Serialization.JavaScriptSerializer=function(){};Sys.Serialization.JavaScriptSerializer.registerClass("Sys.Serialization.JavaScriptSerializer");Sys.Serialization.JavaScriptSerializer._stringRegEx=new RegExp('["\b\f\n\r\t\\\\\x00-\x1F]',"i");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder=function(b,a,h){var c;switch(typeof b){case "object":if(b)if(Array.isInstanceOfType(b)){a.append("[");for(c=0;c<b.length;++c){if(c>0)a.append(",");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(b[c],a)}a.append("]")}else{if(Date.isInstanceOfType(b)){a.append('"\\/Date(');a.append(b.getTime());a.append(')\\/"');break}var e=[],i=0;for(var g in b){if(g.startsWith("$"))continue;e[i++]=g}if(h)e.sort();a.append("{");var j=false;for(c=0;c<i;c++){var f=b[e[c]];if(typeof f!=="undefined"&&typeof f!=="function"){if(j)a.append(",");else j=true;Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(e[c],a,h);a.append(":");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(f,a,h)}}a.append("}")}else a.append("null");break;case "number":if(isFinite(b))a.append(String(b));else throw Error.invalidOperation(Sys.Res.cannotSerializeNonFiniteNumbers);break;case "string":a.append('"');if(Sys.Browser.agent===Sys.Browser.Safari||Sys.Serialization.JavaScriptSerializer._stringRegEx.test(b)){var k=b.length;for(c=0;c<k;++c){var d=b.charAt(c);if(d>=" "){if(d==="\\"||d==='"')a.append("\\");a.append(d)}else switch(d){case "\b":a.append("\\b");break;case "\f":a.append("\\f");break;case "\n":a.append("\\n");break;case "\r":a.append("\\r");break;case "\t":a.append("\\t");break;default:a.append("\\u00");if(d.charCodeAt()<16)a.append("0");a.append(d.charCodeAt().toString(16))}}}else a.append(b);a.append('"');break;case "boolean":a.append(b.toString());break;default:a.append("null");break}};Sys.Serialization.JavaScriptSerializer.serialize=function(b){var a=new Sys.StringBuilder;Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(b,a,false);return a.toString()};Sys.Serialization.JavaScriptSerializer.deserialize=function(data){if(data.length===0)throw Error.argument("data",Sys.Res.cannotDeserializeEmptyString);try{var exp=data.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"',"g"),"$1new Date($2)");return eval("("+exp+")")}catch(a){throw Error.argument("data",Sys.Res.cannotDeserializeInvalidJson)}};Sys.CultureInfo=function(c,b,a){this.name=c;this.numberFormat=b;this.dateTimeFormat=a};Sys.CultureInfo.prototype={_getDateTimeFormats:function(){if(!this._dateTimeFormats){var a=this.dateTimeFormat;this._dateTimeFormats=[a.MonthDayPattern,a.YearMonthPattern,a.ShortDatePattern,a.ShortTimePattern,a.LongDatePattern,a.LongTimePattern,a.FullDateTimePattern,a.RFC1123Pattern,a.SortableDateTimePattern,a.UniversalSortableDateTimePattern]}return this._dateTimeFormats},_getMonthIndex:function(a){if(!this._upperMonths)this._upperMonths=this._toUpperArray(this.dateTimeFormat.MonthNames);return Array.indexOf(this._upperMonths,this._toUpper(a))},_getAbbrMonthIndex:function(a){if(!this._upperAbbrMonths)this._upperAbbrMonths=this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);return Array.indexOf(this._upperMonths,this._toUpper(a))},_getDayIndex:function(a){if(!this._upperDays)this._upperDays=this._toUpperArray(this.dateTimeFormat.DayNames);return Array.indexOf(this._upperDays,this._toUpper(a))},_getAbbrDayIndex:function(a){if(!this._upperAbbrDays)this._upperAbbrDays=this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames);return Array.indexOf(this._upperAbbrDays,this._toUpper(a))},_toUpperArray:function(c){var b=[];for(var a=0,d=c.length;a<d;a++)b[a]=this._toUpper(c[a]);return b},_toUpper:function(a){return a.split("\u00A0").join(" ").toUpperCase()}};Sys.CultureInfo._parse=function(b){var a=Sys.Serialization.JavaScriptSerializer.deserialize(b);return new Sys.CultureInfo(a.name,a.numberFormat,a.dateTimeFormat)};Sys.CultureInfo.registerClass("Sys.CultureInfo");Sys.CultureInfo.InvariantCulture=Sys.CultureInfo._parse('{"name":"","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}');if(typeof __cultureInfo==="undefined")var __cultureInfo='{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":false,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":false},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM dd, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM dd, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"MMMM, yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":false,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}';Sys.CultureInfo.CurrentCulture=Sys.CultureInfo._parse(__cultureInfo);delete __cultureInfo;Sys.UI.Point=function(a,b){this.x=a;this.y=b};Sys.UI.Point.registerClass("Sys.UI.Point");Sys.UI.Bounds=function(c,d,b,a){this.x=c;this.y=d;this.height=a;this.width=b};Sys.UI.Bounds.registerClass("Sys.UI.Bounds");Sys.UI.DomElement=function(){};Sys.UI.DomElement.registerClass("Sys.UI.DomElement");Sys.UI.DomElement.addCssClass=function(a,b){if(!Sys.UI.DomElement.containsCssClass(a,b))if(a.className==="")a.className=b;else a.className+=" "+b};Sys.UI.DomElement.containsCssClass=function(b,a){return Array.contains(b.className.split(" "),a)};Sys.UI.DomElement.getBounds=function(a){var b=Sys.UI.DomElement.getLocation(a);return new Sys.UI.Bounds(b.x,b.y,a.offsetWidth||0,a.offsetHeight||0)};var $get=Sys.UI.DomElement.getElementById=function(f,e){if(!e)return document.getElementById(f);if(e.getElementById)return e.getElementById(f);var c=[],d=e.childNodes;for(var b=0;b<d.length;b++){var a=d[b];if(a.nodeType==1)c[c.length]=a}while(c.length){a=c.shift();if(a.id==f)return a;d=a.childNodes;for(b=0;b<d.length;b++){a=d[b];if(a.nodeType==1)c[c.length]=a}}return null};switch(Sys.Browser.agent){case Sys.Browser.InternetExplorer:Sys.UI.DomElement.getLocation=function Sys$UI$DomElement$getLocation(a){if(a.self||a.nodeType===9)return new Sys.UI.Point(0,0);var d=a.getClientRects();if(!d||!d.length)return new Sys.UI.Point(0,0);var e=a.ownerDocument.parentWindow,g=e.screenLeft-top.screenLeft-top.document.documentElement.scrollLeft+2,h=e.screenTop-top.screenTop-top.document.documentElement.scrollTop+2,c=e.frameElement||null;if(c){var b=c.currentStyle;g+=(c.frameBorder||1)*2+(parseInt(b.paddingLeft)||0)+(parseInt(b.borderLeftWidth)||0)-a.ownerDocument.documentElement.scrollLeft;h+=(c.frameBorder||1)*2+(parseInt(b.paddingTop)||0)+(parseInt(b.borderTopWidth)||0)-a.ownerDocument.documentElement.scrollTop}var f=d[0];return new Sys.UI.Point(f.left-g,f.top-h)};break;case Sys.Browser.Safari:Sys.UI.DomElement.getLocation=function(c){if(c.window&&c.window===c||c.nodeType===9)return new Sys.UI.Point(0,0);var g=0,h=0,j=null,f=null,b;for(var a=c;a;j=a,(f=b,a=a.offsetParent)){b=Sys.UI.DomElement._getCurrentStyle(a);var e=a.tagName;if((a.offsetLeft||a.offsetTop)&&(e!=="BODY"||(!f||f.position!=="absolute"))){g+=a.offsetLeft;h+=a.offsetTop}}b=Sys.UI.DomElement._getCurrentStyle(c);var d=b?b.position:null,k=d&&d!=="static";if(!d||d!=="absolute")for(var a=c.parentNode;a;a=a.parentNode){e=a.tagName;if(e!=="BODY"&&e!=="HTML"&&(a.scrollLeft||a.scrollTop)){g-=a.scrollLeft||0;h-=a.scrollTop||0}b=Sys.UI.DomElement._getCurrentStyle(a);var i=b?b.position:null;if(i&&i==="absolute")break}return new Sys.UI.Point(g,h)};break;case Sys.Browser.Opera:Sys.UI.DomElement.getLocation=function(b){if(b.window&&b.window===b||b.nodeType===9)return new Sys.UI.Point(0,0);var d=0,e=0,i=null;for(var a=b;a;i=a,a=a.offsetParent){var f=a.tagName;d+=a.offsetLeft||0;e+=a.offsetTop||0}var g=b.style.position,c=g&&g!=="static";for(var a=b.parentNode;a;a=a.parentNode){f=a.tagName;if(f!=="BODY"&&f!=="HTML"&&(a.scrollLeft||a.scrollTop)&&(c&&(a.style.overflow==="scroll"||a.style.overflow==="auto"))){d-=a.scrollLeft||0;e-=a.scrollTop||0}var h=a&&a.style?a.style.position:null;c=c||h&&h!=="static"}return new Sys.UI.Point(d,e)};break;default:Sys.UI.DomElement.getLocation=function(d){if(d.window&&d.window===d||d.nodeType===9)return new Sys.UI.Point(0,0);var e=0,f=0,i=null,h=null,b=null;for(var a=d;a;i=a,(h=b,a=a.offsetParent)){var c=a.tagName;b=Sys.UI.DomElement._getCurrentStyle(a);if((a.offsetLeft||a.offsetTop)&&!(c==="BODY"&&(!h||h.position!=="absolute"))){e+=a.offsetLeft;f+=a.offsetTop}if(i!==null&&b){if(c!=="TABLE"&&c!=="TD"&&c!=="HTML"){e+=parseInt(b.borderLeftWidth)||0;f+=parseInt(b.borderTopWidth)||0}if(c==="TABLE"&&(b.position==="relative"||b.position==="absolute")){e+=parseInt(b.marginLeft)||0;f+=parseInt(b.marginTop)||0}}}b=Sys.UI.DomElement._getCurrentStyle(d);var g=b?b.position:null,j=g&&g!=="static";if(!g||g!=="absolute")for(var a=d.parentNode;a;a=a.parentNode){c=a.tagName;if(c!=="BODY"&&c!=="HTML"&&(a.scrollLeft||a.scrollTop)){e-=a.scrollLeft||0;f-=a.scrollTop||0;b=Sys.UI.DomElement._getCurrentStyle(a);e+=parseInt(b.borderLeftWidth)||0;f+=parseInt(b.borderTopWidth)||0}}return new Sys.UI.Point(e,f)};break}Sys.UI.DomElement.removeCssClass=function(d,c){var a=" "+d.className+" ",b=a.indexOf(" "+c+" ");if(b>=0)d.className=(a.substr(0,b)+" "+a.substring(b+c.length+1,a.length)).trim()};Sys.UI.DomElement.setLocation=function(b,c,d){var a=b.style;a.position="absolute";a.left=c+"px";a.top=d+"px"};Sys.UI.DomElement.toggleCssClass=function(b,a){if(Sys.UI.DomElement.containsCssClass(b,a))Sys.UI.DomElement.removeCssClass(b,a);else Sys.UI.DomElement.addCssClass(b,a)};Sys.UI.DomElement._getCurrentStyle=function(a){var b=(a.ownerDocument?a.ownerDocument:a.documentElement).defaultView;return b&&a!==b&&b.getComputedStyle?b.getComputedStyle(a,null):a.style};Sys.UI.Behavior=function(b){Sys.UI.Behavior.initializeBase(this);this._element=b;var a=b._behaviors;if(!a)b._behaviors=[this];else a[a.length]=this};Sys.UI.Behavior.prototype={_name:null,get_element:function(){return this._element},get_id:function(){var a=Sys.UI.Behavior.callBaseMethod(this,"get_id");if(a)return a;if(!this._element||!this._element.id)return "";return this._element.id+"$"+this.get_name()},get_name:function(){if(this._name)return this._name;var a=Object.getTypeName(this),b=a.lastIndexOf(".");if(b!=-1)a=a.substr(b+1);if(!this.get_isInitialized())this._name=a;return a},set_name:function(a){this._name=a},initialize:function(){Sys.UI.Behavior.callBaseMethod(this,"initialize");var a=this.get_name();if(a)this._element[a]=this},dispose:function(){Sys.UI.Behavior.callBaseMethod(this,"dispose");if(this._element){var a=this.get_name();if(a)this._element[a]=null;Array.remove(this._element._behaviors,this);delete this._element}}};Sys.UI.Behavior.registerClass("Sys.UI.Behavior",Sys.Component);Sys.UI.Behavior.getBehaviorByName=function(b,c){var a=b[c];return a&&Sys.UI.Behavior.isInstanceOfType(a)?a:null};Sys.UI.Behavior.getBehaviors=function(a){if(!a._behaviors)return [];return Array.clone(a._behaviors)};Sys.UI.Behavior.getBehaviorsByType=function(d,e){var a=d._behaviors,c=[];if(a)for(var b=0,f=a.length;b<f;b++)if(e.isInstanceOfType(a[b]))c[c.length]=a[b];return c};Sys.UI.VisibilityMode=function(){throw Error.notImplemented()};Sys.UI.VisibilityMode.prototype={hide:0,collapse:1};Sys.UI.VisibilityMode.registerEnum("Sys.UI.VisibilityMode");Sys.UI.Control=function(a){Sys.UI.Control.initializeBase(this);this._element=a;a.control=this;this._oldDisplayMode=this._element.style.display;if(!this._oldDisplayMode||this._oldDisplayMode=="none")this._oldDisplayMode=""};Sys.UI.Control.prototype={_parent:null,_visibilityMode:Sys.UI.VisibilityMode.hide,get_element:function(){return this._element},get_id:function(){if(!this._element)return "";return this._element.id},set_id:function(){throw Error.invalidOperation(Sys.Res.cantSetId)},get_parent:function(){if(this._parent)return this._parent;else{var a=this._element.parentNode;while(a){if(a.control)return a.control;a=a.parentNode}return null}},set_parent:function(a){this._parent=a},get_visibilityMode:function(){return this._visibilityMode},set_visibilityMode:function(a){if(this._visibilityMode!==a){this._visibilityMode=a;if(this.get_visible()===false)if(this._visibilityMode===Sys.UI.VisibilityMode.hide)this._element.style.display=this._oldDisplayMode;else this._element.style.display="none"}this._visibilityMode=a},get_visible:function(){return this._element.style.visibility!="hidden"},set_visible:function(a){if(a!=this.get_visible()){this._element.style.visibility=a?"visible":"hidden";if(a||this._visibilityMode===Sys.UI.VisibilityMode.hide)this._element.style.display=this._oldDisplayMode;else this._element.style.display="none"}},addCssClass:function(a){Sys.UI.DomElement.addCssClass(this._element,a)},dispose:function(){Sys.UI.Control.callBaseMethod(this,"dispose");if(this._element){this._element.control=undefined;delete this._element}},initialize:function(){Sys.UI.Control.callBaseMethod(this,"initialize");var a=this._element},onBubbleEvent:function(){return false},raiseBubbleEvent:function(b,c){var a=this.get_parent();while(a){if(a.onBubbleEvent(b,c))return;a=a.get_parent()}},removeCssClass:function(a){Sys.UI.DomElement.removeCssClass(this._element,a)},toggleCssClass:function(a){Sys.UI.DomElement.toggleCssClass(this._element,a)}};Sys.UI.Control.registerClass("Sys.UI.Control",Sys.Component)
Sys.Res={
"argumentInteger":"Value must be an integer.","scriptLoadMultipleCallbacks":"The script \u0027{0}\u0027 contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed.","invokeCalledTwice":"Cannot call invoke more than once.","webServiceFailed":"The server method \u0027{0}\u0027 failed with the following error: {1}","argumentType":"Object cannot be converted to the required type.","argumentNull":"Value cannot be null.","controlCantSetId":"The id property can\u0027t be set on a control.","formatBadFormatSpecifier":"Format specifier was invalid.","webServiceFailedNoMsg":"The server method \u0027{0}\u0027 failed.","argumentDomElement":"Value must be a DOM element.","invalidExecutorType":"Could not create a valid Sys.Net.WebRequestExecutor from: {0}.","cannotCallBeforeResponse":"Cannot call {0} when responseAvailable is false.","actualValue":"Actual value was {0}.","enumInvalidValue":"\u0027{0}\u0027 is not a valid value for enum {1}.","scriptLoadFailed":"The script \u0027{0}\u0027 could not be loaded.","parameterCount":"Parameter count mismatch.","cannotDeserializeEmptyString":"Cannot deserialize empty string.","formatInvalidString":"Input string was not in a correct format.","invalidTimeout":"Value must be greater than or equal to zero.","cannotAbortBeforeStart":"Cannot abort when executor has not started.","argument":"Value does not fall within the expected range.","cannotDeserializeInvalidJson":"Cannot deserialize. The data does not correspond to valid JSON.","invalidHttpVerb":"httpVerb cannot be set to an empty or null string.","nullWebRequest":"Cannot call executeRequest with a null webRequest.","eventHandlerInvalid":"Handler was not added through the Sys.UI.DomEvent.addHandler method.","cannotSerializeNonFiniteNumbers":"Cannot serialize non finite numbers.","argumentUndefined":"Value cannot be undefined.","webServiceInvalidReturnType":"The server method \u0027{0}\u0027 returned an invalid type. Expected type: {1}","servicePathNotSet":"The path to the web service has not been set.","argumentTypeWithTypes":"Object of type \u0027{0}\u0027 cannot be converted to type \u0027{1}\u0027.","cannotCallOnceStarted":"Cannot call {0} once started.","badBaseUrl1":"Base URL does not contain ://.","badBaseUrl2":"Base URL does not contain another /.","badBaseUrl3":"Cannot find last / in base URL.","setExecutorAfterActive":"Cannot set executor after it has become active.","paramName":"Parameter name: {0}","cannotCallOutsideHandler":"Cannot call {0} outside of a completed event handler.","format":"One of the identified items was in an invalid format.","assertFailedCaller":"Assertion Failed: {0}\r\nat {1}","argumentOutOfRange":"Specified argument was out of the range of valid values.","webServiceTimedOut":"The server method \u0027{0}\u0027 timed out.","notImplemented":"The method or operation is not implemented.","assertFailed":"Assertion Failed: {0}","invalidOperation":"Operation is not valid due to the current state of the object.","breakIntoDebugger":"{0}\r\n\r\nBreak into debugger?"};
/* END MicrosoftAjax.js */
/* START Telerik.Web.UI.Common.Core.js */
// Avoids the background image flickering in IE 6 (http://www.mister-pixel.com/)
try
{
	document.execCommand("BackgroundImageCache", false, true);
}
catch(err) {}

Type.registerNamespace("Telerik.Web.UI");

window.$telerik = window.TelerikCommonScripts = Telerik.Web.CommonScripts = {

    //NEW
    getOuterSize : function(element) 
    {                       
        var size = $telerik.getSize(element);
        var marginBox = $telerik.getMarginBox(element);
        
        return {
            x :  size.x - marginBox.left,
            y : size.y -  marginBox.top, 
            width : size.width + marginBox.left + marginBox.right, 
            height: size.height + marginBox.top + marginBox.bottom
        }
    },
    

	_borderStyleNames : ['borderTopStyle','borderRightStyle','borderBottomStyle','borderLeftStyle'],
	_borderWidthNames : ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'],
	_paddingWidthNames : ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],
	_marginWidthNames : ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'],
	radControls : [],
	
	registerControl : function (control)
	{
		if (!Array.contains(this.radControls, control))
			Array.add(this.radControls, control);
	},
	
	unregisterControl : function (control)
	{
		Array.remove(this.radControls, control);
	},
	
	repaintChildren : function (parentControl)
	{
		var parentElement = parentControl.get_element();
		
		for (var i = 0, length = this.radControls.length; i < length; i ++)
		{
	        var control = this.radControls[i];
        
		    if (control.repaint && this.isDescendant(parentElement, control.get_element()))
				control.repaint();
		}
	},
	
	_borderThickness : function ()
	{
		$telerik._borderThicknesses = { };

		var div0 = document.createElement('div');
		var div1 = document.createElement('div');

		div0.style.visibility = 'hidden';
		div0.style.position = 'absolute';
		div0.style.fontSize = '1px';
	    
		div1.style.height = '0px';
		div1.style.overflow = 'hidden';
	    
		document.body.appendChild(div0).appendChild(div1);
	                    
		var base = div0.offsetHeight;
		div1.style.borderTop = 'solid black';        

		div1.style.borderTopWidth = 'thin';
		$telerik._borderThicknesses['thin'] = div0.offsetHeight - base;
	    
		div1.style.borderTopWidth = 'medium';
		$telerik._borderThicknesses['medium'] = div0.offsetHeight - base;
	    
		div1.style.borderTopWidth = 'thick';
		$telerik._borderThicknesses['thick'] = div0.offsetHeight - base;
	    
		if (typeof(div0.removeChild) !== "undefined")
			div0.removeChild(div1);
			
		document.body.removeChild(div0);
		//Apparently, Safari does not like setting outerHTML on elements not in the document
		//throws NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7
		if (!$telerik.isSafari)
			div1.outerHTML = null;
		if (!$telerik.isSafari)
			div0.outerHTML = null;
		div0 = null;
		div1 = null;
	},
	
	getCurrentStyle : function(element, attribute, defaultValue) {
     
        var currentValue = null;
        if (element) {
            if (element.currentStyle) {
                currentValue = element.currentStyle[attribute];
            } else if (document.defaultView && document.defaultView.getComputedStyle) {
                var style = document.defaultView.getComputedStyle(element, null);
                if (style) {
                    currentValue = style[attribute];
                }
            }
            
            if (!currentValue && element.style.getPropertyValue) {
                currentValue = element.style.getPropertyValue(attribute);
            }
            else if (!currentValue && element.style.getAttribute) {
                currentValue = element.style.getAttribute(attribute);
            }       
        }
        
        if ((!currentValue || currentValue == "" || typeof(currentValue) === 'undefined')) {
            if (typeof(defaultValue) != 'undefined') {
                currentValue = defaultValue;
            }
            else {
                currentValue = null;
            }
        }   
        return currentValue;  
    },
    
    getInheritedBackgroundColor : function(element) {
        if (!element) return '#FFFFFF';
        var background = $telerik.getCurrentStyle(element, 'backgroundColor');
        try {
            while (!background || background == '' || background == 'transparent' || background == 'rgba(0, 0, 0, 0)') {
                element = element.parentNode;
                if (!element) {
                    background = '#FFFFFF';
                } else {
                    background = $telerik.getCurrentStyle(element, 'backgroundColor');
                }
            }
        } catch(ex) {
            background = '#FFFFFF';
        }
        return background;
    },
    
	getLocation : function(element) {

		// workaround for an issue in getLocation where it will compute the location of the document element.
		// this will return an offset if scrolled.
		//
		if (element === document.documentElement) {
			return new Sys.UI.Point(0,0);
		}

		// Workaround for IE6 bug in getLocation (also required patching getBounds - remove that fix when this is removed)
		
		//TEKI: When in IE7 in a scenario when item is in a FRAMESET, the location value is wrong. However, using the IE6 code below it works fine
		if (Sys.Browser.agent == Sys.Browser.InternetExplorer /*&& Sys.Browser.version < 7*/) {
			if (element.window === element || element.nodeType === 9 || !element.getClientRects || !element.getBoundingClientRect) return new Sys.UI.Point(0,0);

			// Get the first bounding rectangle in screen coordinates
			var screenRects = element.getClientRects();
			if (!screenRects || !screenRects.length) {
				return new Sys.UI.Point(0,0);
			}
			var first = screenRects[0];

			// Delta between client coords and screen coords
			var dLeft = 0;
			var dTop = 0;

			var inFrame = false;
			try {
				inFrame = element.ownerDocument.parentWindow.frameElement;
			} catch(ex) {
				// If accessing the frameElement fails, a frame is probably in a different
				// domain than its parent - and we still want to do the calculation below
				inFrame = true;
			}

			// If we're in a frame, get client coordinates too so we can compute the delta
			if (inFrame) {
				// Get the bounding rectangle in client coords
				var clientRect = element.getBoundingClientRect();
				if (!clientRect) {
					return new Sys.UI.Point(0,0);
				}

				// Find the minima in screen coords
				var minLeft = first.left;
				var minTop = first.top;
				for (var i = 1; i < screenRects.length; i++) {
					var r = screenRects[i];
					if (r.left < minLeft) {
						minLeft = r.left;
					}
					if (r.top < minTop) {
						minTop = r.top;
					}
				}

				// Compute the delta between screen and client coords
				dLeft = minLeft - clientRect.left;
				dTop = minTop - clientRect.top;
			}

			// Subtract 2px, the border of the viewport (It can be changed in IE6 by applying a border style to the HTML element,
			// but this is not supported by ASP.NET AJAX, and it cannot be changed in IE7.), and also subtract the delta between
			// screen coords and client coords
			var ownerDocument = element.document.documentElement;
			
			var position = new Sys.UI.Point(first.left - 2 - dLeft + ownerDocument.scrollLeft, first.top - 2 - dTop + ownerDocument.scrollTop);

			if ($telerik.quirksMode)
			{						
				position.x += document.body.scrollLeft;
				position.y += document.body.scrollTop;
			}
			
			return position;
		}

		var position = Sys.UI.DomElement.getLocation(element);
		
		if ($telerik.isOpera)
		{
			var parent = element.offsetParent;
			
			while (parent && parent.tagName.toUpperCase() != 'BODY' 
				&& parent.tagName.toUpperCase() != 'HTML') 
			{
				position.x -= parent.scrollLeft;
				position.y -= parent.scrollTop;
				parent = parent.offsetParent;
			}
		}
		
		if ($telerik.isSafari)
		{
			var parent = element.parentNode;
			
			var parentTD = null;
			var parentTABLE = null;
			
			while (parent && parent.tagName.toUpperCase() != 'BODY' 
				&& parent.tagName.toUpperCase() != 'HTML') 
			{
				
				// Workaround for a problem with parent TABLES - when you have a parent TABLE element with border,
				// Safari acts as if the TABLE/TD has no border and calculates X and Y incorrectly. 
				// That is why we need to add the borders manually. In case this is fixed in a future verion of the browser
				// we will need to remove this code.
				if($telerik.isSafari3 || $telerik.isSafari2)
				{
				    if(parent.tagName.toUpperCase() == "TD")
			        {
			            parentTD = parent;
			        }
                    else if(parent.tagName.toUpperCase() == "TABLE")
                    {
                        parentTABLE = parent;
                    }
                    
                    if(parentTD && parentTABLE)
                    {                
                        position.x += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderTopWidth'));
                        position.y += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderLeftWidth'));
                            
                        // In case the TABLE has borderCollapse:collapse, we need to take the borderWidth of either
                        // the TABLE or the TD.
                        if($telerik.getCurrentStyle(parentTABLE, 'borderCollapse') != 'collapse')
                        {
                            position.x += parseInt($telerik.getCurrentStyle(parentTD, 'borderTopWidth'));
                            position.y += parseInt($telerik.getCurrentStyle(parentTD, 'borderLeftWidth'));
                        }
                        
                        parentTD = null;
                        parentTABLE = null;
                    }
                    // In case we use getLocation for a TD element, we need to calculate the borderWidth of its TABLE
                    // only in case that TABLE has no borderCollapse:collapse.
                    else if(parentTABLE)
                    {
                        if($telerik.getCurrentStyle(parentTABLE, 'borderCollapse') != 'collapse')
                        {
                            position.x += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderTopWidth'));
                            position.y += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderLeftWidth'));
                        }
                        parentTABLE = null;
                    }
                }
                
                // END of Workaround for a problem with parent TABLES
				
				parent = parent.parentNode;
			}			
		}

		if ($telerik.isIE && $telerik.quirksMode)
		{
			position.x += document.body.scrollLeft;
			position.y += document.body.scrollTop;
		}

		return position;
	},

    setLocation : function(element, point) {
        Sys.UI.DomElement.setLocation(element, point.x, point.y);
    },
    
    findControl : function(parent, id)
    {
        var children = parent.getElementsByTagName("*");
        for(var i = 0, l = children.length; i < l; i++)
        {
            var childID = children[i].id;
            if (childID && childID.endsWith(id))
                return $find(childID);
        }
        
        return null;
    },
    
    findElement : function(parent, id)
    {
        var children = parent.getElementsByTagName("*");
        for(var i = 0, l = children.length; i < l; i++)
        {
            var childID = children[i].id;
            if (childID && childID.endsWith(id))
                return $get(childID);
        }
        
        return null;
    },

    getContentSize : function(element) {
        /// <summary>
        /// Gets the "content-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Size of the element (in the form {width,height})
        /// </returns>
        /// <remarks>
        /// The "content-box" is the size of the content area *inside* of the borders and
        /// padding of an element. The "content-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var size = $telerik.getSize(element);
        var borderBox = $telerik.getBorderBox(element);
        var paddingBox = $telerik.getPaddingBox(element);
        return {
            width :  size.width - borderBox.horizontal - paddingBox.horizontal,
            height : size.height - borderBox.vertical - paddingBox.vertical
        }
    },
    
    getSize : function(element) {
        /// <summary>
        /// Gets the "border-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Size of the element (in the form {width,height})
        /// </returns>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        return {
            width:  element.offsetWidth,
            height: element.offsetHeight
        };
    },
    
    setContentSize : function(element, size) {
        /// <summary>
        /// Sets the "content-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="size" type="Object">
        /// Size of the element (in the form {width,height})
        /// </param>
        /// <remarks>
        /// The "content-box" is the size of the content area *inside* of the borders and
        /// padding of an element. The "content-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!size) {
            throw Error.argumentNull('size');
        }
        // FF respects -moz-box-sizing css extension, so adjust the box size for the border-box
        if($telerik.getCurrentStyle(element, 'MozBoxSizing') == 'border-box' || $telerik.getCurrentStyle(element, 'BoxSizing') == 'border-box') {
            var borderBox = $telerik.getBorderBox(element);
            var paddingBox = $telerik.getPaddingBox(element);
            size = {
                width: size.width + borderBox.horizontal + paddingBox.horizontal,
                height: size.height + borderBox.vertical + paddingBox.vertical
            };
        }
        element.style.width = size.width.toString() + 'px';
        element.style.height = size.height.toString() + 'px';
    },
    
    setSize : function(element, size) {
        /// <summary>
        /// Sets the "border-box" size of an element.
        /// </summary>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and 
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        /// <param name="element" type="Sys.UI.DomElement">DOM element</param>
        /// <param name="size" type="Object">Size of the element (in the form {width,height})</param>
        /// <returns />
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!size) {
            throw Error.argumentNull('size');
        }
        var borderBox = $telerik.getBorderBox(element);
        var paddingBox = $telerik.getPaddingBox(element);
        var contentSize = {
            width:  size.width - borderBox.horizontal - paddingBox.horizontal,
            height: size.height - borderBox.vertical - paddingBox.vertical
        };
        $telerik.setContentSize(element, contentSize);
    },
	
	getBounds : function(element) {
        /// <summary>Gets the coordinates, width and height of an element.</summary>
        /// <param name="element" domElement="true"/>
        /// <returns type="Sys.UI.Bounds">
        ///   A Bounds object with four fields, x, y, width and height, which contain the pixel coordinates,
        ///   width and height of the element.
        /// </returns>

        var offset = $telerik.getLocation(element);
        return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0);
    },
	
	setBounds : function(element, bounds) {
        /// <summary>
        /// Sets the "border-box" bounds of an element
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="bounds" type="Object">
        /// Bounds of the element (of the form {x,y,width,height})
        /// </param>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!bounds) {
            throw Error.argumentNull('bounds');
        }
        $telerik.setSize(element, bounds);
        $telerik.setLocation(element, bounds);
    },
    
    getClientBounds : function() {
        /// <summary>
        /// Gets the width and height of the browser client window (excluding scrollbars)
        /// </summary>
        /// <returns type="Sys.UI.Bounds">
        /// Browser's client width and height
        /// </returns>

        var clientWidth;
        var clientHeight;
        switch(Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                if (clientWidth == 0 && clientHeight == 0)
                {
                    //no doctype. use the body settings
                    clientWidth = document.body.clientWidth;
                    clientHeight = document.body.clientHeight;
                }
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }
        return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);
    },
    
    getMarginBox : function(element) {
        /// <summary>
        /// Gets the entire margin box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's margin box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getMargin(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getMargin(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getMargin(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getMargin(element, Telerik.Web.BoxSide.Left)
        }
        
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },
    
    getPaddingBox : function(element) {
        /// <summary>
        /// Gets the entire padding box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's padding box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getPadding(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getPadding(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getPadding(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getPadding(element, Telerik.Web.BoxSide.Left)
        }
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },
    
    getBorderBox : function(element) {
        /// <summary>
        /// Gets the entire border box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's border box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Left)
        }
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },

	isBorderVisible : function(element, boxSide) {
        /// <summary>
        /// Gets whether the current border style for an element on a specific boxSide is not 'none'.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Boolean">
        /// Whether the current border style for an element on a specific boxSide is not 'none'.
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._borderStyleNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return styleValue != "none";
    },
    getMargin : function(element, boxSide) {
        /// <summary>
        /// Gets the margin thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Margin thickness on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._marginWidthNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);

        try { return $telerik.parsePadding(styleValue); } catch(ex) { return 0; }
    },

    getBorderWidth : function(element, boxSide) {
        /// <summary>
        /// Gets the border thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Border thickness on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        if(!$telerik.isBorderVisible(element, boxSide)) {
            return 0;
        }        
        var styleName = $telerik._borderWidthNames[boxSide];    
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return $telerik.parseBorderWidth(styleValue);
    },
    
    getPadding : function(element, boxSide) {
        /// <summary>
        /// Gets the padding thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Padding on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._paddingWidthNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return $telerik.parsePadding(styleValue);
    },
    
    parseBorderWidth : function(borderWidth) {
        /// <summary>
        /// Parses a border-width string into a pixel size
        /// </summary>
        /// <param name="borderWidth" type="String" mayBeNull="true">
        /// Type of border ('thin','medium','thick','inherit',px unit,null,'')
        /// </param>
        /// <returns type="Number" integer="true">
        /// Number of pixels in the border-width
        /// </returns>
        
        if(borderWidth) {
            switch(borderWidth) {
                case 'thin':
                case 'medium':
                case 'thick':
                    return $telerik._borderThicknesses[borderWidth];
                case 'inherit':
                    return 0;
            }
            var unit = $telerik.parseUnit(borderWidth);
            return unit.size;
        }
        return 0;
    },
    
    parsePadding : function(padding) {
        /// <summary>
        /// Parses a padding string into a pixel size
        /// </summary>
        /// <param name="padding" type="String" mayBeNull="true">
        /// Padding to parse ('inherit',px unit,null,'')
        /// </param>
        /// <returns type="Number" integer="true">
        /// Number of pixels in the padding
        /// </returns>
        
        if(padding) {
            if(padding == 'inherit') {
                return 0;
            }
            var unit = $telerik.parseUnit(padding);
            return unit.size;
        }
        return 0;
    },
    
    parseUnit : function(value) {
        /// <summary>
        /// Parses a unit string into a unit object
        /// </summary>
        /// <param name="value" type="String" mayBeNull="true">
        /// Value to parse (of the form px unit,% unit,em unit,...)
        /// </param>
        /// <returns type="Object">
        /// Parsed unit (of the form {size,type})
        /// </returns>
        
        if (!value) {
            throw Error.argumentNull('value');
        }
        
        value = value.trim().toLowerCase();
        var l = value.length;
        var s = -1;
        for(var i = 0; i < l; i++) {
            var ch = value.substr(i, 1);
            if((ch < '0' || ch > '9') && ch != '-' && ch != '.' && ch != ',') {
                break;
            }
            s = i;
        }
        if(s == -1) {
            throw Error.create('No digits');
        }
        var type;
        var size;
        if(s < (l - 1)) {
            type = value.substring(s + 1).trim();
        } else {
            type = 'px';
        }
        size = parseFloat(value.substr(0, s + 1));
        if(type == 'px') {
            size = Math.floor(size);
        }
        return { 
            size: size,
            type: type
        };
    },
    
    containsPoint : function(rect, x, y) {
        /// <summary>
        /// Tests whether a point (x,y) is contained within a rectangle
        /// </summary>
        /// <param name="rect" type="Object">The rectangle</param>
        /// <param name="x" type="Number">The x coordinate of the point</param>
        /// <param name="y" type="Number">The y coordinate of the point</param>
        
        //ORIGINAL TOOLKIT SCRIPT CHANGE: instead of rect.height it was written rect.width (!!!) Clearly a major bug!!!!
        return x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y && y <= (rect.y + rect.height);
    },

    isDescendant : function(ancestor, descendant) {
        /// <summary>
        /// Whether the specified element is a descendant of the ancestor
        /// </summary>
        /// <param name="ancestor" type="Sys.UI.DomElement">Ancestor node</param>
        /// <param name="descendant" type="Sys.UI.DomElement">Possible descendant node</param>
        /// <returns type="Boolean" />
        
        for (var n = descendant.parentNode; n != null; n = n.parentNode) {
            if (n == ancestor) return true;
        }
        return false;
    },
	
	isDescendantOrSelf : function(ancestor, descendant) {
        /// <summary>
        /// Whether the specified element is a descendant of the ancestor or the same as the ancestor
        /// </summary>
        /// <param name="ancestor" type="Sys.UI.DomElement">Ancestor node</param>
        /// <param name="descendant" type="Sys.UI.DomElement">Possible descendant node</param>
        /// <returns type="Boolean" />

        if (ancestor === descendant) 
            return true;
        return $telerik.isDescendant(ancestor, descendant);
    },
    
	setOuterHeight : function (element, height)
	{
		if (height <= 0 || height == "") 
		{
			element.style.height = "";
		} 
		else
		{
			element.style.height = height + "px";
			var diff = element.offsetHeight - height;
			var newHeight = height - diff;
			if (newHeight > 0) {
				element.style.height = newHeight + "px";
			} else {
				element.style.height = "";
			}
		}
	},
	
    setOpacity : function(element, value) {
        /// <summary>
        /// Set the element's opacity
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// Element
        /// </param>
        /// <param name="value" type="Number">
        /// Opacity of the element
        /// </param>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        try
        {
            if (element.filters) {
                var filters = element.filters;
                var createFilter = true;
                if (filters.length !== 0) {
                    var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                    if (alphaFilter) {
                        createFilter = false;
                        alphaFilter.opacity = value * 100;
                    }
                }
                if (createFilter) {
                    element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (value * 100) + ')';
                }
            }
            else {
                element.style.opacity = value;
            }
        }
        catch (ex) {}
    },
    	
    getOpacity : function(element) {
        /// <summary>
        /// Get the element's opacity
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// Element
        /// </param>
        /// <returns type="Number">
        /// Opacity of the element
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        
        var hasOpacity = false;
        var opacity;
        
        try
        {
            if (element.filters) {
                var filters = element.filters;
                if (filters.length !== 0) {
                    var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                    if (alphaFilter) {
                        opacity = alphaFilter.opacity / 100.0;
                        hasOpacity = true;
                    }
                }
            }
            else {
                opacity = $telerik.getCurrentStyle(element, 'opacity', 1);
                hasOpacity = true;
            }
        }
        catch (ex) {}
        
        if (hasOpacity === false) {
            return 1.0;
        }
        return parseFloat(opacity);
    },

    addCssClasses : function(element, classNames) {
        /// <summary>
        /// Adds multiple css classes to a DomElement
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement">The element to modify</param>
        /// <param name="classNames" type="Array">The class names to add</param>
        
        for(var i = 0; i < classNames.length; i++) {
            Sys.UI.DomElement.addCssClass(element, classNames[i]);
        }
    },
    
    removeCssClasses : function(element, classNames) {
        /// <summary>
        /// Removes multiple css classes to a DomElement
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement">The element to modify</param>
        /// <param name="classNames" type="Array">The class names to remove</param>
        
        for(var i = 0; i < classNames.length; i++) {
            Sys.UI.DomElement.removeCssClass(element, classNames[i]);
        }
    },    	
	setOuterWidth : function (element, width)
	{
		if (width <= 0 || width == "") 
		{
			element.style.width = "";
		}
		else
		{
			element.style.width = width + "px";
			var diff = element.offsetWidth - width;
			var newWidth = width - diff;
			if (newWidth > 0) {
				element.style.width = newWidth + "px";
			} else {
				element.style.width = "";
			}
		}
	},
	
	getScrollOffset : function(element, recursive)
	{
		var left = 0;
		var top = 0;
		var parent = element;

		while (parent != null && parent.scrollLeft != null) {
			left += parent.scrollLeft;
			top += parent.scrollTop;
			// Don't include anything below the body. 
			if (!recursive || (parent == document.body && (parent.scrollLeft != 0 || parent.scrollTop != 0)))
				break;

			parent = parent.parentNode;
		}

		return { x: left, y: top };
	},
	
	getElementByClassName : function(element, className, tagName)
	{
		var children = null;
		if (tagName)
		{
			children = element.getElementsByTagName(tagName);
		}
		else
		{
			children = element.getElementsByTagName("*");
		}
	    
		for (var i = 0, length = children.length; i < length; i++)
		{
			var child = children[i];
	        
			if (Sys.UI.DomElement.containsCssClass(child, className))
			{
				return child;
			}
		}
	    
		return null;
	},
	
	//The $addHandler and $removeHandler only work with DOM HTML elements.
	//In products that use iframes (RadWindow, RadEditor, EditorPopup) events need to be attached to the iframes' document and/or contentWindow.
	//In addition to this to construct an event object, the MS AJAX framework attempts to use the window.event - which is null in the main page, when the event originates from a child frame
	//Thus, the need to provide an alternative to the MS AJAX framework arises
	addExternalHandler : function(element, eventName, handler)
	{        	
		if (element.addEventListener)
		{
			element.addEventListener(eventName, handler, false);
		}
		else if (element.attachEvent)
		{	
			element.attachEvent("on" + eventName, handler);
		}
	},
	removeExternalHandler : function(element, eventName, handler)
	{    	
		if (element.addEventListener)
		{
			element.removeEventListener(eventName, handler, false);
		}
		else if (element.detachEvent)
		{
			element.detachEvent("on" + eventName, handler);
		}
	},
	
	cancelRawEvent : function(e)
	{    	
		if (!e) return false;
		if (e.preventDefault) e.preventDefault();
		if (e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		e.returnValue = false;	
		return false;
	},
	
	getOuterHtml : function(element)
	{
		if (element.outerHTML)
		{
			return element.outerHTML;
		}
		else
		{
			var elementCopy = element.cloneNode(true);
			var tmpDiv = element.ownerDocument.createElement("DIV");
			tmpDiv.appendChild(elementCopy);
			return tmpDiv.innerHTML;		
		}
	},
	
	setVisible : function(e, value) 
	{
		if (!e) return;

		if (value != $telerik.getVisible(e)) {
	        
			if (value) {
				if (e.style.removeAttribute) {
					e.style.removeAttribute("display");
				} else {
				   e.style.removeProperty("display");
				}
			}
			else {
				e.style.display = 'none';
			}
	        
			e.style.visibility = value ? 'visible' : 'hidden';
		}
	},
	
	getVisible : function(e) 
	{
		if (!e) return false;

		return (("none" != $telerik.getCurrentStyle(e, "display")) &&
        ("hidden" != $telerik.getCurrentStyle(e, "visibility")));
	},
	
	getViewPortSize : function()
	{
		var width = 0;
		var height = 0;

		var canvas = document.body;

		if (!$telerik.quirksMode && !$telerik.isSafari)
		{
			canvas = document.documentElement;
		}

		if (window.innerWidth)
		{
			width = window.innerWidth;
			height = window.innerHeight;
		}
		else
		{
			width = canvas.clientWidth;
			height = canvas.clientHeight;
		}

		width += canvas.scrollLeft;
		height += canvas.scrollTop;

		return { width : width - 6, height : height - 6 };
	},
	
	elementOverflowsTop : function (element)
	{
		return $telerik.getLocation(element).y < 0;
	}, 

	elementOverflowsLeft : function (element)
	{
		return $telerik.getLocation(element).x < 0;
	},

	elementOverflowsBottom : function (screenSize, element)
	{
		var bottomEdge = $telerik.getLocation(element).y + element.offsetHeight;
		return bottomEdge > screenSize.height;
	},

	elementOverflowsRight : function (screenSize, element)
	{
		var rightEdge = $telerik.getLocation(element).x + element.offsetWidth;
		return rightEdge > screenSize.width;
	},

	getDocumentRelativeCursorPosition : function(e)
	{
		var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		var left = e.clientX + scrollLeft;
		var top = e.clientY + scrollTop;
		return {left:left, top:top};
	},
	
//	//Lini: this code is not needed anymore. It will be removed for the Q1 2008 release.
//	makeCompatible : function(type)
//	{
//		/// <exclude />
//		/// <summary>
//		///		Doubles the get_propertyName, set_propertyName, add_event, remove_event
//		///		methods with get_PropertyName, set_PropertyName, etc. ones, to save troubles for
//		///		users already having client-side code with the mistaken client-side convention.
//		///
//		///     Doubles the methodName(...) with MethodName(...) member to save troubles for
//	    ///		users already having client-side code with the mistaken client-side convention.
//		/// </summary>

//		var proto = type.prototype;
//		for (var memberName in proto)
//		{
//			if (/([gs]et|add|remove|raise)_[a-z].*/.test(memberName))
//			{
//				var propNameStart = RegExp.$1.length + 1;
//				var oldPropName = memberName.substr(0, propNameStart) + memberName.charAt(propNameStart).toUpperCase() + memberName.substr(propNameStart + 1);
//				proto[oldPropName] = proto[memberName];
//			}
//			else if (/^[a-z][a-zA-Z]+$/.test(memberName) && 
//		             proto.hasOwnProperty(memberName) &&
//		             typeof(proto[memberName]) == "function" && 
//		             memberName != "initialize" &&
//		             memberName != "dispose")
//		    {
//		        var oldMethodName = memberName.charAt(0).toUpperCase() + memberName.substr(1);
//		        proto[oldMethodName] = proto[memberName];		    
//		    }
//		}
//	},
	
	getFirstChildByTagName : function (element, tagName, index)
	{
		if (!element || !element.childNodes)
		{
			return null;
		}
		
		var currentNode = element.childNodes[index] || element.firstChild;
		
		while (currentNode)
		{
			if (currentNode.nodeType == 1 && currentNode.tagName.toLowerCase() == tagName)
				return currentNode;
			
			currentNode = currentNode.nextSibling;
		}
	
		return null;
	},

	getChildByClassName : function(element, className, index)
	{
		var currentNode = element.childNodes[index] || element.firstChild;
		while (currentNode)
		{
			if (currentNode.nodeType == 1 && currentNode.className.indexOf(className) > -1)
				return currentNode;
			currentNode = currentNode.nextSibling;
		}
		return null;
	},

	getChildrenByTagName : function (element, tagName)
	{
		var children = new Array();
		var childNodes = element.children || element.childNodes;
		
		for (var i = 0, length = childNodes.length; i < length; i++)
		{
			var child = childNodes[i];
			if (child.nodeType == 1 && child.tagName.toLowerCase() == tagName)
				Array.add(children, child);
		}
		return children;
	},
	
	getChildrenByClassName : function (element, className)
	{
		var children = new Array();
		var childNodes = element.children || element.childNodes;
		
		for (var i = 0, length = childNodes.length; i < length; i++)
		{
			var child = childNodes[i];
			if (child.nodeType == 1 && child.className.indexOf(className) > -1)
				Array.add(children, child);
		}
		return children;
	},
	
	isMouseOverElement : function(element, e)
	{
		var elementBounds = $telerik.getBounds(element);
		var cursor = $telerik.getDocumentRelativeCursorPosition(e);

		return $telerik.containsPoint(elementBounds, cursor.left, cursor.top);
	}
}

if (typeof(Sys.Browser.WebKit) == "undefined")
{
	Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
}
if (typeof(Sys.Browser.Chrome) == "undefined")
{
	Sys.Browser.Chrome = {};
}

if(navigator.userAgent.indexOf("Chrome") > -1)
{
	//Sys.Browser.version = navigator.userAgent.match(/Chrome\/(\d+(\.\d+(\.\d+))?)/)[1];
	Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
	Sys.Browser.agent = Sys.Browser.Chrome;
	Sys.Browser.name = "Chrome";
}
else if(navigator.userAgent.indexOf("WebKit/") > -1)
{
	Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
	if (Sys.Browser.version < 500)
	{
		Sys.Browser.agent = Sys.Browser.Safari;
		Sys.Browser.name = "Safari";
	}
	else
	{
		Sys.Browser.agent = Sys.Browser.WebKit;
		Sys.Browser.name = "WebKit";
	}
}

$telerik.isChrome = Sys.Browser.agent == Sys.Browser.Chrome;
$telerik.isSafari3 = Sys.Browser.agent == Sys.Browser.WebKit || Sys.Browser.agent == Sys.Browser.Chrome;
$telerik.isSafari2 = Sys.Browser.agent == Sys.Browser.Safari;
$telerik.isSafari = $telerik.isSafari2 || $telerik.isSafari3;
$telerik.isIE = Sys.Browser.agent == Sys.Browser.InternetExplorer;
$telerik.isIE7 = $telerik.isIE && Sys.Browser.version == 7;
$telerik.isIE6 = $telerik.isIE && Sys.Browser.version < 7;
$telerik.isOpera = Sys.Browser.agent == Sys.Browser.Opera;
$telerik.isFirefox = Sys.Browser.agent == Sys.Browser.Firefox;
$telerik.quirksMode = $telerik.isIE && document.compatMode != "CSS1Compat";
$telerik.standardsMode = !$telerik.quirksMode;

//Initialize the thickness of borders based on their style
$telerik._borderThickness();

Telerik.Web.UI.Orientation = function() {
    /// <summary>
    /// The Telerik.Web.UI.Orientation enumeration is used to specify 
    /// the orientation of a given asset
    /// </summary>
    /// <field name="Horizontal" type="Number" integer="true"/>
    /// <field name="Vertical" type="Number" integer="true"/>
    throw Error.invalidOperation();
}
Telerik.Web.UI.Orientation.prototype = {
    Horizontal : 0,
    Vertical : 1
} 
Telerik.Web.UI.Orientation.registerEnum('Telerik.Web.UI.Orientation', false);

Telerik.Web.UI.RadWebControl = function(element) 
{
    Telerik.Web.UI.RadWebControl.initializeBase(this, [element]);
    
    this._clientStateFieldID = null;
}

Telerik.Web.UI.RadWebControl.prototype = 
{
    initialize: function() 
    {
        Telerik.Web.UI.RadWebControl.callBaseMethod(this, 'initialize');
        
        $telerik.registerControl(this);
        
        if(!this.get_clientStateFieldID()) return;
        
        var input = $get(this.get_clientStateFieldID());    
        
        if(!input) return;
        
        input.setAttribute('autocomplete', 'off');
    },
    
    dispose: function() 
    {
        $telerik.unregisterControl(this);
        
        var element = this.get_element();
        
        Telerik.Web.UI.RadWebControl.callBaseMethod(this, 'dispose');
        
        if (element)
        {
			element.control = null;
			element._events = null;
		}
    },
    
    raiseEvent : function(eventName, eventArgs) {
        /// <summary>
        /// Raise the event
        /// </summary>
        /// <param name="eventName" type="String" mayBeNull="false">
        /// Name of the event to be raised
        /// </param>
        /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="true">
        /// Event arguments for the given event
        /// </param>
        /// <returns />

		var handler = this.get_events().getHandler(eventName);
		if (handler) {
			if (!eventArgs) {
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
        }
    },
    
    updateClientState: function()
    {
        /// <summary>
        /// Call this function to update the client state hidden field.
        /// Use this function with caution, because it is resource hungry.
        /// </summary>
		this.set_clientState(this.saveClientState());
    },
    
    saveClientState: function()
    {
        /// <summary>
        /// This function should return the serialized client state of the control.
        /// </summary>
        /// <example>
		/// saveClientState: function()
		/// {
		///		var state = 
		///		{
		///			Collapsed	: this.get_collapsed(),
		///			Width		: this.get_width(),
		///			Height		: this.get_height()
		///		};
		///		return Sys.Serialization.JavaScriptSerializer.serialize(state);
		/// }
        /// </example>
         return null;
    },
    
    get_clientStateFieldID : function() 
    {
        /// <value type="String">
        /// ID of the hidden field used to store the client state
        /// </value>
        return this._clientStateFieldID;
    },
    set_clientStateFieldID : function(value) 
    {
        if (this._clientStateFieldID != value) 
        {
            this._clientStateFieldID = value;
            this.raisePropertyChanged('ClientStateFieldID');
        }
    },

    get_clientState : function() {
        /// <value type="String">
        /// Client state
        /// </value>
        if (this._clientStateFieldID) 
        {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) 
            {
                return input.value;
            }
        }
        return null;
    },
    set_clientState : function(value) 
    {
        if (this._clientStateFieldID) 
        {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) 
            {
                input.value = value;
            }
        }
    },
    
    _getChildElement : function(id)
	{
		return $get(this.get_id() + "_" + id);
	},
	
	_findChildControl : function(id)
	{
		return $find(this.get_id() + "_" + id);
	}
}

Telerik.Web.UI.RadWebControl.registerClass('Telerik.Web.UI.RadWebControl', Sys.UI.Control);

Telerik.Web.Timer = function() {
    Telerik.Web.Timer.initializeBase(this);
    
    this._interval = 1000;
    this._enabled = false;
    this._timer = null;
    
    this._timerCallbackDelegate = Function.createDelegate(this, this._timerCallback);
}

Telerik.Web.Timer.prototype = {
    get_interval: function() {
        
        return this._interval;
    },
    set_interval: function(value) {
        
        if (this._interval !== value) {
            this._interval = value;
            this.raisePropertyChanged('interval');
            
            if (!this.get_isUpdating() && (this._timer !== null)) {
                this._stopTimer();
                this._startTimer();
            }
        }
    },
    
    get_enabled: function() {
        
        return this._enabled;
    },
    set_enabled: function(value) {
        
        if (value !== this.get_enabled()) {
            this._enabled = value;
            this.raisePropertyChanged('enabled');
            if (!this.get_isUpdating()) {
                if (value) {
                    this._startTimer();
                }
                else {
                    this._stopTimer();
                }
            }
        }
    },

    
    add_tick: function(handler) {
        this.get_events().addHandler("tick", handler);
    },

    remove_tick: function(handler) {
        this.get_events().removeHandler("tick", handler);
    },

    dispose: function() {
        this.set_enabled(false);
        this._stopTimer();
        
        Telerik.Web.Timer.callBaseMethod(this, 'dispose');
    },
    
    updated: function() {
        Telerik.Web.Timer.callBaseMethod(this, 'updated');

        if (this._enabled) {
            this._stopTimer();
            this._startTimer();
        }
    },

    _timerCallback: function() {
        var handler = this.get_events().getHandler("tick");
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },

    _startTimer: function() {
        this._timer = window.setInterval(this._timerCallbackDelegate, this._interval);
    },

    _stopTimer: function() {
        window.clearInterval(this._timer);
        this._timer = null;
    }
}

Telerik.Web.Timer.registerClass('Telerik.Web.Timer', Sys.Component);

Telerik.Web.BoxSide = function() {
}
Telerik.Web.BoxSide.prototype = {
    Top : 0,
    Right : 1,
    Bottom : 2,
    Left : 3
}
Telerik.Web.BoxSide.registerEnum("Telerik.Web.BoxSide", false);

if (Sys.CultureInfo.prototype._getAbbrMonthIndex) {
    try {
        Sys.CultureInfo.prototype._getAbbrMonthIndex('');
    } catch(ex) {
        Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) {
            if (!this._upperAbbrMonths) {
                this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
            }
            return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
        }
        Sys.CultureInfo.CurrentCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;
        Sys.CultureInfo.InvariantCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;
    }
}

Type.registerNamespace("Telerik.Web.UI.Dialogs");

Telerik.Web.IParameterConsumer = function() {
}
Telerik.Web.IParameterConsumer.prototype = {
    clientInit: function(parameters) { throw Error.notImplemented(); }
}
Telerik.Web.IParameterConsumer.registerInterface('Telerik.Web.IParameterConsumer');

Telerik.Web.UI.Dialogs.CommonDialogScript = function()
{
}
Telerik.Web.UI.Dialogs.CommonDialogScript.get_windowReference = function()
{
	if (window.radWindow)
	{
		return window.radWindow;
	}
	if (window.frameElement && window.frameElement.radWindow)
	{
		return window.frameElement.radWindow;
	}
	return null;
};

Telerik.Web.UI.Dialogs.CommonDialogScript.registerClass('Telerik.Web.UI.Dialogs.CommonDialogScript', null);

Telerik.Web.UI.WebServiceLoaderEventArgs = function(context)
{
	Telerik.Web.UI.WebServiceLoaderEventArgs.initializeBase(this);
	this._context = context;
}

Telerik.Web.UI.WebServiceLoaderEventArgs.prototype =
{
	get_context : function ()
	{
		return this._context;
	}
}

Telerik.Web.UI.WebServiceLoaderEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderEventArgs', Sys.EventArgs);


// ---------- WebServiceLoaderSuccessEventArgs Class ----------
Telerik.Web.UI.WebServiceLoaderSuccessEventArgs = function(data, context)
{
	Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.initializeBase(this, [context]);
	this._data = data;
}

Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.prototype =
{
	get_data : function ()
	{
		return this._data;
	}	
}

Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderSuccessEventArgs', Telerik.Web.UI.WebServiceLoaderEventArgs);


// ---------- WebServiceLoaderErrorEventArgs Class ----------
Telerik.Web.UI.WebServiceLoaderErrorEventArgs = function(message, context)
{
	Telerik.Web.UI.WebServiceLoaderErrorEventArgs.initializeBase(this, [context]);
	this._message = message;
}

Telerik.Web.UI.WebServiceLoaderErrorEventArgs.prototype =
{
	get_message : function ()
	{
		return this._message;
	}
}

Telerik.Web.UI.WebServiceLoaderErrorEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderErrorEventArgs', Telerik.Web.UI.WebServiceLoaderEventArgs);


// ---------- WebServiceLoader Class ----------
Telerik.Web.UI.WebServiceLoader = function(webServiceSettings)
{
	this._webServiceSettings = webServiceSettings;
	this._events = null;
	this._currentWebRequest = null;
	this._onWebServiceSuccessDelegate = Function.createDelegate(this, this._onWebServiceSuccess);
	this._onWebServiceErrorDelegate = Function.createDelegate(this, this._onWebServiceError);
}

Telerik.Web.UI.WebServiceLoader.prototype =
{
	// Public properties
	get_webServiceSettings : function ()
	{
		return this._webServiceSettings;
	},
	
	get_events: function ()
	{
		if (!this._events)
		{
			this._events = new Sys.EventHandlerList();
		}
		
		return this._events;
	},
	
	
	// Public methods
	loadData : function (params, context)
	{
		var webServiceSettings = this.get_webServiceSettings();
		
		if (webServiceSettings.get_isEmpty())
		{
			Error.invalidOperation("Please, specify valid web service and method.");
			return;
		}

		var webServicePath = webServiceSettings.get_path();
		var webMethod = webServiceSettings.get_method();
		
		this._raiseEvent("loadingStarted", new Telerik.Web.UI.WebServiceLoaderEventArgs(context));

		this._currentWebRequest =	Sys.Net.WebServiceProxy.invoke(webServicePath, webMethod, false, params,
										this._onWebServiceSuccessDelegate, this._onWebServiceErrorDelegate, context);
	},
	
	
	// Events
	add_loadingStarted : function(handler)
	{
		this.get_events().addHandler("loadingStarted", handler);
	},

	add_loadingError : function(handler)
	{
		this.get_events().addHandler("loadingError", handler);
	},

	add_loadingSuccess : function(handler)
	{
		this.get_events().addHandler("loadingSuccess", handler);
	},
	
	
	// Private methods	
	_onWebServiceSuccess : function (data, context)
	{
		var successEventArgs = new Telerik.Web.UI.WebServiceLoaderSuccessEventArgs(data, context);
		this._raiseEvent("loadingSuccess", successEventArgs);
	},
	
	_onWebServiceError : function (error, context)
	{	
		var errorEventArgs = new Telerik.Web.UI.WebServiceLoaderErrorEventArgs(error.get_message(), context);
		this._raiseEvent("loadingError", errorEventArgs);
	},

	_raiseEvent : function (eventName, eventArgs)
	{
		var handler = this.get_events().getHandler(eventName);        

		if (handler)
		{
			if (!eventArgs)
			{
				eventArgs = Sys.EventArgs.Empty;
			}

			handler(this, eventArgs);
		}
	}
}

Telerik.Web.UI.WebServiceLoader.registerClass('Telerik.Web.UI.WebServiceLoader');

Telerik.Web.UI.WebServiceSettings = function(serializedWebServiceSettings)
{
	this._path = null;
	this._method = null;
	
	//Add a check for the parameter existance
	if (!serializedWebServiceSettings) serializedWebServiceSettings = {};
	
	if (typeof(serializedWebServiceSettings.path) != "undefined")
	{
		this._path = serializedWebServiceSettings.path;
	}
	
	if (typeof(serializedWebServiceSettings.method) != "undefined")
	{
		this._method = serializedWebServiceSettings.method;
	}
}

Telerik.Web.UI.WebServiceSettings.prototype =
{
	get_path : function ()
	{
		return this._path;
	},
	
	set_path : function(value)
	{
		this._path = value;
	},

	get_method : function ()
	{
		return this._method;
	},
	
	set_method : function(value)
	{
		this._method = value;
	},
	
	get_isEmpty : function ()
	{
		/// <value type="Boolean">
		///		A value indicating wether the web service settings contain
		///		a non-null and non-empty service path and method.
		/// </value>
		var path = this.get_path();
		var method = this.get_method();
		
		return (!(path && method))
	}
}

Telerik.Web.UI.WebServiceSettings.registerClass('Telerik.Web.UI.WebServiceSettings');
/* END Telerik.Web.UI.Common.Core.js */
/* START Telerik.Web.UI.Ajax.Ajax.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadAjaxControl = function(element) 
{
    Telerik.Web.UI.RadAjaxControl.initializeBase(this, [element]);
    
    this._clientEvents = {};
    this._uniqueID = "";
    this._enableHistory = false;
    this._enableAJAX = true;
   
    this._requestQueueSize = 0;
    this._requestQueue = [];

    this._loadingPanelsToHide = [];
    this._initializeRequestHandler = null;
    this._endRequestHandler = null;
    this._isRequestInProgress = false;

    this._links = [];
    this._styles = [];
    
    this.Type = "Telerik.Web.UI.RadAjaxControl";
    
    // OBSOLETE!
    this.UniqueID = this._uniqueID;
    this.EnableHistory = this._enableHistory;
    this.EnableAJAX = this._enableAJAX;
    this.Links = this._links;
    this.Styles = this._styles;
    
    this._updatePanels = "";
}

Telerik.Web.UI.RadAjaxControl.prototype = 
{
    initialize: function() 
    {
       Telerik.Web.UI.RadAjaxControl.callBaseMethod(this, 'initialize');

       for(var clientEvent in this._clientEvents)
       {
			if (typeof(this._clientEvents[clientEvent]) != "string")
				continue;
				
			if (this._clientEvents[clientEvent] != "")
			{
				var handlerString = this._clientEvents[clientEvent];

				if (handlerString.indexOf("(") != -1)
				{
					// function call
					this[clientEvent] = handlerString;
				}
				else
				{
					// function reference
					this[clientEvent] = eval(handlerString);
				}
			}
			else
			{
				this[clientEvent] = null;
			}
       }

       var requestManager = Sys.WebForms.PageRequestManager.getInstance();

       this._initializeRequestHandler = Function.createDelegate(this, this._initializeRequest);
       requestManager.add_initializeRequest(this._initializeRequestHandler);
    },
    
    _getResponseHeader : function(xmlHttpRequest, headerName)
    {
        try
	    {
		    return xmlHttpRequest.getResponseHeader(headerName);
	    }
	    catch(e)
	    {
		    return null;
	    }
    },
    
    _handleAsyncRedirect : function(xmlHttpRequestObject)
    {
        var redirectURL = this._getResponseHeader(xmlHttpRequestObject, "Location");

		if (redirectURL && redirectURL != "")
		{
		    var tmp = document.createElement("a");
		    tmp.style.display = "none";
		    tmp.href = redirectURL;
		    document.body.appendChild(tmp);
		    if(tmp.click)
		    {
		        try
		        {
		            tmp.click();
		        }
		        catch(e) { }
		    }
		    else
		    {
		        window.location.href = redirectURL;
		    }
		    document.body.removeChild(tmp);
		    
		    return true;
		}
		
		return false;
    },
    
    _onFormSubmitCompleted : function(sender, args)
    {
        if(sender._xmlHttpRequest != null)
        {
            if(this._handleAsyncRedirect(sender._xmlHttpRequest))
            {
                try
                {
                    sender._aborted = true;
                }
                catch(e)
                {
                    //
                }
                return;
            }
        }
        
        if(sender._xmlHttpRequest != null && !sender.get_timedOut())
        {
            var scriptBlocks = this.getResponseItems(sender.get_responseData(), "scriptBlock");
            for(var i = 0, length = scriptBlocks.length; i < length; i++)
            {
                var content = scriptBlocks[i].content;
                if(content.indexOf(Sys.WebForms.PageRequestManager.getInstance()._uniqueIDToClientID(this._uniqueID)) != -1)
                {
                   var linksString = content.substr(content.indexOf("\"links\":") + 10, content.indexOf("]", content.indexOf("\"links\":")) - (content.indexOf("\"links\":") + 10)).replace(/\"/g, '');
                   if(linksString != "")
                   {
                    this._links = linksString.split(",");
                    this.updateHeadLinks();
                   }
                }
                
                if(content.indexOf(".axd") == -1 && scriptBlocks[i].id == "ScriptPath")
                {
                    Telerik.Web.UI.RadAjaxControl.IncludeClientScript(content);
                }
            }

            var panels = this.getResponseItems(sender.get_responseData(), "updatePanel");

            Telerik.Web.UI.RadAjaxControl.panelsToClear = [];

            for(var i = 0, length = panels.length; i < length; i++)
            {
                var panel = panels[i];
                if(!$get(panel.id))
                {
					var newUpdatePanel = document.createElement("div");
                    newUpdatePanel.id = panel.id;
                    var element = $get(panel.id.replace("Panel", ""));

                    if(!element)
                        continue;

                    var parent = element.parentNode;
                    var nextSibling = element.nextSibling || Telerik.Web.UI.RadAjaxControl.GetNodeNextSibling(element);
                    
                    if (element.nodeType === 1) 
                    {
						if (element.dispose && typeof(element.dispose) === "function") 
						{
							element.dispose();
						}
						else if (element.control && typeof(element.control.dispose) === "function") 
						{
							element.control.dispose();
						}
						var behaviors = Sys.UI.Behavior.getBehaviors(element);
						for (var j = behaviors.length - 1; j >= 0; j--) 
						{
							behaviors[j].dispose();
						}
					}
					
                    Sys.WebForms.PageRequestManager.getInstance()._destroyTree(element);
                    parent.removeChild(element);

                    Telerik.Web.UI.RadAjaxControl.InsertAtLocation(newUpdatePanel, parent, nextSibling);
                    Telerik.Web.UI.RadAjaxControl.panelsToClear[Telerik.Web.UI.RadAjaxControl.panelsToClear.length] = panel;
                }
            }
        }

         sender.get_webRequest().remove_completed(this._onFormSubmitCompletedHandler);
    },
    
    dispose: function() 
    {
        this.hideLoadingPanels();

        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        requestManager.remove_initializeRequest(this._initializeRequestHandler);

        $clearHandlers(this.get_element());
        this._element.control = null;

        Telerik.Web.UI.RadAjaxControl.callBaseMethod(this, 'dispose');
    },
    
    get_enableAJAX: function() 
    {
        return this._enableAJAX;
    },
    set_enableAJAX : function(value) 
    {
        if (this._enableAJAX != value) 
        {
            this._enableAJAX = value;
        }
    },

    get_enableHistory: function() 
    {
        return this._enableHistory;
    },
    set_enableHistory : function(value) 
    {
        if (this._enableHistory != value) 
        {
            this._enableHistory = value;
        }
    },

    get_clientEvents: function() 
    {
        return this._clientEvents;
    },
    set_clientEvents : function(value) 
    {
        if (this._clientEvents != value) 
        {
            this._clientEvents = value;
        }
    },

    get_links : function() 
    {
        return this._links;
    },
    set_links : function(value) 
    {
        if (this._links != value) 
        {
            this._links = value;
            
            if (this._links.length > 0)
            {
                this.updateHeadLinks();
            }
        }
    },
    
    get_styles : function() 
    {
        return this._styles;
    },
    set_styles : function(value) 
    {
        if (this._styles != value) 
        {
            this._styles = value;
            
            if(this._styles.length > 0)
            {
                this.updateHeadStyles();
            }
        }
    },

    get_uniqueID : function() 
    {
        return this._uniqueID;
    },
    set_uniqueID : function(value) 
    {
        if (this._uniqueID != value) 
        {
            this._uniqueID = value;
            window[Sys.WebForms.PageRequestManager.getInstance()._uniqueIDToClientID(this._uniqueID)] = this;
        }
    },
    
    get_requestQueueSize : function()
    {
        return this._requestQueueSize;
    },
    
    set_requestQueueSize : function(value)
    {
        if (value > 0)
        {
            this._requestQueueSize = value;
            this.raisePropertyChanged("requestQueueSize");
        }
    },

    isChildOf : function(control, parent)
    {
        while(control != null)
        {
            if (control == parent)
                return true;
            
            control = control.parentNode;
        }
        
        return false;
    },

    _initializeRequest : function(sender, args)
    {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        if (requestManager.get_isInAsyncPostBack() && this._requestQueueSize > 0)
        {
            this._queueRequest(sender, args);
        }    

        if (this.Type == "Telerik.Web.UI.RadAjaxManager")
        {
            if (args.get_postBackElement() != this.get_element())
            { 
                var plainPanels = this._updatePanels.split(",");

                if(Array.contains(plainPanels, args.get_postBackElement().id))
                {
                    this._isRequestInProgress = true;
                    this._attachRequestHandlers(sender, args, false);
                    return false;
                }
                else
                {
                    var parentNode = args.get_postBackElement().parentNode;
                    var found = false;
                    while (parentNode != null)
                    {
                       if (parentNode.id && Array.contains(plainPanels, parentNode.id))
                       {
                          found = true;
                          break;
                       }
                       parentNode = parentNode.parentNode;
                    }
                    
                    if (found)
                    {
                        this._isRequestInProgress = true;
                        this._attachRequestHandlers(sender, args, false);
                        return false;
                    }
                }
               
                if (!this._initiators[args.get_postBackElement().id])
                {
                     var parentNode = args.get_postBackElement().parentNode;
                     var found = false;
                     while (parentNode != null)
                     {
                        if (parentNode.id && this._initiators[parentNode.id])
                        {
                           found = true;
                           break;
                        }
                        parentNode = parentNode.parentNode;
                     }

                    if (!found)
                    {
                        this._isRequestInProgress = true;
                        this._attachRequestHandlers(sender, args, false);
                        return false;
                    }
                }
            }
        }

        if (this.Type == "Telerik.Web.UI.RadAjaxPanel")
        {
            // cancel request for nested panels (avoid duplicate request)
            var parentAjaxPanel = this._getParentAjaxPanel(args.get_postBackElement());
            if (parentAjaxPanel && parentAjaxPanel.get_id() != this.get_id())
            {
                return false;
            }
            
            if (!this.isChildOf(args.get_postBackElement(), this.get_element()))
            {
		         //this._isRequestInProgress = true;
		         //this._attachRequestHandlers(sender, args);
                 return false;
            }
        }

        if (this._enableHistory)
        {
            if (Telerik.Web.UI.RadAjaxControl.History[""] == null)
            {
                Telerik.Web.UI.RadAjaxControl.HandleHistory(sender._uniqueIDToClientID(this._uniqueID), "");
            }

            Telerik.Web.UI.RadAjaxControl.HandleHistory(sender._uniqueIDToClientID(this._uniqueID), args.get_request().get_body());
        }

        if(sender._form["__EVENTTARGET"] && sender._form["__EVENTTARGET"].value)
        {
            this.__EVENTTARGET = sender._form["__EVENTTARGET"].value;
        }
        else
        {
            this.__EVENTTARGET = args.get_postBackElement().id;
        }

        if (args.get_postBackElement().name)
        {
            this.__EVENTTARGET = args.get_postBackElement().name;
        }
        
        
        this.__EVENTARGUMENT = sender._form["__EVENTARGUMENT"].value;
    	var evt = new Telerik.Web.UI.RadAjaxRequestEventArgs(this.__EVENTTARGET, sender._form["__EVENTARGUMENT"].value, this._enableAJAX);

        var result = this.fireEvent(this, "OnRequestStart", [evt]);
        if (evt.get_cancel() || (typeof(result) != "undefined" && !result))
        {
            args.set_cancel(true);
			return;
		}

	    if (!evt._enableAjax || !evt.EnableAjax)
        {
            args.set_cancel(true);
            sender._form["__EVENTTARGET"].value = this.__EVENTTARGET ;
            sender._form["__EVENTARGUMENT"].value = this.__EVENTARGUMENT ;
            sender._form.submit();
			return;
        }

		this._isRequestInProgress = true;
		
		this._attachRequestHandlers(sender, args, true);
    },
    
    _endRequest : function(sender, args)
    {
        sender.remove_endRequest(this._endRequestHandler);

        for(var i = 0, length = Telerik.Web.UI.RadAjaxControl.panelsToClear.length; i < length; i++)
        {
            var panel = Telerik.Web.UI.RadAjaxControl.panelsToClear[i];
            var panelHtmlElement = document.getElementById(panel.id);
            var element = $get(panel.id.replace("Panel", ""));
           
           if(!element)
                continue;

            var parent = panelHtmlElement.parentNode;
            var nextSibling = panelHtmlElement.nextSibling || Telerik.Web.UI.RadAjaxControl.GetNodeNextSibling(panelHtmlElement);

            Telerik.Web.UI.RadAjaxControl.InsertAtLocation(element, parent, nextSibling);

            panelHtmlElement.parentNode.removeChild(panelHtmlElement);
        }

        this._isRequestInProgress = false;
        
        this.hideLoadingPanels();

        if(typeof(this.__EVENTTARGET) != "undefined" && typeof(this.__EVENTARGUMENT) != "undefined")
        {
            var evt = new Telerik.Web.UI.RadAjaxRequestEventArgs(this.__EVENTTARGET, this.__EVENTARGUMENT, this._enableAJAX);
            this.fireEvent(this, "OnResponseEnd", [evt]);
        }
        
        if (this._requestQueue.length > 0)
        {
            this._executePendingRequest();
        }
    },
    
    _queueRequest : function(sender, args)
    {
        args.set_cancel(true);
        
        if (this._requestQueue.length >= this._requestQueueSize)
        {
            //queue is full -- ignore the request
            return;
        }
        
        var postBackElement = args.get_postBackElement();
        var eventTarget = postBackElement.id;
        if (postBackElement.name)
        {
            eventTarget = postBackElement.name;
        }

        if (sender._form["__EVENTTARGET"] && sender._form["__EVENTTARGET"].value)
        {
            eventTarget = sender._form["__EVENTTARGET"].value;
        }
        
        var eventArgument = sender._form["__EVENTARGUMENT"].value;
 
        Array.enqueue(this._requestQueue, [eventTarget, eventArgument]);
    },
    
    _executePendingRequest : function()
    {
        var pendingRequest = Array.dequeue(this._requestQueue);
        
        var eventTarget = pendingRequest[0];        
        var eventArgument = pendingRequest[1];
        
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        requestManager._doPostBack(eventTarget, eventArgument);
    },    
    
    _attachRequestHandlers : function(sender, args, sendRadAJAXControlID)
    {
        this._endRequestHandler = Function.createDelegate(this, this._endRequest);
        sender.add_endRequest(this._endRequestHandler);

//        this.pageLoadingHandler = Function.createDelegate(this, this.pageLoading);
//        sender.add_pageLoading(this.pageLoadingHandler);

//        this.pageLoadedHandler = Function.createDelegate(this, this.pageLoaded);
//        sender.add_pageLoaded(this.pageLoadedHandler);

        this._onFormSubmitCompletedHandler = Function.createDelegate(this, this._onFormSubmitCompleted);
        args.get_request().add_completed(this._onFormSubmitCompletedHandler);
        args.get_request()._get_eventHandlerList()._list.completed.reverse();
        
        if(sendRadAJAXControlID)
        {
            var requestBody = args.get_request().get_body();
            var delimiter = (requestBody.lastIndexOf("&") != requestBody.length - 1)? "&" : "";
            requestBody +=  delimiter + "RadAJAXControlID=" + sender._uniqueIDToClientID(this._uniqueID);
            args.get_request().set_body(requestBody);
        }
    },

    _getParentAjaxPanel : function(control)
    {
        var ajaxPanel = null;
        while (control != null)
        {
            if (typeof(control.id) != "undefined" &&
                $find(control.id) &&
                $find(control.id).Type == "Telerik.Web.UI.RadAjaxPanel")
            {
                ajaxPanel = $find(control.id);
                break;
            }
            
            control = control.parentNode;
        }
        
        return ajaxPanel;
    },

    getResponseItems : function(responseText, itemType, itemId)
    {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        // Parse the message format
        // General format: length|type|id|content|
        var reply = responseText;
        var delimiterIndex, len, type, id, content;
        var replyIndex = 0;
        var parserErrorDetails = null;
        var delimitByLengthDelimiter = '|';
        var delta = [];

        while (replyIndex < reply.length) {
            // length| - from index to next delimiter
            delimiterIndex = reply.indexOf(delimitByLengthDelimiter, replyIndex);
            if (delimiterIndex === -1) {
                parserErrorDetails = requestManager._findText(reply, replyIndex);
                break;
            }
            len = parseInt(reply.substring(replyIndex, delimiterIndex), 10);
            if ((len % 1) !== 0) {
                parserErrorDetails = requestManager._findText(reply, replyIndex);
                break;
            }
            replyIndex = delimiterIndex + 1;

            // type| - from index to next delimiter
            delimiterIndex = reply.indexOf(delimitByLengthDelimiter, replyIndex);
            if (delimiterIndex === -1) {
                parserErrorDetails = requestManager._findText(reply, replyIndex);
                break;
            }
            type = reply.substring(replyIndex, delimiterIndex);
            replyIndex = delimiterIndex + 1;

            // id| - from index to next delimiter
            delimiterIndex = reply.indexOf(delimitByLengthDelimiter, replyIndex);
            if (delimiterIndex === -1) {
                parserErrorDetails = requestManager._findText(reply, replyIndex);
                break;
            }
            id = reply.substring(replyIndex, delimiterIndex);
            replyIndex = delimiterIndex + 1;

            // content - the next 'len' characters after index
            if ((replyIndex + len) >= reply.length) {
                parserErrorDetails = requestManager._findText(reply, reply.length);
                break;
            }
            
            if(typeof(requestManager._decodeString) != "undefined")
            {
                content = requestManager._decodeString(reply.substr(replyIndex, len));
            }
            else
            {
                content = reply.substr(replyIndex, len);
            }
            
            replyIndex += len;

            // terminating delimiter
            if (reply.charAt(replyIndex) !== delimitByLengthDelimiter) {
                parserErrorDetails = requestManager._findText(reply, replyIndex);
                break;
            }

            replyIndex++;

            if(itemType != undefined && itemType != type)
                continue;

            if(itemId != undefined && itemId != id)
                continue;

            Array.add(delta, {type: type, id: id, content: content});
        }
        
        return delta;
    },

    pageLoading : function(sender, args)
    {
        //sender.remove_pageLoading(this.pageLoadingHandler);
    },
    
    pageLoaded : function(sender, args)
    {
        //sender.remove_pageLoaded(this.pageLoadedHandler);
    },
    
    hideLoadingPanels : function()
    {
        for(var i = 0; i < this._loadingPanelsToHide.length; i++)
        {
            var panel = this._loadingPanelsToHide[i].Panel;
            var controlID = this._loadingPanelsToHide[i].ControlID;
            if(panel != null)
            {
                panel.hide(controlID);
                Array.remove(this._loadingPanelsToHide, this._loadingPanelsToHide[i]);
                i--;
            }
        }
    },

    fireEvent : function(sender, eventHandler, eventArguments)
    {
		var returnValue = true;
		if (typeof(sender[eventHandler]) == "string")
		{
			returnValue = eval(sender[eventHandler]);
		}
		else if (typeof(sender[eventHandler]) == "function")
		{
			if (eventArguments)
			{
			    if(typeof(eventArguments.unshift) != "undefined")
			    {
				    eventArguments.unshift(sender);
				    returnValue = sender[eventHandler].apply(sender, eventArguments);
				}
				else
				{
				    returnValue = sender[eventHandler].apply(sender, [eventArguments]);
				}
			}
			else
			{
				returnValue = sender[eventHandler]();
			}
		}

		if (typeof(returnValue) != "boolean")
		{
			return true;
		}
		else
		{
			return returnValue;
		}
    },
    
    updateHeadLinks : function()
    {
        var head = this.getHeadElement();
        var existingLinks = head.getElementsByTagName("link");
        
        var existingHrefs = []
        for (var j = 0, innerLength = existingLinks.length; j < innerLength; j++)
        {
            var existingHref = existingLinks[j].getAttribute("href");
            existingHrefs.push(existingHref);
        }

        for(var i = 0, length = this._links.length; i < length; i++)
        {
            var href = this._links[i];
            href = href.replace(/&amp;amp;t/g, "&t");
            href = href.replace(/&amp;t/g, "&t");
            var alreadyExists = Array.contains(existingHrefs, href);
            
            if(!alreadyExists)
            {
		        if(href == "")
		            continue;

                var link = document.createElement("link");
                link.setAttribute("rel", "stylesheet");
                link.setAttribute("href", href);
                
                head.appendChild(link);
            }
        }
    },
    
    updateHeadStyles : function()
    {
        if (document.createStyleSheet != null)
        {
            //IE
            for (var i = 0, length = this._styles.length; i < length; i++)
            {
			    var cssCode = this._styles[i];
   				
                var newStyle = null;
                try
                {
                    newStyle = document.createStyleSheet();
                }
                catch(e)
                {}
                
                if(newStyle == null)
                {
                    newStyle = document.createElement('style');
                }
    			
			    newStyle.cssText = cssCode;
            }
        }
        else
        {
            //SAFARI, Moz, Opera
            var targetStylesheet = null;
            if (document.styleSheets.length == 0)
            {
	            css = document.createElement('style');
	            css.media = 'all';
	            css.type  = 'text/css';
    	        
	            var oldHeader = this.getHeadElement();
	            oldHeader.appendChild(css);
	            targetStylesheet = css;
            }

            if (document.styleSheets[0])
            {   
                 targetStylesheet = document.styleSheets[0];
            }
            
            for (var i = 0; i < this._styles.length; i++)
            {
			    var cssCode = this._styles[i];
                
                var rules = cssCode.split("}");

                for (var j = 0; j < rules.length; j++)
                {
                    if (rules[j].replace(/\s*/, "") == "")
                        continue;
                    
                    targetStylesheet.insertRule(rules[j] + "}", j + 1);
                }
            }
         }
    },
    
    getHeadElement : function()
    {
	    var heads = document.getElementsByTagName("head");
        if (heads.length > 0)
		    return heads[0];

	    //DESHEV: I think all browsers have a head, even if the server does not render one
	    //Just in case...
	    var head = document.createElement("head");
	    document.documentElement.appendChild(head);
	    return head;
    },
    
    ajaxRequest : function(args)
    {
        __doPostBack(this._uniqueID, args);
    },
    
    ajaxRequestWithTarget : function(eventTarget, eventArgument)
    {
        __doPostBack(eventTarget, eventArgument);
    },
    
    __doPostBack : function(sender, args)
    {
        var form = Sys.WebForms.PageRequestManager.getInstance()._form;
        if(form != null)
        {
            if(form["__EVENTTARGET"] != null)
                form["__EVENTTARGET"].value = sender;

            if(form["__EVENTARGUMENT"] != null)
                form["__EVENTARGUMENT"].value = args;

            form.submit();
        }
    }
}

//$telerik.makeCompatible(Telerik.Web.UI.RadAjaxControl);
Telerik.Web.UI.RadAjaxControl.registerClass('Telerik.Web.UI.RadAjaxControl', Sys.UI.Control);

Telerik.Web.UI.RadAjaxRequestEventArgs = function(eventTarget, eventArgument, enableAjax)
{
    Telerik.Web.UI.RadAjaxRequestEventArgs.initializeBase(this);
    
    this._enableAjax = enableAjax;
    this._eventTarget = eventTarget;
    this._eventArgument = eventArgument;
    
    this._postbackControlClientID = eventTarget.replace(/(\$|:)/g, "_");
    this._eventTargetElement = $get(this._postbackControlClientID);
    
    // OBSOLETE! 
    this.EnableAjax = this._enableAjax;
    this.EventTarget = this._eventTarget;
    this.EventArgument = this._eventArgument;
    this.EventTargetElement = this._eventTargetElement;
}

Telerik.Web.UI.RadAjaxRequestEventArgs.prototype = 
{
    get_enableAjax : function()
    {
        return this._enableAjax;
    },
    
    set_enableAjax : function(value)
    {
        if (this._enableAjax != value)
        {
            this._enableAjax = value;
        }
    },
    
    get_eventTarget : function()
    {
        return this._eventTarget;
    },
    
    get_eventArgument : function()
    {
        return this._eventArgument;
    },
    
    get_eventTargetElement : function()
    {
        return this._eventTargetElement;
    }
};

Telerik.Web.UI.RadAjaxRequestEventArgs.registerClass('Telerik.Web.UI.RadAjaxRequestEventArgs', Sys.CancelEventArgs);


Telerik.Web.UI.RadAjaxControl.History = {};

Telerik.Web.UI.RadAjaxControl.HandleHistory = function(clientID, data)
{
    if(window.netscape) return;

    var historyFrame = $get(clientID + "_History");
    if(historyFrame == null)
    {
        historyFrame = document.createElement("iframe");
        historyFrame.id = clientID + "_History";
        historyFrame.name = clientID + "_History";
        historyFrame.style.width = "0px";
        historyFrame.style.height = "0px";
        historyFrame.src = "javascript:''";
        historyFrame.style.visibility = "hidden";        

        var loadHandler = function(e)
        {
            if(!Telerik.Web.UI.RadAjaxControl.ShouldLoadHistory)
            {
                Telerik.Web.UI.RadAjaxControl.ShouldLoadHistory = true;
                return;
            }
            
            //if(!AjaxNS.IsInRequest)
            {
                var target = "";
                var argument = "";

                var dataValueElement = historyFrame.contentWindow.document.getElementById("__DATA");

                if(!dataValueElement) return;

                var dataArray = dataValueElement.value.split("&");

                for (var i = 0, length = dataArray.length; i < length; i++)
                {
                    var keyValue = dataArray[i].split("=");

                    if(keyValue[0] == "__EVENTTARGET")
                    {
                        target = keyValue[1];
                    }
                    
                    if(keyValue[0] == "__EVENTARGUMENT")
                    {
                        argument = keyValue[1];
                    }

                    var element = document.getElementById(Sys.WebForms.PageRequestManager.getInstance()._uniqueIDToClientID(keyValue[0]));
                    if(element != null)
                    {
                        Telerik.Web.UI.RadAjaxControl.RestorePostData(element, Telerik.Web.UI.RadAjaxControl.DecodePostData(keyValue[1]));
                    }
                }

                if(target != "")
                {
                    __doPostBack(Telerik.Web.UI.RadAjaxControl.DecodePostData(target), Telerik.Web.UI.RadAjaxControl.DecodePostData(argument), clientID);
                }
            }
        };

        $addHandler(historyFrame, "load", loadHandler);
        document.body.appendChild(historyFrame);
    }
    
    if(Telerik.Web.UI.RadAjaxControl.History[data] == null)
    {
        Telerik.Web.UI.RadAjaxControl.History[data] = true;
        Telerik.Web.UI.RadAjaxControl.AddHistoryEntry(historyFrame, data);
    }
};

Telerik.Web.UI.RadAjaxControl.AddHistoryEntry = function(historyFrame, data)
{
    Telerik.Web.UI.RadAjaxControl.ShouldLoadHistory = false;

    historyFrame.contentWindow.document.open();
    historyFrame.contentWindow.document.write("<input id='__DATA' name='__DATA' type='hidden' value='" + data + "' />");
    historyFrame.contentWindow.document.close();

    if(window.netscape)
    {
        historyFrame.contentWindow.document.location.hash = "#'" + new Date() + "'";
    }
};

Telerik.Web.UI.RadAjaxControl.DecodePostData = function(value)
{
    if (decodeURIComponent)
    {
        return decodeURIComponent(value);
    }
    else
    {
        return unescape(value);
    }
};

Telerik.Web.UI.RadAjaxControl.RestorePostData = function(element, value)
{
    if(element.tagName.toLowerCase() == "select")
    {
        for (var i = 0, length = element.options.length; i < length; i++)
        {
            if (value.indexOf(element.options[i].value) != -1)
            {
                element.options[i].selected = true;
            }
        }
    }

    if(element.tagName.toLowerCase() == "input" && (element.type.toLowerCase() == "text" || element.type.toLowerCase() == "hidden"))
    {
        element.value = value;
    }
    
    if(element.tagName.toLowerCase() == "input" && (element.type.toLowerCase() == "checkbox" || element.type.toLowerCase() == "radio"))
    {
        element.checked = value;
    }
};

Telerik.Web.UI.RadAjaxControl.GetNodeNextSibling = function (node)
{
	if (node != null && node.nextSibling != null)
	{
		return node.nextSibling;
	}
	return null;
};

Telerik.Web.UI.RadAjaxControl.InsertAtLocation = function(element, parent, nextSibling)
{	
	if (nextSibling != null)
    {		
	    return parent.insertBefore(element, nextSibling);
    }
    else
    {		
	    return parent.appendChild(element);
    }
};

Telerik.Web.UI.RadAjaxControl.FocusElement = function(controlId)
{
    var controlToFocus = document.getElementById(controlId);
    if (controlToFocus)
    {
        var controlTagName = controlToFocus.tagName;
        var controlType = controlToFocus.type;
        
        if (controlTagName.toLowerCase()== "input" && (controlType.toLowerCase() == "checkbox" || controlType.toLowerCase() == "radio"))
        {
            window.setTimeout(
                function()
                {
                    try 
                    {
                        controlToFocus.focus();
                    }
                    catch(e)
                    {}
                }, 500);
        }
        else
        {
            try 
            {
                Telerik.Web.UI.RadAjaxControl.SetSelectionFocus(controlToFocus);
                controlToFocus.focus();
            }
            catch(e)
            {}
        }
    }
};

Telerik.Web.UI.RadAjaxControl.SetSelectionFocus = function(element)
{
    if (element.createTextRange == null)
    {
        return;
    }
        
	var range = null;
	try
	{
	    range = element.createTextRange();
	}
	catch(e){}
	
	if (range != null)
	{
	    range.moveStart('textedit', range.text.length);
	    range.collapse(false);
	    range.select();
	}
};

Telerik.Web.UI.RadAjaxControl.panelsToClear = [];

Telerik.Web.UI.RadAjaxControl.UpdateElement = function(id, html)
{
    var element = $get(id);
    if(element != null)
    {
        element.innerHTML =  html;

        var scripts = Telerik.Web.UI.RadAjaxControl.GetScriptsSrc(html);
        for(var i = 0, length = scripts.length; i < length; i++)
        {
            Telerik.Web.UI.RadAjaxControl.IncludeClientScript(scripts[i]);
        }
        
        scripts = Telerik.Web.UI.RadAjaxControl.GetTags(html, "script");
        for(var i = 0, length = scripts.length; i < length; i++)
        {
            var script = scripts[i];
            if(script.inner != "")
            {
                Telerik.Web.UI.RadAjaxControl.EvalScriptCode(script.inner);
             }
        }

        var head = document.getElementsByTagName("head")[0];
        var hrefs = Telerik.Web.UI.RadAjaxControl.GetLinkHrefs(html);
        for(var i = 0, length = hrefs.length; i < length; i++)
        {
            var href = hrefs[i];
            var link = document.createElement("link");
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("href", href);
            head.appendChild(link);
        }

    }
};

Telerik.Web.UI.RadAjaxControl.IncludeClientScript = function(src)
{
    var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

	request.open("GET", src, false);
	request.send(null);
	
	if(request.status == 200)
	{
		var scriptCode = request.responseText;
		Telerik.Web.UI.RadAjaxControl.EvalScriptCode(scriptCode);
	}
};

Telerik.Web.UI.RadAjaxControl.EvalScriptCode = function(scriptCode)
{
	if (Telerik.Web.UI.RadAjaxControl.IsSafari())
	{
		scriptCode = scriptCode.replace(/^\s*<!--((.|\n)*)-->\s*$/mi, "$1");
	}
	
    var newScript = document.createElement("script");
    newScript.setAttribute("type", "text/javascript");    		
   
    if (Telerik.Web.UI.RadAjaxControl.IsSafari())
    {
        newScript.appendChild(document.createTextNode(scriptCode));
    }
    else
    {
        newScript.text = scriptCode;
    }
    
	var scriptContainer = document.getElementsByTagName("head")[0];
	
	scriptContainer.appendChild(newScript);
    
    if (Telerik.Web.UI.RadAjaxControl.IsSafari())
    {
        newScript.innerHTML = "";
    }
    else
    {
        newScript.parentNode.removeChild(newScript);
    }
};

Telerik.Web.UI.RadAjaxControl.GetTags = function(htmlString, tagName)
{
    var result = [];
    var html = htmlString;
    while(1)
    {
        var tagContent = Telerik.Web.UI.RadAjaxControl.GetTag(html, tagName);
        if (tagContent.index == -1)
            break;
            
        result[result.length] = tagContent;
        var lastIndex = tagContent.index + tagContent.outer.length;
        html = html.substring(lastIndex, html.length);
    }
    return result;
}

Telerik.Web.UI.RadAjaxControl.GetTag = function(htmlString, tagName, defaultValue)
{
    if (typeof(defaultValue) == "undefined")
        defaultValue = "";
        
    var tagMatcher = new RegExp("<" + tagName + "[^>]*>((.|\n|\r)*?)</" + tagName + ">", "i");
    var tagMatch = htmlString.match(tagMatcher);
    
    if (tagMatch != null && tagMatch.length >= 2)
    {
        return { outer: tagMatch[0], inner: tagMatch[1], index: tagMatch.index };
    }
    else
    {
        return { outer: defaultValue, inner: defaultValue, index: -1 };
    }
}

Telerik.Web.UI.RadAjaxControl.GetLinkHrefs = function(htmlString)
{
    var html = htmlString;
    var hrefs = [];
    while(1)
    {
        var match = html.match(/<link[^>]*href=('|")?([^'"]*)('|")?([^>]*)>.*?(<\/link>)?/i);
        if (match == null || match.length < 3)
            break;
            
        var value = match[2];
        hrefs[hrefs.length] = value;
        var lastIndex = match.index + value.length;
        html = html.substring(lastIndex, html.length);
    }
    return hrefs;
}

Telerik.Web.UI.RadAjaxControl.GetScriptsSrc = function(htmlString)
{
    var html = htmlString;
    var hrefs = [];
    while(1)
    {
        var match = html.match(/<script[^>]*src=('|")?([^'"]*)('|")?([^>]*)>.*?(<\/script>)?/i);
        if (match == null || match.length < 3)
            break;
            
        var value = match[2];
        hrefs[hrefs.length] = value;
        var lastIndex = match.index + value.length;
        html = html.substring(lastIndex, html.length);
    }
    return hrefs;
}

Telerik.Web.UI.RadAjaxControl.IsSafari = function()
{
	return (navigator.userAgent.match(/safari/i) != null);
};;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadAjaxLoadingPanel = function(element) 
{
    Telerik.Web.UI.RadAjaxLoadingPanel.initializeBase(this, [element]);
    
    this._uniqueID = "";

    this._minDisplayTime = 0;
    this._initialDelayTime = 0;
    this._isSticky = false;
    this._transparency = 0;
    this._manager = null;
    this._zIndex = 90000;
    
    // OBSOLETE!
    this.UniqueID = this._uniqueID;
    this.MinDisplayTime = this._minDisplayTime;
    this.InitialDelayTime = this._initialDelayTime;
    this.IsSticky = this._isSticky;
    this.Transparency = this._transparency;
    this.ZIndex = this._zIndex;
}

Telerik.Web.UI.RadAjaxLoadingPanel.prototype = 
{
    initialize: function() 
    {
       Telerik.Web.UI.RadAjaxLoadingPanel.callBaseMethod(this, 'initialize');
    },
    
    dispose: function() 
    {
        Telerik.Web.UI.RadAjaxLoadingPanel.callBaseMethod(this, 'dispose');
    },
    
    get_zIndex : function()
    {
        return this._zIndex;
    },
    
    set_zIndex : function(value)
    {
        if (this._zIndex != value)
        {
            this._zIndex = value;
        }
    },
    
    get_uniqueID : function() 
    {
        return this._uniqueID;
    },
    set_uniqueID : function(value) 
    {
        if (this._uniqueID != value) 
        {
            this._uniqueID = value;
            window[Sys.WebForms.PageRequestManager.getInstance()._uniqueIDToClientID(this._uniqueID)] = this;
        }
    },
    
    get_initialDelayTime : function()
    {
        return this._initialDelayTime;
    },
    set_initialDelayTime : function(value)
    {
        if (this._initialDelayTime != value)
        {
            this._initialDelayTime = value;
        }
    },
    
    get_isSticky : function()
    {
        return this._isSticky;
    },
    set_isSticky : function(value)
    {
        if (this._isSticky != value)
        {
            this._isSticky = value;
        }
    },
    
    get_minDisplayTime : function()
    {
        return this._minDisplayTime;
    },
    set_minDisplayTime : function(value)
    {
        if (this._minDisplayTime != value)
        {
            this._minDisplayTime = value;
        }
    },
    
    get_transparency : function()
    {
        return this._transparency;
    },
    set_transparency : function(value)
    {
        if (this._transparency != value)
        {
            this._transparency = value;
        }
    },          

    show: function(updatedElementID)
    {        
	    var updatedElement = $get(updatedElementID + "_wrapper");
	    if ((typeof(updatedElement) == "undefined") || (!updatedElement))
	    {
		    updatedElement = $get(updatedElementID);
	    }

	    var loadingPanelHtmlElement = this.get_element();
	    if (!(updatedElement && loadingPanelHtmlElement))
	    {
		    return false;
	    }

	    var initialDelay = this._initialDelayTime;
	    var loadingPanel = this;

	    var clone = (!this._isSticky)? this.cloneLoadingPanel(loadingPanelHtmlElement, updatedElementID) : loadingPanelHtmlElement;

	    if (initialDelay)
	    {
            window.setTimeout(function() 
            {
                 try
                 {
                    if (loadingPanel._manager != null && loadingPanel._manager._isRequestInProgress)
                        loadingPanel.displayLoadingElement(clone, updatedElement);
                 }
                 catch(e)
                 {}  
             }, initialDelay);				
	    }
	    else
	    {
		    this.displayLoadingElement(clone, updatedElement);
	    }
	    
	    return true;
    },
    
    hide : function(updatedElementID)
    {
        var element = $get(updatedElementID);
        
        var newID = String.format("{0}_wrapper", updatedElementID);
        var newElement = $get(newID);
        if(newElement)
        {
            element = newElement;
        }

        if (this.get_element() == null)
        {        
            var el = $get(Sys.WebForms.PageRequestManager.getInstance()._uniqueIDToClientID(this._uniqueID));
            if(el == null)
                return;
            this._element = el;    
        }
		    

	    var displayedPanel = (!this._isSticky) ? $get(this.get_element().id + updatedElementID) : this.get_element();

	    var now = new Date();

	    if (displayedPanel == null)
		    return;

	    var timeSpan = now - displayedPanel._startDisplayTime;
        var minDisplayTime = this._minDisplayTime;

		if (this._isSticky)
		{
		    if (minDisplayTime > timeSpan)
		    {
                window.setTimeout(function()
                {
                    displayedPanel.style.display = "none";
                }, minDisplayTime)
		    }
		    else
		    {
		        displayedPanel.style.display = "none";
		    }
		}
		else
		{
		    if (minDisplayTime > timeSpan)
		    {
                window.setTimeout(function()
                {
                    displayedPanel.parentNode.removeChild(displayedPanel);
                    if (typeof(element) != "undefined" && (element != null))
		            {
			            element.style.visibility = "visible";
		            }
		        }, minDisplayTime);
		    }
		    else
		    {
    		    displayedPanel.parentNode.removeChild(displayedPanel);
    		    if (typeof(element) != "undefined" && (element != null))
		        {
			        element.style.visibility = "visible";
		        }
    		}
		}
    },

    cloneLoadingPanel: function(panelElement, updatedElementID)
    {
	    var clone = panelElement.cloneNode(false);
	    clone.innerHTML = panelElement.innerHTML;
	    
	    clone.id = panelElement.id + updatedElementID;

		document.body.insertBefore(clone, document.body.firstChild);
	    
	    return clone;
    },

    displayLoadingElement : function(loadingElement, updatedElement)
    {
		if (!this._isSticky)
		{
			var rect = this.getElementRectangle(updatedElement);
			loadingElement.style.position = "absolute";				
			loadingElement.style.width = rect.width + "px";
			loadingElement.style.height = rect.height+ "px";
			loadingElement.style.left = rect.left+ "px";
			loadingElement.style.top = rect.top+ "px";
			loadingElement.style.textAlign = "center";
			loadingElement.style.zIndex = this._zIndex;
		}

		loadingElement.style.display = "";
		loadingElement._startDisplayTime = new Date();
		
        var transparency = 100 - parseInt(this._transparency);
		if (parseInt(this._transparency) > 0)			
		{
			if (loadingElement.style && loadingElement.style.MozOpacity != null)
			{
				loadingElement.style.MozOpacity = transparency/100;
			}
			else if (loadingElement.style && loadingElement.style.opacity != null)
			{
				loadingElement.style.opacity = transparency/100;
			}
			else if (loadingElement.style && loadingElement.style.filter != null)
			{
				loadingElement.style.filter = "alpha(opacity=" + transparency + ");";
				loadingElement.style.zoom = 1;
			}
		}
		else if (!this._isSticky)
		{
			updatedElement.style.visibility = "hidden";
		}
    },
    
    getElementRectangle : function(element)
    {
	    if (!element) 
	    { 
		    element = this;
	    } 

	    var position = $telerik.getLocation(element);
        
	    var left = position.x; 
	    var top = position.y; 

	    var width = element.offsetWidth; 
	    var height = element.offsetHeight; 

	    return {"left" : left, "top" : top, "width" : width, "height" : height};
    }

}

//$telerik.makeCompatible(Telerik.Web.UI.RadAjaxLoadingPanel);
Telerik.Web.UI.RadAjaxLoadingPanel.registerClass('Telerik.Web.UI.RadAjaxLoadingPanel', Sys.UI.Control);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadAjaxManager = function(element) 
{
    Telerik.Web.UI.RadAjaxManager.initializeBase(this, [element]);
    
    this._ajaxSettings = [];
    this._defaultLoadingPanelID = "";
    
    this._initiators = {};
    this._loadingPanelsToHide = [];

    this._isRequestInProgress = false;
    
    this.Type = "Telerik.Web.UI.RadAjaxManager";
    
    this._updatePanelsRenderMode = null;
    
    // OBSOLETE!
    this.AjaxSettings = this._ajaxSettings;
    this.DefaultLoadingPanelID = this._defaultLoadingPanelID;
}

Telerik.Web.UI.RadAjaxManager.prototype = 
{
    initialize: function() 
    {
       Telerik.Web.UI.RadAjaxManager.callBaseMethod(this, 'initialize');

       var element = this.get_element();
       if(element != null && element.parentNode != null && element.parentNode.id == element.id + "SU")
       {
            element.parentNode.style.display = "none";
       }
       
       var ajaxSettings = this.get_ajaxSettings();
       for(var i = 0, length = ajaxSettings.length; i < length; i++)
       {
            this._initiators[ajaxSettings[i].InitControlID] = ajaxSettings[i].UpdatedControls;
       }
    },
    
    dispose: function() 
    {
        Telerik.Web.UI.RadAjaxManager.callBaseMethod(this, 'dispose');
    },

    get_ajaxSettings : function() 
    {
        return this._ajaxSettings;
    },
//    set_ajaxSettings : function(value) 
//    {
//        if (this._ajaxSettings != value) 
//        {
//            this._ajaxSettings = value;
//        }
//    },
    
    get_defaultLoadingPanelID : function() 
    {
        return this._defaultLoadingPanelID;
    },
    set_defaultLoadingPanelID : function(value) 
    {
        if (this._defaultLoadingPanelID != value) 
        {
            this._defaultLoadingPanelID = value;
        }
    },
    
    get_updatePanelsRenderMode: function() 
    {
        return this._updatePanelsRenderMode;
    },
    set_updatePanelsRenderMode : function(value) 
    {
        if (this._updatePanelsRenderMode != value) 
        {
            this._updatePanelsRenderMode = value;
            
            this._applyUpdatePanelsRenderMode(value);
        }
    },
    
    _applyUpdatePanelsRenderMode : function(value)
    {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        var ids = requestManager._updatePanelClientIDs;

        for(var i = 0; i < ids.length; i++)
        {
            var panel = $get(ids[i]);
            if(panel)
            {
                if(panel.tagName.toLowerCase() == "span") continue;
                panel.style.display = (value == 0)? "block" : "inline";
            }
        }
    },

    showLoadingPanels : function(id, ajaxSettings)
    {
         for (var i = 0, length = ajaxSettings.length; i < length; i++)
         {
            if(ajaxSettings[i].InitControlID == id)
            {
                var ajaxSetting = ajaxSettings[i];
                for (var j = 0, length2 = ajaxSetting.UpdatedControls.length; j < length2; j++)
                {
                    var updated = ajaxSetting.UpdatedControls[j];

                    var panelID = updated.PanelID;
                    
                    if (panelID == "")
                    {
                        panelID = this._defaultLoadingPanelID;
                    }
                                    
                    var controlID = updated.ControlID;
                    if (controlID == this._uniqueID)
                        continue;

                    var panel = $find(panelID)
                    if (panel != null)
                    {
                        panel._manager = this;

                        if(panel.show(controlID))
                        {
                            var obj = { "Panel" : panel, "ControlID" : controlID }

                            if(!Array.contains(this._loadingPanelsToHide, obj))
                            {
                                this._loadingPanelsToHide[this._loadingPanelsToHide.length] = obj;
                            }
                        }
                    }
                }
            }
         }
    },

    _initializeRequest : function(sender, args)
    {
        Telerik.Web.UI.RadAjaxManager.callBaseMethod(this, '_initializeRequest', [sender, args]);

        if (!this._isRequestInProgress)
            return;

        var postBackElement = args.get_postBackElement();
        if (postBackElement != null)
        {
            if (this._initiators[postBackElement.id])
            {
                this.showLoadingPanels(postBackElement.id, this.get_ajaxSettings());
            }
            else
            {
                 var parentNode = postBackElement.parentNode;
                 var found = false;
                 while (parentNode != null)
                 {
                    if (parentNode.id && this._initiators[parentNode.id])
                    {
                        found = true;
                        break;
                    }
                    parentNode = parentNode.parentNode;
                 }
                
                if (found)
                {
                    this.showLoadingPanels(parentNode.id, this.get_ajaxSettings());
                }
            }
        } 
    },
    
    updateElement : function(id, html)
    {
        Telerik.Web.UI.RadAjaxControl.UpdateElement(id, html);
    }
}

//$telerik.makeCompatible(Telerik.Web.UI.RadAjaxManager);
Telerik.Web.UI.RadAjaxManager.registerClass('Telerik.Web.UI.RadAjaxManager', Telerik.Web.UI.RadAjaxControl);


Telerik.Web.UI.RadAjaxManager.UpdateElement = function(id, html)
{
    Telerik.Web.UI.RadAjaxControl.UpdateElement(id, html);
};;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadAjaxPanel = function(element) 
{
    Telerik.Web.UI.RadAjaxPanel.initializeBase(this, [element]);
    
    this._loadingPanelID = "";
    this._loadingPanelsToHide = [];
    
    this.Type = "Telerik.Web.UI.RadAjaxPanel";
    
    // OBSOLETE!
    this.LoadingPanelID = this._loadingPanelID;
}

Telerik.Web.UI.RadAjaxPanel.prototype = 
{
    initialize: function() 
    {
       var parentNode = this.get_element().parentNode;
       
       if(this.get_element().style.height != "")
       {
            parentNode.style.height = this.get_element().style.height;
            this.get_element().style.height = "100%";
       }
       
       if(this.get_element().style.width != "")
       {
            parentNode.style.width = this.get_element().style.width;
            this.get_element().style.width = "";
       }
       
       Telerik.Web.UI.RadAjaxPanel.callBaseMethod(this, 'initialize');
    },
    
    dispose: function() 
    {
        Telerik.Web.UI.RadAjaxPanel.callBaseMethod(this, 'dispose');
    },

    _initializeRequest : function(sender, args)
    {
        Telerik.Web.UI.RadAjaxPanel.callBaseMethod(this, '_initializeRequest', [sender, args]);
        
        if (!this._isRequestInProgress)
            return;

        var postBackElement = args.get_postBackElement();
        if (postBackElement != null && (postBackElement == this.get_element() || this.isChildOf(postBackElement, this.get_element())))
        {
            var panel = $find(this._loadingPanelID);
            if (panel != null)
            {
                panel._manager = this;

                if (panel.show(this.get_element().id))
                {
                    var obj = { "Panel" : panel, "ControlID" : this.get_element().id }

                    if(!Array.contains(this._loadingPanelsToHide, obj))
                    {
                        this._loadingPanelsToHide[this._loadingPanelsToHide.length] = obj;
                    }
                }
            }
        } 
    },
    
    get_loadingPanelID : function()
    {
        return this._loadingPanelID;
    },
    
    set_loadingPanelID : function(value)
    {
        if (this._loadingPanelID != value)
        {
            this._loadingPanelID = value;
        }
    }
}

Telerik.Web.UI.RadAjaxPanel.registerClass('Telerik.Web.UI.RadAjaxPanel', Telerik.Web.UI.RadAjaxControl);;
/* END Telerik.Web.UI.Ajax.Ajax.js */
/* START Telerik.Web.UI.Common.Animation.AnimationScripts.js */
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

Type.registerNamespace('Telerik.Web.Animation');

// Create an alias for the namespace to save 25 chars each time it's used since
// this is a very long script and will take awhile to download
var $TWA = Telerik.Web.Animation;

$TWA.registerAnimation = function(name, type) {
    /// <summary>
    /// Register an animation with the AJAX Control Toolkit animation framework. This serves a dual purpose:
    /// 1) to add standard utility methods to the animation type (such as a <code>play</code> method that creates
    /// an animation, plays it, and disposes it when the animation is over), and 2) to associate a name with the
    /// type that will be used when creating animations from a JSON description.  This method can also be called
    /// by other animation libraries to seamlessly interoperate with the AJAX Control Toolkit's animation
    /// framework.
    /// </summary>
    /// <param name="name" type="String">
    /// Name of the animation that will be used as the XML tag name in the XML animation description.  It
    /// should be a valid XML tag (i.e. an alpha-numeric sequence with no spaces, special characters, etc.).
    /// </param>
    /// <param name="type" type="Type">
    /// The type of the new animation must inherit from <see cref="Telerik.Web.Animation.Animation" />.
    /// </param>
    /// <returns />

    // Make sure the type inherits from Telerik.Web.Animation.Animation
    if (type && ((type === $TWA.Animation) || (type.inheritsFrom && type.inheritsFrom($TWA.Animation)))) {
        // We'll store the animation name/type mapping in a "static" object off of
        // Telerik.Web.Animation.  If this __animations object hasn't been
        // created yet, demand create it on the first registration.
        if (!$TWA.__animations) {
            $TWA.__animations = { };
        }
        
        // Add the current type to the collection of animations
        $TWA.__animations[name.toLowerCase()] = type;
        
        // Add a play function that will make it very easy to create, play, and
        // dispose of an animation.  This is effectively a "static" function on
        // each animation and will take the same parameters as that animation's
        // constructor.
        type.play = function() {
            /// <summary>
            /// Create an animation, play it immediately, and dispose it when finished.
            /// </summary>
            /// <param parameterArray="true" elementType="Object">
            /// The play function takes the same parameters as the type's constructor
            /// </param>
            /// <returns />
        
            // Create and initialize a new animation of the right type and pass in
            // any arguments given to the play function
            var animation = new type();
            type.apply(animation, arguments);
            animation.initialize();
            
            // Add an event handler to dispose the animation when it's finished
            var handler = Function.createDelegate(animation,
                function() {
                    /// <summary>
                    /// Dispose the animation after playing
                    /// </summary>
                    /// <returns />
                    animation.remove_ended(handler);
                    handler = null;
                    animation.dispose();
                });
            animation.add_ended(handler);
            
            // Once the animation has been created and initialized, play it and
            // dispose it as soon as it's finished
            animation.play();            
        }
    } else {
        // Raise an error if someone registers an animation that doesn't inherit
        // from our base Animation class
        throw Error.argumentType('type', type, $TWA.Animation, "Telerik.Web.Animation.registerAnimation can only register types that inherit from Telerik.Web.Animation.Animation");
    }
}

// In the Xml comments for each of the animations below, there is a special <animation /> tag
// that describes how the animation is referenced from a generic XML animation description


$TWA.Animation = function(target, duration, fps) {
    /// <summary>
    /// <code>Animation</code> is an abstract base class used as a starting point for all the other animations.
    /// It provides the basic mechanics for the animation (playing, pausing, stopping, timing, etc.)
    /// and leaves the actual animation to be done in the abstract methods <code>getAnimatedValue</code>
    /// and <code>setValue</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <field name="DynamicProperties" type="Object">
    /// The DynamicProperties collection is used to associate JavaScript expressions with
    /// properties.  The expressions are evaluated just before the animation is played
    /// everytime (in the base onStart method).  The object itself maps strings with the
    /// names of property setters (like "set_verticalOffset") to JavaScript expressions
    /// (like "$find('MyBehavior').get_element().offsetHeight").  Note specifically that
    /// the dynamic properties are JavaScript expressions and not abitrary statements (i.e.
    /// you can't include things like "return foo;"), although you can include anything
    /// inside an anonymous function definition that you immediately invoke (i.e.,
    /// "(function() { return foo; })()").  A dynamic property can be set in the generic
    /// XML animation description by appending Script onto any legitimate property name
    /// (for example, instead of Height="70" we could use
    /// HeightScript="$find('MyBehavior').get_element().offsetHeight").  Any exceptions
    /// raised when setting dynamic properties (including both JavaScript evaluation errors
    /// and other exceptions raised by property setters) will only be propogated when
    /// debugging.
    /// </field>
    /// <remarks>
    /// Animations need to be as fast as possible - even in debug mode.  Don't add validation code to
    /// methods involved in every step of the animation.
    /// </remarks>
    /// <animation>Animation</animation>
    $TWA.Animation.initializeBase(this);
    
    // Length of the animation in seconds
    this._duration = 1;
    
    // Number of steps per second
    this._fps = 25;
    
    // Target Sys.UI.DomElement of the animation
    this._target = null;
    
    // Tick event handler
    this._tickHandler = null;
    
    // Animation timer
    this._timer = null;
    
    // Percentage of the animation already played
    this._percentComplete = 0;
    
    // Percentage of the animation to play on each step
    this._percentDelta = null;
    
    // Reference to the animation that owns this animation (currently only set in 
    // ParallelAnimation.add).  This concept of ownership allows an entire animation
    // subtree to be driven off a single timer so all the operations are properly
    // synchronized.
    this._owner = null;
    
    // Reference to the animation that contains this as a child (this is set
    // in ParentAnimation.add).  The primary use of the parent animation is in
    // resolving the animation target when one isn't specified.
    this._parentAnimation = null;
    
    // The DynamicProperties collection is used to associate JavaScript expressions with
    // properties.  The expressions are evaluated just before the animation is played
    // everytime (in the base onStart method).  See the additional information in the
    // XML <field> comment above.
    this.DynamicProperties = { };
    
    // Set the target, duration, and fps if they were provided in the constructor
    if (target) {
        this.set_target(target);
    }
    if (duration) {
        this.set_duration(duration);
    }
    if (fps) { 
        this.set_fps(fps);
    }
}
$TWA.Animation.prototype = {
    dispose : function() {
        /// <summary>
        /// Dispose the animation
        /// </summary>
        /// <returns />
        
        if (this._timer) {
            this._timer.dispose();
            this._timer = null;
        }
        
        this._tickHandler = null;
        this._target = null;
        
        $TWA.Animation.callBaseMethod(this, 'dispose');
    },
    
    play : function() {
        /// <summary>
        /// Play the animation from the beginning or where it was left off when paused.
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>play</code> on its parent instead.
        /// </remarks>
        
        // If ownership of this animation has been claimed, then we'll require the parent to
        // handle playing the animation (this is very important because then the entire animation
        // tree runs on the same timer and updates consistently)
        if (!this._owner) {
            var resume = true;
            if (!this._timer) {
                resume = false;
                
                if (!this._tickHandler) {
                    this._tickHandler = Function.createDelegate(this, this._onTimerTick);
                }

                this._timer = new Telerik.Web.Timer();
                this._timer.add_tick(this._tickHandler);
               
                this.onStart();
                
                this._timer.set_interval(1000 / this._fps);
                this._percentDelta = 100 / (this._duration * this._fps);
                this._updatePercentComplete(0, true);
            }

            this._timer.set_enabled(true);
            
            this.raisePropertyChanged('isPlaying');
            if (!resume) {
                this.raisePropertyChanged('isActive');
            }
        }
    },
    
    pause : function() {
        /// <summary>
        /// Pause the animation if it is playing.  Calling <code>play</code> will resume where
        /// the animation left off.
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>pause</code> on its parent instead.
        /// </remarks>
        
        if (!this._owner) {
            if (this._timer) {
                this._timer.set_enabled(false);
                
                this.raisePropertyChanged('isPlaying');
            }
        }
    },
    
    stop : function(finish) {
        /// <summary>
        /// Stop playing the animation.
        /// </summary>
        /// <param name="finish" type="Boolean" mayBeNull="true" optional="true">
        /// Whether or not stopping the animation should leave the target element in a state
        /// consistent with the animation playing completely by performing the last step.
        /// The default value is true.
        /// </param>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>stop</code> on
        /// its parent instead.
        /// </remarks>
        
        if (!this._owner) {
            var t = this._timer;
            this._timer = null;
            if (t) {
                t.dispose();
                
                if (this._percentComplete !== 100) {
                    this._percentComplete = 100;
                    this.raisePropertyChanged('percentComplete');
                    if (finish || finish === undefined) {
                        this.onStep(100);
                    }
                }
                this.onEnd();
                
                this.raisePropertyChanged('isPlaying');
                this.raisePropertyChanged('isActive');
            }
        }
    },
    
    onStart : function() {
        /// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        
        this.raiseStarted();
        
        // Initialize any dynamic properties
        for (var property in this.DynamicProperties) {
            try {
                // Invoke the property's setter on the evaluated expression
                this[property](eval(this.DynamicProperties[property]));
            } catch(ex) {
                // Propogate any exceptions if we're debugging, otherwise eat them
                if ( Sys.Debug.isDebug) {
                    throw ex;
                }
            }
        }
    },
    
    onStep : function(percentage) {
        /// <summary>
        /// The <code>onStep</code> method is called repeatedly to progress the animation through each frame
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns />
        
        this.setValue(this.getAnimatedValue(percentage));
    },
    
    onEnd : function() {
        /// <summary>
        /// The <code>onEnd</code> method is called just after the animation is played each time.
        /// </summary>
        /// <returns />
        
        this.raiseEnded();
    },
    
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Determine the state of the animation after the given percentage of its duration has elapsed
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns type="Object">
        /// State of the animation after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        throw Error.notImplemented();
    },
    
    setValue : function(value) {
        /// <summary>
        /// Set the current state of the animation
        /// </summary>
        /// <param name="value" type="Object">Current state of the animation (as retreived from <code>getAnimatedValue</code>)</param>
        /// <returns />
        throw Error.notImplemented();
    },
    
    interpolate : function(start, end, percentage) {
        /// <summary>
        /// The <code>interpolate</code> function is used to find the appropriate value between starting and
        /// ending values given the current percentage.
        /// </summary>
        /// <param name="start" type="Number">
        /// Start of the range to interpolate
        /// </param>
        /// <param name="end" type="Number">
        /// End of the range to interpolate
        /// </param>
        /// <param name="percentage" type="Number">
        /// Percentage completed in the range to interpolate
        /// </param>
        /// <returns type="Number">
        /// Value the desired percentage between the start and end values
        /// </returns>
        /// <remarks>
        /// In the future, we hope to make several implementations of this available so we can dynamically
        /// change the apparent speed of the animations, although it may make more sense to modify the
        /// <code>_updatePercentComplete</code> function instead.
        /// </remarks>
        return start + (end - start) * (percentage / 100);
    },
    
    _onTimerTick : function() {
        /// <summary>
        /// Handler for the tick event to move the animation along through its duration
        /// </summary>
        /// <returns />
        this._updatePercentComplete(this._percentComplete + this._percentDelta, true);
		this.raise_onTick();
    },
    
    _updatePercentComplete : function(percentComplete, animate) {
        /// <summary>
        /// Update the animation and its target given the current percentage of its duration that
        /// has already elapsed
        /// </summary>
        /// <param name="percentComplete" type="Number">
        /// Percentage of the animation duration that has already elapsed
        /// </param>
        /// <param name="animate" type="Boolean" mayBeNull="true" optional="true">
        /// Whether or not updating the animation should visually modify the animation's target
        /// </param>
        /// <returns />
        
        if (percentComplete > 100) {
            percentComplete = 100;
        }
        
        this._percentComplete = percentComplete;
        this.raisePropertyChanged('percentComplete');
        
        if (animate) {
            this.onStep(percentComplete);
        }
        
        if (percentComplete === 100) {
            this.stop(false);
        }
    },
    
    setOwner : function(owner) {
        /// <summary>
        /// Make this animation the child of another animation
        /// </summary>
        /// <param name="owner" type="Telerik.Web.Animation.Animation">
        /// Parent animation
        /// </param>
        /// <returns />
        this._owner = owner;
    },
    
    raiseStarted : function() {
        /// <summary>
        /// Raise the <code>started</code> event
        /// </summary>
        /// <returns />
        var handlers = this.get_events().getHandler('started');
        if (handlers) {
            handlers(this, Sys.EventArgs.Empty);
        }
    },
    
    add_started : function(handler) {
        /// <summary>
        /// Adds an event handler for the <code>started</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to add to the event.
        /// </param>
        /// <returns />
        this.get_events().addHandler("started", handler);
    },
    
    remove_started : function(handler) {
        /// <summary>
        /// Removes an event handler for the <code>started</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to remove from the event.
        /// </param>
        /// <returns />
        this.get_events().removeHandler("started", handler);
    },
    
    raiseEnded : function() {
        /// <summary>
        /// Raise the <code>ended</code> event
        /// </summary>
        /// <returns />
        var handlers = this.get_events().getHandler('ended');
        if (handlers) {
            handlers(this, Sys.EventArgs.Empty);
        }
    },
    
    add_ended : function(handler) {
        /// <summary>
        /// Adds an event handler for the <code>ended</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to add to the event.
        /// </param>
        /// <returns />
        this.get_events().addHandler("ended", handler);
    },
    
    remove_ended : function(handler) {
        /// <summary>
        /// Removes an event handler for the <code>ended</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to remove from the event.
        /// </param>
        /// <returns />
        this.get_events().removeHandler("ended", handler);
    },

	raise_onTick : function ()
	{
        var handlers = this.get_events().getHandler('onTick');
        if (handlers)
		{
            handlers(this, Sys.EventArgs.Empty);
        }
	},
	
	add_onTick : function (handler)
	{
		this.get_events().addHandler("onTick", handler);
	},
	
	remove_onTick : function (handler)
	{
		this.get_events().removeHandler("onTick", handler);
	},

    get_target : function() {
        /// <value type="Sys.UI.DomElement" domElement="true" mayBeNull="true">
        /// Target of the animation.  If the target of this animation is null and
        /// the animation has a parent, then it will recursively use the target of
        /// the parent animation instead.
        /// </value>
        /// <remarks>
        /// Do not set this property in a generic Xml animation description. It should be set
        /// using either the extender's TargetControlID or the AnimationTarget property (the latter
        /// maps to Telerik.Web.Animation.set_animationTarget).  The only valid way to
        /// set this property in the generic Xml animation description is to use the dynamic
        /// property TargetScript="$get('myElement')".
        /// <remarks>
        if (!this._target && this._parentAnimation) {
            return this._parentAnimation.get_target();
        }
        return this._target;
    },
    set_target : function(value) {
        if (this._target != value) {
            this._target = value;
            this.raisePropertyChanged('target');
        }
    },
    
    set_animationTarget : function(id) {
        /// <value type="string" mayBeNull="false">
        /// ID of a Sys.UI.DomElement or Sys.UI.Control to use as the target of the animation
        /// </value>
        /// <remarks>
        /// If no Sys.UI.DomElement or Sys.UI.Control can be found for the given ID, an
        /// argument exception will be thrown.
        /// <remarks>
        
        // Try to find a Sys.UI.DomElement
        var target = null;
        var element = $get(id);
        if (element) {
            target = element;
        } else {
            // Try to find the control in the AJAX controls collection
            var ctrl = $find(id);
            if (ctrl) {
                element = ctrl.get_element();
                if (element) {
                    target = element;
                }
            }
        }
        
        // Use the new target if we have one, or raise an error if not
        if (target) { 
            this.set_target(target);
        } else {
            throw Error.argument('id', String.format('Telerik.Web.Animation.Animation.set_animationTarget requires the ID of a Sys.UI.DomElement or Sys.UI.Control.  No element or control could be found corresponding to "{0}"', id));
        }
    },
    
    get_duration : function() {
        /// <value type="Number">
        /// Length of the animation in seconds.  The default is 1.
        /// </value>
        return this._duration;
    },
    set_duration : function(value) {
        value = this._getFloat(value);
        if (this._duration != value) {
            this._duration = value;
            this.raisePropertyChanged('duration');
        }
    },
    
    get_fps : function() {
        /// <value type="Number" integer="true">
        /// Number of steps per second.  The default is 25.
        /// </value>
        return this._fps;
    },
    set_fps : function(value) {
        value = this._getInteger(value);
        if (this.fps != value) {
            this._fps = value;
            this.raisePropertyChanged('fps');
        }
    },
    
    get_isActive : function() {
        /// <value type="Boolean">
        /// <code>true</code> if animation is active, <code>false</code> if not.
        /// </value>
        return (this._timer !== null);
    },
    
    get_isPlaying : function() {
        /// <value type="Boolean">
        /// <code>true</code> if animation is playing, <code>false</code> if not.
        /// </value>
        return (this._timer !== null) && this._timer.get_enabled();
    },
    
    get_percentComplete : function() {
        /// <value type="Number">
        /// Percentage of the animation already played.
        /// </value>
        return this._percentComplete;
    },
    
    _getBoolean : function(value) {
        /// <summary>
        /// Helper to convert strings to booleans for property setters
        /// </summary>
        /// <param name="value" type="Object">
        /// Value to convert if it's a string
        /// </param>
        /// <returns type="Object">
        /// Value that has been converted if it was a string
        /// </returns>
        if (String.isInstanceOfType(value)) {
            return Boolean.parse(value);
        }
        return value;
    },
    
    _getInteger : function(value) {
        /// <summary>
        /// Helper to convert strings to integers for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value)) {
            return parseInt(value);
        }
        return value;
    },
    
    _getFloat : function(value) {
        /// <summary>
        /// Helper to convert strings to floats for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value)) {
            return parseFloat(value);
        }
        return value;
    },
    
    _getEnum : function(value, type) {
        /// <summary>
        /// Helper to convert strings to enum values for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <param name="type" type="Type">Type of the enum to convert to</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value) && type && type.parse) {
            return type.parse(value);
        }
        return value;
    }
}
$TWA.Animation.registerClass('Telerik.Web.Animation.Animation', Sys.Component);
$TWA.registerAnimation('animation', $TWA.Animation);


$TWA.ParentAnimation = function(target, duration, fps, animations) {
    /// <summary>
    /// The <code>ParentAnimation</code> serves as a base class for all animations that contain children (such as
    /// <see cref="Telerik.Web.Animation.ParallelAnimation" />, <see cref="Telerik.Web.SequenceAnimation" />,
    /// etc.).  It does not actually play the animations, so any classes that inherit from it must do so.  Any animation
    /// that requires nested child animations must inherit from this class, although it will likely want to inherit off of
    /// <see cref="Telerik.Web.Animation.ParallelAnimation" /> or <see cref="Telerik.Web.SequenceAnimation" />
    /// which will actually play their child animations.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="animations" mayBeNull="true" optional="true" parameterArray="true" elementType="Telerik.Web.Animation.Animation">
    /// Array of child animations to be played
    /// </param>
    /// <animation>Parent</animation>
    $TWA.ParentAnimation.initializeBase(this, [target, duration, fps]);
    
    // Array of child animations (there are no assumptions placed on order because
    // it will matter for some derived animations like SequenceAnimation, but not
    // for others like ParallelAnimation) that is demand created in add
    this._animations = [];
    
    // Add any child animations passed into the constructor
    if (animations && animations.length) {
        for (var i = 0; i < animations.length; i++) {
            this.add(animations[i]);
        }
    }
}
$TWA.ParentAnimation.prototype = {
    initialize : function() {
    	/// <summary>
        /// Initialize the parent along with any child animations that have not yet been initialized themselves
    	/// </summary>
    	/// <returns />
        $TWA.ParentAnimation.callBaseMethod(this, 'initialize');
        
        // Initialize all the uninitialized child animations
        if (this._animations) {
            for (var i = 0; i < this._animations.length; i++) {
                var animation = this._animations[i];
                if (animation && !animation.get_isInitialized) {
                    animation.initialize();
                }
            }
        }
    },
    
    dispose : function() {
    	/// <summary>
        /// Dispose of the child animations
    	/// </summary>
    	/// <returns />

        this.clear();
        this._animations = null;
        $TWA.ParentAnimation.callBaseMethod(this, 'dispose');
    },
    
    get_animations : function() {
    	/// <value elementType="Telerik.Web.Animation.Animation">
        /// Array of child animations to be played (there are no assumptions placed on order because it will matter for some
        /// derived animations like <see cref="Telerik.Web.Animation.SequenceAnimation" />, but not for
        /// others like <see cref="Telerik.Web.Animation.ParallelAnimation" />).  To manipulate the child
        /// animations, use the functions <code>add</code>, <code>clear</code>, <code>remove</code>, and <code>removeAt</code>.
    	/// </value>
        return this._animations;
    },
    
    add : function(animation) {
    	/// <summary>
        /// Add an animation as a child of this animation.
    	/// </summary>
    	/// <param name="animation" type="Telerik.Web.Animation.Animation">Child animation to add</param>
    	/// <returns />

        if (this._animations) {
            if (animation) {
                animation._parentAnimation = this;
            }
            Array.add(this._animations, animation);
            this.raisePropertyChanged('animations');
        }
    },
    
    remove : function(animation) {
        /// <summary>
        /// Remove the animation from the array of child animations.
        /// </summary>
        /// <param name="animation" type="Telerik.Web.Animation.Animation">
        /// Child animation to remove
        /// </param>
        /// <returns />
        /// <remarks>
        /// This will dispose the removed animation.
        /// </remarks>

        if (this._animations) {
            if (animation) {
                animation.dispose();
            }
            Array.remove(this._animations, animation);
            this.raisePropertyChanged('animations');
        }
    },
    
    removeAt : function(index) {
        /// <summary>
        /// Remove the animation at a given index from the array of child animations.
        /// </summary>
        /// <param name="index" type="Number" integer="true">
        /// Index of the child animation to remove
        /// </param>
        /// <returns />
        
        if (this._animations) {
            var animation = this._animations[index];
            if (animation) {
                animation.dispose();
            }
            Array.removeAt(this._animations, index);
            this.raisePropertyChanged('animations');
        }
    },
    
    clear : function() {
    	/// <summary>
        /// Clear the array of child animations.
    	/// </summary>
    	/// <remarks>
    	/// This will dispose the cleared child animations.
    	/// </remarks>
    	/// <returns />

        if (this._animations) {
            for (var i = this._animations.length - 1; i >= 0; i--) {
                this._animations[i].dispose();
                this._animations[i] = null;
            }
            Array.clear(this._animations);
            this._animations = [];
            this.raisePropertyChanged('animations');
        }
    }
}
$TWA.ParentAnimation.registerClass('Telerik.Web.Animation.ParentAnimation', $TWA.Animation);
$TWA.registerAnimation('parent', $TWA.ParentAnimation);


$TWA.ParallelAnimation = function(target, duration, fps, animations) {
    /// <summary>
    /// The <code>ParallelAnimation</code> plays several animations simultaneously.  It inherits from
    /// <see cref="Telerik.Web.Animation.ParentAnimation" />, but makes itself the owner of all
    /// its child animations to allow the use a single timer and syncrhonization mechanisms shared with
    /// all the children (in other words, the <code>duration</code> properties of any child animations
    /// are ignored in favor of the parent's <code>duration</code>).  It is very useful in creating
    /// sophisticated effects through combination of simpler animations.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="animations" mayBeNull="true" optional="true" parameterArray="true" elementType="Telerik.Web.Animation.Animation">
    /// Array of child animations
    /// </param>
    /// <animation>Parallel</animation>
    $TWA.ParallelAnimation.initializeBase(this, [target, duration, fps, animations]);
}
$TWA.ParallelAnimation.prototype = {
    add : function(animation) {
    	/// <summary>
        /// Add an animation as a child of this animation and make ourselves its owner.
    	/// </summary>
    	/// <param name="animation" type="Telerik.Web.Animation.Animation">Child animation to add</param>
    	/// <returns />
        $TWA.ParallelAnimation.callBaseMethod(this, 'add', [animation]);
        animation.setOwner(this);
    },
    
    onStart : function() {
        /// <summary>
        /// Get the child animations ready to play
        /// </summary>
        /// <returns />

        $TWA.ParallelAnimation.callBaseMethod(this, 'onStart');
        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onStart();
        }
    },
    
    onStep : function(percentage) {
        /// <summary>
        /// Progress the child animations through each frame
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns />

        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onStep(percentage);
        }
    },
    
    onEnd : function() {
        /// <summary>
        /// Finish playing all of the child animations
        /// </summary>
        /// <returns />

        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onEnd();
        }
        $TWA.ParallelAnimation.callBaseMethod(this, 'onEnd');
    }
}
$TWA.ParallelAnimation.registerClass('Telerik.Web.Animation.ParallelAnimation', $TWA.ParentAnimation);
$TWA.registerAnimation('parallel', $TWA.ParallelAnimation);

$TWA.FadeEffect = function() {
    /// <summary>
    /// The FadeEffect enumeration determines whether a fade animation is used to fade in or fade out.
    /// </summary>
    /// <field name="FadeIn" type="Number" integer="true" />
    /// <field name="FadeOut" type="Number" integer="true" />
    throw Error.invalidOperation();
}
$TWA.FadeEffect.prototype = {
    FadeIn : 0,
    FadeOut : 1
}
$TWA.FadeEffect.registerEnum("Telerik.Web.Animation.FadeEffect", false);

$TWA.FadeAnimation = function(target, duration, fps, effect, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The <code>FadeAnimation</code> is used to fade an element in or out of view, depending on the
    /// provided <see cref="Telerik.Web.Animation.FadeEffect" />, by settings its opacity.
    /// The minimum and maximum opacity values can be specified to precisely control the fade.
    /// You may also consider using <see cref="Telerik.Web.Animation.FadeInAnimation" /> or
    /// <see cref="Telerik.Web.Animation.FadeOutAnimation" /> if you know the only direction you
    /// are fading.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="effect" type="Telerik.Web.Animation.FadeEffect" mayBeNull="true" optional="true">
    /// Determine whether to fade the element in or fade the element out.  The possible values are <code>FadeIn</code>
    /// and <code>FadeOut</code>.  The default value is <code>FadeOut</code>.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>Fade</animation>
    $TWA.FadeAnimation.initializeBase(this, [target, duration, fps]);

    // The effect determines whether or not we fade in or out
    this._effect = (effect !== undefined) ? effect : $TWA.FadeEffect.FadeIn;
    
    // Maximum and minimum opacities default to 100% and 0%
    this._max = (maximumOpacity !== undefined) ? maximumOpacity : 1;
    this._min = (minimumOpacity !== undefined) ? minimumOpacity : 0;
    
    // Starting and ending opacities
    this._start = this._min;
    this._end = this._max;
    
    // Whether the a layout has already been created (to work around IE problems)
    this._layoutCreated = false;

    // Whether or not we should force a layout to be created for IE by giving it a width
    // and setting its background color (the latter is required in case the user has ClearType enabled).
    // http://msdn.microsoft.com/library/default.asp?url=/workshop/author/filter/reference/filters/alpha.asp
    this._forceLayoutInIE = (forceLayoutInIE === undefined || forceLayoutInIE === null) ? true : forceLayoutInIE;
    
    // Current target of the animation that is cached before the animation plays (since looking up
    // the target could mean walking all the way up to the root of the animation's tree, which we don't
    // want to do for every step of the animation)
    this._currentTarget = null;
    
    // Properly set up the min/max values provided by the constructor
    this._resetOpacities();
}
$TWA.FadeAnimation.prototype = {
    _resetOpacities : function() {
    	/// <summary>
        /// Set the starting and ending opacity values based on the effect (i.e. when we're fading
        /// in we go from <code>_min</code> to <code>_max</code>, but we go <code>_max</code> to
        /// <code>_min</code> when fading out)
    	/// </summary>
    	/// <returns />

        if (this._effect == $TWA.FadeEffect.FadeIn) {
            this._start = this._min;
            this._end = this._max;
        } else {
            this._start = this._max;
            this._end = this._min;
        }
    },
    
    _createLayout : function() {
    	/// <summary>
        /// Create a layout when using Internet Explorer (which entails setting a width and also
        /// a background color if it currently has neither)
    	/// </summary>
    	/// <returns />

        var element = this._currentTarget;
        if (element) {
            // Get the original width/height/back color
            var originalWidth = $telerik.getCurrentStyle(element, 'width');
            var originalHeight = $telerik.getCurrentStyle(element, 'height');
            var originalBackColor = $telerik.getCurrentStyle(element, 'backgroundColor');

            // Set the width which will force the creation of a layout
            if ((!originalWidth || originalWidth == '' || originalWidth == 'auto') &&
                (!originalHeight || originalHeight == '' || originalHeight == 'auto')) {
                element.style.width = element.offsetWidth + 'px';
            }
            
            // Set the back color to avoid ClearType problems
            if (!originalBackColor || originalBackColor == '' || originalBackColor == 'transparent' || originalBackColor == 'rgba(0, 0, 0, 0)') {
                element.style.backgroundColor = $telerik.getInheritedBackgroundColor(element);
            }
            
            // Mark that we've created the layout so we only do it once
            this._layoutCreated = true;
        }
    },
    
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />       
        $TWA.FadeAnimation.callBaseMethod(this, 'onStart');
        
        this._currentTarget = this.get_target();
        this.setValue(this._start);
        
        // Force the creation of a layout in IE if we're supposed to and the current browser is Internet Explorer
        if (this._forceLayoutInIE && !this._layoutCreated && Sys.Browser.agent == Sys.Browser.InternetExplorer) {
            this._createLayout();
        }
    },
    
    getAnimatedValue : function(percentage) {
    	/// <summary>
        /// Determine the current opacity after the given percentage of its duration has elapsed
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns type="Number">
        /// Current opacity after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        return this.interpolate(this._start, this._end, percentage);
    },
    
    setValue : function(value) {
        /// <summary>
        /// Set the current opacity of the element.
        /// </summary>
        /// <param name="value" type="Number">
        /// Current opacity (as retreived from <code>getAnimatedValue</code>)
        /// </param>
        /// <returns />
        /// <remarks>
        /// This method will be replaced by a dynamically generated function that requires no logic
        /// to determine whether it should use filters or the style's opacity.
        /// </remarks>
        if (this._currentTarget) {
            $telerik.setOpacity(this._currentTarget, value);
        }
    },
    
//    set_target : function(value) {
//        /// <value type="Sys.UI.DomElement">
//        /// Override the <code>target</code> property to dynamically create the setValue function.
//        /// </value>
//        /// <remarks>
//        /// Do not set this property in a generic Xml animation description. It will be set automatically
//        /// using either the extender's TargetControlID or the AnimationTarget property.
//        /// <remarks>
//        $TWA.FadeAnimation.callBaseMethod(this, 'set_target', [value]);
//        
//        var element = value;
//        if (element) {
//            var filters = element.filters;
//            if (filters) {
//                var alphaFilter = null;
//                if (filters.length !== 0) {
//                    alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
//                }
//                if (!alphaFilter) {
//                    element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (this._start * 100) + ')';
//                    alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
//                }
//                if (alphaFilter) {
//                    this.setValue = function(val) { alphaFilter.opacity = val * 100; }
//                } else {
//                    this.setValue = function(val) {
//                        element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (val * 100) + ')';
//                    };
//                }
//            }
//            else {
//                this.setValue = function(val) { element.style.opacity = val; };
//            }
//        }
//    },
    
    get_effect : function() {
    	/// <value type="Telerik.Web.Animation.FadeEffect">
        /// Determine whether to fade the element in or fade the element out.  The possible values are
        /// <code>FadeIn</code> and <code>FadeOut</code>.  The default value is <code>FadeOut</code>.
    	/// </value>
        return this._effect;
    },
    set_effect : function(value) {
        value = this._getEnum(value, $TWA.FadeEffect);
        if (this._effect != value) {
            this._effect = value;
            this._resetOpacities();
            this.raisePropertyChanged('effect');
        }
    },
    
    get_minimumOpacity : function() {
        /// <value type="Number">
        /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1.
        /// The default value is 0.
        /// </value>
	    return this._min;
    },
    set_minimumOpacity : function(value) {
        value = this._getFloat(value);
        if (this._min != value) {
            this._min = value;
            this._resetOpacities();
            this.raisePropertyChanged('minimumOpacity');
        }
    },
    
    get_maximumOpacity : function() {
        /// <value type="Number">
        /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1.
        /// The default value is 1.
        /// </value>
        return this._max;
    },
    set_maximumOpacity : function(value) {
        value = this._getFloat(value);
        if (this._max != value) {
            this._max = value;
            this._resetOpacities();
            this.raisePropertyChanged('maximumOpacity');
        }
    },
    
    get_forceLayoutInIE : function() {
        /// <value type="Boolean">
        /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
        /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
        /// This is obviously ignored when working in other browsers.
        /// </value>
        return this._forceLayoutInIE;
    },
    set_forceLayoutInIE : function(value) {
        value = this._getBoolean(value);
        if (this._forceLayoutInIE != value) {
            this._forceLayoutInIE = value;
            this.raisePropertyChanged('forceLayoutInIE');
        }
    },
    
    set_startValue : function(value) {
        /// <value type="Number">
        /// Set the start value (so that child animations can set the current opacity as the start value when fading in or out)
        /// </value>
        value = this._getFloat(value);
        this._start = value;
    }
}
$TWA.FadeAnimation.registerClass('Telerik.Web.Animation.FadeAnimation', $TWA.Animation);
$TWA.registerAnimation('fade', $TWA.FadeAnimation);


$TWA.FadeInAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The <code>FadeInAnimation</code> will fade the target in by moving from hidden to visible.
    /// It starts the animation the target's current opacity.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>FadeIn</animation>
    $TWA.FadeInAnimation.initializeBase(this, [target, duration, fps, $TWA.FadeEffect.FadeIn, minimumOpacity, maximumOpacity, forceLayoutInIE]);
}
$TWA.FadeInAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.FadeInAnimation.callBaseMethod(this, 'onStart');
        
        if (this._currentTarget) {
            this.set_startValue($telerik.getOpacity(this._currentTarget));
        }
    }
}
$TWA.FadeInAnimation.registerClass('Telerik.Web.Animation.FadeInAnimation', $TWA.FadeAnimation);
$TWA.registerAnimation('fadeIn', $TWA.FadeInAnimation);


$TWA.FadeOutAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The FadeInAnimation will fade the element out by moving from visible to hidden. It starts the animation
    /// at the element's current opacity.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>FadeOut</animation>
    $TWA.FadeOutAnimation.initializeBase(this, [target, duration, fps, $TWA.FadeEffect.FadeOut, minimumOpacity, maximumOpacity, forceLayoutInIE]);
}
$TWA.FadeOutAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.FadeOutAnimation.callBaseMethod(this, 'onStart');

        if (this._currentTarget) {
            this.set_startValue($telerik.getOpacity(this._currentTarget));
        }
    }
}
$TWA.FadeOutAnimation.registerClass('Telerik.Web.Animation.FadeOutAnimation', $TWA.FadeAnimation);
$TWA.registerAnimation('fadeOut', $TWA.FadeOutAnimation);


$TWA.PropertyAnimation = function(target, duration, fps, property, propertyKey) {
    /// <summary>
    /// The <code>PropertyAnimation</code> is a useful base animation that will assign the value from
    /// <code>getAnimatedValue</code> to a specified <code>property</code>. You can provide the name of
    /// a <code>property</code> alongside an optional <code>propertyKey</code> (which indicates the value
    /// <code>property[propertyKey]</code>, like <code>style['backgroundColor']</code>).
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <animation>Property</animation>
    $TWA.PropertyAnimation.initializeBase(this, [target, duration, fps]);

    // Name of the property to set
    this._property = property;
    
    // Optional Key of the property to set (i.e., if the property were "style" then
    // this might be "backgroundColor")
    this._propertyKey = propertyKey;
    
    // Current target of the animation that is cached before the animation plays (since looking up
    // the target could mean walking all the way up to the root of the animation's tree, which we don't
    // want to do for every step of the animation)
    this._currentTarget = null;
}
$TWA.PropertyAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.PropertyAnimation.callBaseMethod(this, 'onStart');

        this._currentTarget = this.get_target();
    },

    setValue : function(value) {
        /// <summary>
        /// Set the current value of the property
        /// </summary>
        /// <param name="value" type="Object" mayBeNull="true">
        /// Value to assign
        /// </param>
        /// <returns />

        var element = this._currentTarget;
        if (element && this._property && this._property.length > 0) { 
            if (this._propertyKey && this._propertyKey.length > 0 && element[this._property]) {
                element[this._property][this._propertyKey] = value;
            } else {
                element[this._property] = value;
            }
        }
        // Sys.TypeDescriptor.setProperty(this.get_target(), this._property, value, this._propertyKey);
    },
    
    getValue : function() {
        /// <summary>
        /// Get the current value from the property
        /// </summary>
        /// <returns type="Object" mayBeNull="true">
        /// Current value of the property
        /// </returns>

        var element = this.get_target();
        if (element && this._property && this._property.length > 0) { 
            var property = element[this._property];
            if (property) {
                if (this._propertyKey && this._propertyKey.length > 0) {
                    return property[this._propertyKey];
                }
                return property;
            }
        }
        return null;
        // return Sys.TypeDescriptor.getProperty(this.get_target(), this._property, this._propertyKey);
    },
    
    get_property : function() {
        /// <value type="String">
        /// Property of the <code>target</code> element to set when animating
        /// </value>
        return this._property;
    },
    set_property : function(value) {
        if (this._property != value) {
            this._property = value;
            this.raisePropertyChanged('property');
        }
    },
    
    get_propertyKey : function() {
        /// <value type="String" mayBeNull="true" optional="true">
        /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
        /// </value>
        return this._propertyKey;
    },
    set_propertyKey : function(value) {
        if (this._propertyKey != value) {
            this._propertyKey = value;
            this.raisePropertyChanged('propertyKey');
        }
    }
}
$TWA.PropertyAnimation.registerClass('Telerik.Web.Animation.PropertyAnimation', $TWA.Animation);
$TWA.registerAnimation('property', $TWA.PropertyAnimation);


$TWA.DiscreteAnimation = function(target, duration, fps, property, propertyKey, values) {
    /// <summary>
    /// The <code>DiscreteAnimation</code> inherits from <see cref="Telerik.Web.Animation.PropertyAnimation" />
    /// and sets the value of the <code>property</code> to the elements in a provided array of <code>values</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="values" mayBeNull="true" optional="true" parameterArray="true" elementType="Object">
    /// Array of possible values of the property that will be iterated over as the animation is played
    /// </param>
    /// <animation>Discrete</animation>
    $TWA.DiscreteAnimation.initializeBase(this, [target, duration, fps, property, propertyKey]);

    // Values to assign to the property
    this._values = (values && values.length) ? values : [];
}
$TWA.DiscreteAnimation.prototype = {
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Assign the value whose index corresponds to the current percentage
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="Object">
        /// State of the animation after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        var index = Math.floor(this.interpolate(0, this._values.length - 1, percentage));
        return this._values[index];
    },
    
    get_values : function() {
        /// <value parameterArray="true" elementType="Object">
        /// Array of possible values of the property that will be iterated over as the animation is played
        /// </value>
        return this._values;
    },
    set_values : function(value) {
        if (this._values != value) {
            this._values = value;
            this.raisePropertyChanged('values');
        }
    }
}
$TWA.DiscreteAnimation.registerClass('Telerik.Web.Animation.DiscreteAnimation', $TWA.PropertyAnimation);
$TWA.registerAnimation('discrete', $TWA.DiscreteAnimation);


$TWA.InterpolatedAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
    /// <summary>
    /// The <code>InterpolatedAnimation</code> assigns a range of values between <code>startValue</code>
    /// and <code>endValue</code> to the designated property.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="Number" mayBeNull="true" optional="true">
    /// Start of the range of values
    /// </param>
    /// <param name="endValue" type="Number" mayBeNull="true" optional="true">
    /// End of the range of values
    /// </param>
    /// <animation>Interpolated</animation>
    $TWA.InterpolatedAnimation.initializeBase(this, [target, duration, fps, ((property !== undefined) ? property : 'style'), propertyKey]);

    // Start and end values
    this._startValue = startValue;
    this._endValue = endValue;
}
$TWA.InterpolatedAnimation.prototype = {
    get_startValue : function() {
        /// <value type="Number">
        /// Start of the range of values
        /// </value>
        return this._startValue;
    },
    set_startValue : function(value) {
        value = this._getFloat(value);
        if (this._startValue != value) {
            this._startValue = value;
            this.raisePropertyChanged('startValue');
        }
    },
    
    get_endValue : function() {
        /// <value type="Number">
        /// End of the range of values
        /// </value>
        return this._endValue;
    },
    set_endValue : function(value) {
        value = this._getFloat(value);
        if (this._endValue != value) {
            this._endValue = value;
            this.raisePropertyChanged('endValue');
        }
    }   
}
$TWA.InterpolatedAnimation.registerClass('Telerik.Web.Animation.InterpolatedAnimation', $TWA.PropertyAnimation);
$TWA.registerAnimation('interpolated', $TWA.InterpolatedAnimation);


$TWA.ColorAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
    /// <summary>
    /// The <code>ColorAnimation</code> transitions the value of the <code>property</code> between
    /// two colors (although it does ignore the alpha channel). The colors must be 7-character hex strings
    /// (like <code>#246ACF</code>).
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="String" mayBeNull="true" optional="true">
    /// Start of the range of colors
    /// </param>
    /// <param name="endValue" type="String" mayBeNull="true" optional="true">
    /// End of the range of colors
    /// </param>
    /// <animation>Color</animation>
    $TWA.ColorAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);
    
    // Cached start/end RBG triplets
    this._start = null;
    this._end = null;
    
    // Flags indicating whether each dimension of color will be interpolated
    this._interpolateRed = false;
    this._interpolateGreen = false;
    this._interpolateBlue = false;
}
$TWA.ColorAnimation.prototype = {
    onStart : function() {
        /// <summary>
        /// Determine which dimensions of color will be animated
        /// </summary>
        /// <returns />
        $TWA.ColorAnimation.callBaseMethod(this, 'onStart');
       
        this._start = $TWA.ColorAnimation.getRGB(this.get_startValue());
        this._end = $TWA.ColorAnimation.getRGB(this.get_endValue());
        
        this._interpolateRed = (this._start.Red != this._end.Red);
        this._interpolateGreen = (this._start.Green != this._end.Green);
        this._interpolateBlue = (this._start.Blue != this._end.Blue);
    },
    
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Get the interpolated color values
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="String">
        /// Current color formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </returns>

        var r = this._start.Red;
        var g = this._start.Green;
        var b = this._start.Blue;
        
        if (this._interpolateRed)
            r = Math.round(this.interpolate(r, this._end.Red, percentage));
        
        if (this._interpolateGreen)
            g = Math.round(this.interpolate(g, this._end.Green, percentage));
        
        if (this._interpolateBlue)
            b = Math.round(this.interpolate(b, this._end.Blue, percentage));
        
        return $TWA.ColorAnimation.toColor(r, g, b);
    },
    
    set_startValue : function(value) {
        /// <value type="String">
        /// Starting color of the transition formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </value>

        if (this._startValue != value) {
            this._startValue = value;
            this.raisePropertyChanged('startValue');
        }
    },
    
    set_endValue : function(value) {
        /// <value type="String">
        /// Ending color of the transition formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </value>

        if (this._endValue != value) {
            this._endValue = value;
            this.raisePropertyChanged('endValue');
        }
    }   
}
$TWA.ColorAnimation.getRGB = function(color) {
    /// <summary>
    /// Convert the color to an RGB triplet
    /// </summary>
    /// <param name="color" type="String">
    /// Color formatted as a 7-character hex string (like <code>#246ACF</code>)
    /// </param>
    /// <returns type="Object">
    /// Object representing the color with <code>Red</code>, <code>Green</code>, and <code>Blue</code> properties.
    /// </returns>

    if (!color || color.length != 7) {
        throw String.format('Color must be a 7-character hex representation (e.g. #246ACF), not "{0}"', color);
    }
    return { 'Red': parseInt(color.substr(1,2), 16),
             'Green': parseInt(color.substr(3,2), 16),
             'Blue': parseInt(color.substr(5,2), 16) };
}
$TWA.ColorAnimation.toColor = function(red, green, blue) {
    /// <summary>
    /// Convert an RBG triplet into a 7-character hex string (like <code>#246ACF</code>)
    /// </summary>
    /// <param name="red" type="Number" integer="true">
    /// Value of the color's red dimension
    /// </param>
    /// <param name="green" type="Number" integer="true">
    /// Value of the color's green dimension
    /// </param>
    /// <param name="blue" type="Number" integer="true">
    /// Value of the color's blue dimension
    /// </param>
    /// <returns type="String">
    /// Color as a 7-character hex string (like <code>#246ACF</code>)
    /// </returns>

    var r = red.toString(16);
    var g = green.toString(16);
    var b = blue.toString(16);
    if (r.length == 1) r = '0' + r;
    if (g.length == 1) g = '0' + g;
    if (b.length == 1) b = '0' + b;
    return '#' + r + g + b;
}
$TWA.ColorAnimation.registerClass('Telerik.Web.Animation.ColorAnimation', $TWA.InterpolatedAnimation);
$TWA.registerAnimation('color', $TWA.ColorAnimation);


$TWA.LengthAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue, unit) {
    /// <summary>
    /// The <code>LengthAnimation</code> is identical to <see cref="Telerik.Web.Animation.InterpolatedAnimation" />
    /// except it adds a <code>unit</code> to the value before assigning it to the <code>property</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="Number" mayBeNull="true" optional="true">
    /// Start of the range of values
    /// </param>
    /// <param name="endValue" type="Number" mayBeNull="true" optional="true">
    /// End of the range of values
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Unit of the interpolated values.  The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Length</animation>
    $TWA.LengthAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);
    
    // Unit of length (which defaults to px)
    this._unit = (unit != null) ? unit : 'px';
}
$TWA.LengthAnimation.prototype = {

    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Get the interpolated length value
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="String">
        /// Interpolated length
        /// </returns>

        var value = this.interpolate(this.get_startValue(), this.get_endValue(), percentage);
        return Math.round(value) + this._unit;
    },
    
    get_unit : function() {
        /// <value type="String">
        /// Unit of the interpolated values.  The default value is <code>'px'</code>.
        /// </value>
        return this._unit;
    },
    set_unit : function(value) {
        if (this._unit != value) {
            this._unit = value;
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.LengthAnimation.registerClass('Telerik.Web.Animation.LengthAnimation', $TWA.InterpolatedAnimation);
$TWA.registerAnimation('length', $TWA.LengthAnimation);


$TWA.MoveAnimation = function(target, duration, fps, horizontal, vertical, relative, unit) {
    /// <summary>
    /// The <code>MoveAnimation</code> is used to move the <code>target</code> element. If the
    /// <code>relative</code> flag is set to <code>true</code>, then it treats the <code>horizontal</code>
    /// and <code>vertical</code> properties as offsets to move the element. If the <code>relative</code>
    /// flag is <code>false</code>, then it will treat the <code>horizontal</code> and <code>vertical</code>
    /// properties as coordinates on the page where the <code>target</code> element should be moved. It is
    /// important to note that the <code>target</code> must be positioned (i.e. <code>absolutely</code>) so
    /// that settings its <code>top</code>/<code>left<code> style attributes will change its location.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="horizontal" type="Number" mayBeNull="true" optional="true">
    /// If <code>relative</code>  is <code>true</code>, this is the offset to move horizontally. Otherwise this is the x
    /// coordinate on the page where the <code>target</code> should be moved.
    /// </param>
    /// <param name="vertical" type="Number" mayBeNull="true" optional="true">
    /// If <code>relative</code> is <code>true</code>, this is the offset to move vertically. Otherwise this is the y
    /// coordinate on the page where the <code>target</code> should be moved.
    /// </param>
    /// <param name="relative" type="Boolean" mayBeNull="true" optional="true">
    /// <code>true</code> if we are moving relative to the current position, <code>false</code> if we are moving absolutely
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Move</animation>
    $TWA.MoveAnimation.initializeBase(this, [target, duration, fps, null]);

    // Distance to move horizontally and vertically
    this._horizontal = horizontal ? horizontal : 0;
    this._vertical = vertical ? vertical : 0;
    this._relative = (relative === undefined) ? true : relative;
    
    // Length animations representing the movememnts
    this._horizontalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'left', null, null, unit);
    this._verticalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'top', null, null, unit);
    this.add(this._verticalAnimation);
    this.add(this._horizontalAnimation);
}
$TWA.MoveAnimation.prototype = {
    
    onStart : function() {
        /// <summary>
        /// Use the <code>target</code>'s current position as the starting point for the animation
        /// </summary>
        /// <returns />
        $TWA.MoveAnimation.callBaseMethod(this, 'onStart');
        
        // Set the start and end values of the animations by getting
        // the element's current position and applying the offsets
        var element = this.get_target();
        this._horizontalAnimation.set_startValue(element.offsetLeft);
        this._horizontalAnimation.set_endValue(this._relative ? element.offsetLeft + this._horizontal : this._horizontal);
        this._verticalAnimation.set_startValue(element.offsetTop); 
        this._verticalAnimation.set_endValue(this._relative ? element.offsetTop + this._vertical : this._vertical);
    },
    
    get_horizontal : function() {
        /// <value type="Number">
        /// If <code>relative</code>  is <code>true</code>, this is the offset to move horizontally. Otherwise this is the x
        /// coordinate on the page where the <code>target</code> should be moved.
        /// </value>
        return this._horizontal;
    },
    set_horizontal : function(value) {
        value = this._getFloat(value);
        if (this._horizontal != value) {
            this._horizontal = value;
            this.raisePropertyChanged('horizontal');
        }
    },
    
    get_vertical : function() {
        /// <value type="Number">
        /// If <code>relative</code> is <code>true</code>, this is the offset to move vertically. Otherwise this is the y
        /// coordinate on the page where the <code>target</code> should be moved.
        /// </value>
        return this._vertical;
    },
    set_vertical : function(value) {
        value = this._getFloat(value);
        if (this._vertical != value) {
            this._vertical = value;
            this.raisePropertyChanged('vertical');
        }
    },
    
    get_relative : function() {
        /// <value type="Boolean">
        /// <code>true</code> if we are moving relative to the current position, <code>false</code> if we are moving absolutely
        /// </value>
        return this._relative;
    },
    set_relative : function(value) {
        value = this._getBoolean(value);
        if (this._relative != value) {
            this._relative = value;
            this.raisePropertyChanged('relative');
        }
    },
    
    get_unit : function() {
        /// <value type="String" mayBeNull="true">
        /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
        /// </value>
        this._horizontalAnimation.get_unit();
    },
    set_unit : function(value) {
        var unit = this._horizontalAnimation.get_unit();
        if (unit != value) {
            this._horizontalAnimation.set_unit(value);
            this._verticalAnimation.set_unit(value);
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.MoveAnimation.registerClass('Telerik.Web.Animation.MoveAnimation', $TWA.ParallelAnimation);
$TWA.registerAnimation('move', $TWA.MoveAnimation);


$TWA.ResizeAnimation = function(target, duration, fps, width, height, unit) {
    /// <summary>
    /// The <code>ResizeAnimation</code> changes the size of the <code>target</code> from its
    /// current value to the specified <code>width</code> and <code>height</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="width" type="Number" mayBeNull="true" optional="true">
    /// New width of the <code>target</code>
    /// </param>
    /// <param name="height" type="Number" mayBeNull="true" optional="true">
    /// New height of the <code>target</code>
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Resize</animation>
    $TWA.ResizeAnimation.initializeBase(this, [target, duration, fps, null]);

    // New size of the element
    this._width = width;
    this._height = height;
    
    // Animations to set the size across both dimensions
    this._horizontalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'width', null, null, unit);
    this._verticalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'height', null, null, unit);
    this.add(this._horizontalAnimation);
    this.add(this._verticalAnimation);
}
$TWA.ResizeAnimation.prototype = {
    
    onStart : function() {
        /// <summary>
        /// Use the <code>target</code>'s current size as the starting point for the animation
        /// </summary>
        /// <returns />

        $TWA.ResizeAnimation.callBaseMethod(this, 'onStart');
        
        // Set the start and end values of the animations by getting
        // the element's current width and height
        var element = this.get_target();
        this._horizontalAnimation.set_startValue(element.offsetWidth);
        this._verticalAnimation.set_startValue(element.offsetHeight);
        this._horizontalAnimation.set_endValue((this._width !== null && this._width !== undefined) ?
            this._width : element.offsetWidth);
        this._verticalAnimation.set_endValue((this._height !== null && this._height !== undefined) ?
            this._height : element.offsetHeight);
    },
    
    get_width : function() {
        /// <value type="Number">
        /// New width of the <code>target</code>
        /// </value>

        return this._width;
    },
    set_width : function(value) {
        value = this._getFloat(value);
        if (this._width != value) {
            this._width = value;
            this.raisePropertyChanged('width');
        }
    },
    
    get_height : function() {
        /// <value type="Number">
        /// New height of the <code>target</code>
        /// </value>

        return this._height;
    },
    set_height : function(value) {
        value = this._getFloat(value);
        if (this._height != value) {
            this._height = value;   
            this.raisePropertyChanged('height');
        }
    },
    
    get_unit : function() {
        /// <value type="String">
        /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
        /// </value>

        this._horizontalAnimation.get_unit();
    },
    set_unit : function(value) {
        var unit = this._horizontalAnimation.get_unit();
        if (unit != value) {
            this._horizontalAnimation.set_unit(value);
            this._verticalAnimation.set_unit(value);
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.ResizeAnimation.registerClass('Telerik.Web.Animation.ResizeAnimation', $TWA.ParallelAnimation);
$TWA.registerAnimation('resize', $TWA.ResizeAnimation);

$TWA.SequenceAnimation = function(target, duration, fps, animations, iterations) {
    /// <summary>
    /// The <code>SequenceAnimation</code> runs several animations one after the other.  It can also
    /// repeat the sequence of animations for a specified number of iterations (which defaults to a
    /// single iteration, but will repeat forever if you specify zero or less iterations).  Also, the
    /// <code>SequenceAnimation</code> cannot be a child of a <see cref="Telerik.Web.Animation.ParallelAnimation" />
    /// (or any animation inheriting from it).
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="animations" mayBeNull="true" optional="true" parameterArray="true" elementType="Telerik.Web.Animation.Animation">
    /// Array of child animations
    /// </param>
    /// <param name="iterations" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of times to repeatedly play the sequence.  If zero or less iterations are specified, the sequence
    /// will repeat forever.  The default value is 1 iteration.
    /// </param>
    /// <remarks>
    /// The <code>SequenceAnimation</code> ignores the <code>duration</code> and <code>fps</code>
    /// properties, and will let each of its child animations use any settings they please.
    /// </remarks>
    /// <animation>Sequence</animation>
    $TWA.SequenceAnimation.initializeBase(this, [target, duration, fps, animations]);

    // Handler used to determine when an animation has finished
    this._handler = null;
    
    // Flags to note whether we're playing, paused, or stopped
    this._paused = false;
    this._playing = false;
    
    // Index of the currently executing animation in the sequence
    this._index = 0;
    
    // Counter used when playing the animation to determine the remaining number of times to play the entire sequence
    this._remainingIterations = 0;
    
    // Number of iterations
    this._iterations = (iterations !== undefined) ? iterations : 1;
}
$TWA.SequenceAnimation.prototype = {
    dispose : function() {
    	/// <summary>
        /// Dispose the animation
        /// </summary>
        /// <returns />
        this._handler = null;
        $TWA.SequenceAnimation.callBaseMethod(this, 'dispose');
    },
    
    stop : function() {
        /// <summary>
        /// Stop playing the entire sequence of animations
        /// </summary>
        /// <returns />
        /// <remarks>
        /// Stopping this animation will perform the last step of each child animation, thereby leaving their
        /// target elements in a state consistent with the animation playing completely. If this animation is
        /// the child of another, you must call <code>stop</code> on its parent instead.
        /// </remarks>

        if (this._playing) {
            var animations = this.get_animations();
            if (this._index < animations.length) {
                // Remove the handler from the currently running animation
                animations[this._index].remove_ended(this._handler);
                // Call stop on all remaining animations to ensure their
                // effects will be seen
                for (var i = this._index; i < animations.length; i++) {
                    animations[i].stop();
                }
            }
            this._playing = false;
            this._paused = false;
            this.raisePropertyChanged('isPlaying');
            this.onEnd();
        }
    },
    
    pause : function() {
        /// <summary>
        /// Pause the animation if it is playing.  Calling <code>play</code> will resume where
        /// the animation left off.
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>pause</code> on its parent instead.
        /// </remarks>

        if (this.get_isPlaying()) {
            var current = this.get_animations()[this._index];
            if (current != null) {
                current.pause();
            }
            this._paused = true;
            this.raisePropertyChanged('isPlaying');
        }
    },
    
    play : function() {
        /// <summary>
        /// Play the sequence of animations from the beginning or where it was left off when paused
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>play</code> on its parent instead
        /// </remarks>

        var animations = this.get_animations();
        if (!this._playing) {
            this._playing = true;
            if (this._paused) {
                this._paused = false;
                var current = animations[this._index];
                if (current != null) {
                    current.play();
                    this.raisePropertyChanged('isPlaying');
                }
            } else {
                this.onStart();
                // Reset the index and attach the handler to the first
                this._index = 0;
                var first = animations[this._index];
                if (first) {
                    first.add_ended(this._handler);
                    first.play();
                    this.raisePropertyChanged('isPlaying');
                } else {
                    this.stop();
                }
            }
        }
    },
    
    onStart : function() {
        /// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time
        /// </summary>
        /// <returns />
        $TWA.SequenceAnimation.callBaseMethod(this, 'onStart');
        this._remainingIterations = this._iterations - 1;
        
        // Create the handler we attach to each animation as it plays to determine when we've finished with it
        if (!this._handler) {
            this._handler = Function.createDelegate(this, this._onEndAnimation);
        }
    },
    
    _onEndAnimation : function() {
    	/// <summary>
        /// Wait for the end of each animation, and then continue by playing the other animations remaining
        /// in the sequence.  Stop when it reaches the last animation and there are no remaining iterations.
    	/// </summary>
    	/// <returns />

        // Remove the handler from the current animation
        var animations = this.get_animations();
        var current = animations[this._index++];
        if (current) {
            current.remove_ended(this._handler);
        }
        
        // Keep running animations and stop when we're out
        if (this._index < animations.length) {
            var next = animations[this._index];
            next.add_ended(this._handler);
            next.play();
        } else if (this._remainingIterations >= 1 || this._iterations <= 0) {
            this._remainingIterations--;
            this._index = 0;
            var first = animations[0];
            first.add_ended(this._handler);
            first.play();
        } else {
            this.stop();
        }
    },
    
    onStep : function(percentage) {
        /// <summary>
        /// Raises an invalid operation exception because this will only be called if a <code>SequenceAnimation</code>
        /// has been nested inside an <see cref="Telerik.Web.Animation.ParallelAnimation" /> (or a derived type).
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns />
        throw Error.invalidOperation("CANNOT NEST");
    },
    
    onEnd : function() {
        /// <summary>
        /// The <code>onEnd</code> method is called just after the animation is played each time.
        /// </summary>
        /// <returns />
        this._remainingIterations = 0;
        $TWA.SequenceAnimation.callBaseMethod(this, 'onEnd');
    },
    
    get_isActive : function() {
    	/// <value type="Boolean">
        /// <code>true</code> if animation is active, <code>false</code> if not.
        /// </value>
        return true;
    },
    
    get_isPlaying : function() {
    	/// <value type="Boolean">
        /// <code>true</code> if animation is playing, <code>false</code> if not.
        /// </value>
        return this._playing && !this._paused;
    },
    
    get_iterations : function() {
        /// <value type="Number" integer="true">
        /// Number of times to repeatedly play the sequence.  If zero or less iterations are specified, the sequence
        /// will repeat forever.  The default value is 1 iteration.
        /// </value>
        return this._iterations;
    },
    set_iterations : function(value) {
        value = this._getInteger(value);
        if (this._iterations != value) {
            this._iterations = value;
            this.raisePropertyChanged('iterations');
        }
    },
    
    get_isInfinite : function() {
    	/// <value type="Boolean">
        /// <code>true</code> if this animation will repeat forever, <code>false</code> otherwise.
    	/// </value>
        return this._iterations <= 0;
    }
}
$TWA.SequenceAnimation.registerClass('Telerik.Web.Animation.SequenceAnimation', $TWA.ParentAnimation);
$TWA.registerAnimation('sequence', $TWA.SequenceAnimation);

$TWA.PulseAnimation = function(target, duration, fps, iterations, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The PulseAnimation fades an element in and our repeatedly to create a pulsating
    /// effect.  The iterations determines how many pulses there will be (which defaults
    /// to three, but it will repeat infinitely if given zero or less).  The duration
    /// property defines the duration of each fade in or fade out, not the duration of
    /// the animation as a whole.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="iterations" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of times to repeatedly play the sequence.  If zero or less iterations are specified, the sequence
    /// will repeat forever.  The default value is 1 iteration.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>Pulse</animation>
    $TWA.PulseAnimation.initializeBase(this, [target, duration, fps, null, ((iterations !== undefined) ? iterations : 3)]);

    // Create the FadeOutAnimation
    this._out = new $TWA.FadeOutAnimation(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE);
    this.add(this._out);
    
    // Create the FadeInAnimation
    this._in = new $TWA.FadeInAnimation(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE);
    this.add(this._in);
}
$TWA.PulseAnimation.prototype = {
   
    get_minimumOpacity : function() {
        /// <value type="Number">
        /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
        /// </value>
        return this._out.get_minimumOpacity();
    },
    set_minimumOpacity : function(value) {
        value = this._getFloat(value);
        this._out.set_minimumOpacity(value);
        this._in.set_minimumOpacity(value);
        this.raisePropertyChanged('minimumOpacity');
    },
    
    get_maximumOpacity : function() {
        /// <value type="Number">
        /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
        /// </value>
        return this._out.get_maximumOpacity();
    },
    set_maximumOpacity : function(value) {
        value = this._getFloat(value);
        this._out.set_maximumOpacity(value);
        this._in.set_maximumOpacity(value);
        this.raisePropertyChanged('maximumOpacity');
    },
    
    get_forceLayoutInIE : function() {
        /// <value type="Boolean">
        /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
        /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
        /// This is obviously ignored when working in other browsers.
        /// </value>
        return this._out.get_forceLayoutInIE();
    },
    set_forceLayoutInIE : function(value) {
        value = this._getBoolean(value);
        this._out.set_forceLayoutInIE(value);
        this._in.set_forceLayoutInIE(value);
        this.raisePropertyChanged('forceLayoutInIE');
    },
    
    set_duration : function(value) {
        /// <value type="Number">
        /// Override the <code>duration</code> property
        /// </value>
        value = this._getFloat(value);
        $TWA.PulseAnimation.callBaseMethod(this, 'set_duration', [value]);
        this._in.set_duration(value);
        this._out.set_duration(value);
    },
    
    set_fps : function(value) {
        /// <value type="Number" integer="true">
        /// Override the <code>fps</code> property
        /// </value>
        value = this._getInteger(value);
        $TWA.PulseAnimation.callBaseMethod(this, 'set_fps', [value]);
        this._in.set_fps(value);
        this._out.set_fps(value);
    }
    
}
$TWA.PulseAnimation.registerClass('Telerik.Web.Animation.PulseAnimation', $TWA.SequenceAnimation);
$TWA.registerAnimation('pulse', $TWA.PulseAnimation);;//---------------------------------------- ANIMATIONS --------------------------------------------------//
//Controls to benefit are - tooltip, window, dock, colorpicker
//Animations combine two animations [open/close] using the same set of data.
//Properties that are needed to provide information show and hide animations
//startBounds, endBounds, Telerik.Web.UI.ToolTipPosition position!-> will probably need to be made common for all controls.

//Window can be moved from original location, their opener can be moved, so calculating exact values to use can requier more actions to get the correct values
//Close animations assume the animated element's size and position
Type.registerNamespace('Telerik.Web.UI.Animations');

Telerik.Web.UI.Animations.ShowHideAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    ///<exclude/>    
    this.controller = controller;
        
    this._duration = (duration !=  null) ? duration : .3;
    this._fps = (fps !=  null) ? fps : 50;
    this._frames = duration * fps;		    
    this._position = null != position ? position : 32;//Telerik.Web.UI.ToolTipPosition.BottomCenter;
        
    this._animatedElement = animatedElement;//The element to be animated    
    this._sourceElement = sourceElement;    //The source element that initiates the animation can be used to obtain start/end bounds
    
    //Start bounds are optional and not set on some animations.If a sourceElement exists, it has higher priority than the startBounds
    this._startBounds = null;
    //End bounds are mandatory for animations that perform resizing, and must be set in onStart handler
    this._endBounds = null;
    
    //Created by classes that inherit the base class
    this._showAnimation = null;
    this._hideAnimation = null;
}


Telerik.Web.UI.Animations.ShowHideAnimation.prototype = 
{   
    //## region protected methods##
    
    //Returns the horizontal position of animated element relative to the sourceElement
    _getHorizontalPosition : function()
    {
      return parseInt((this._position + "").charAt(1));      
    },
    
    //Returns the vertical position of animated element relative to the sourceElement
    _getVerticalPosition : function()
    {
      return parseInt((this._position + "").charAt(0));      
    },
    
    //Use it to set proper values to the animation. 
    //if startBounds are set, use them as initial size/position values. Else - if _sourceElement is set - use its bounds for initial values
    _onBeforeShow : function()
    {    
        /* Override in subclass */
    },
            
    _onBeforeHide : function()
    {    
        /* Override in subclass */
    },
        
    _onAfterShow : function()
    {   
        /* Override in subclass */ 
    },
    
    _onAfterHide : function()
    {   
        /* Override in subclass */ 
    },
                                      
    //## region Public API ##//
    onShowStart : function()
    {
        /* Override when initializing */
    },
            
    onHideStart : function()
    {
        /* Override when initializing */
    },
    
    onShowEnd : function()
    {
       /* Override when initializing */
    },
    onHideEnd : function()
    {
       /* Override when initializing */
    },
    
    play : function(isHideSequence)
    {
        var animation = (true == isHideSequence) ? this._hideAnimation : this._showAnimation;
        
        if (animation)
        {
            //Stop running animation [if any]
            this.stop();
            
            if (!animation.__isTelerikModified)
            {
                var _this = this;
                animation.__isTelerikModified = true;
                
                //Attach to onStart and prevent onStart from being replaced multiple times on each animation play
                var oldStart = animation.onStart;
                animation.onStart = function()
                {                            
                    //Call current onStart to allow for setting configuration values
                    if (isHideSequence) _this.onHideStart();
                    else _this.onShowStart();
              
                    //Use the values set in the onStart event handler to finish the initialization process
                    if (true == isHideSequence)
                    {
                        _this._onBeforeHide();
                    }
                    else
                    {                                  
                        _this._onBeforeShow();          
                    }
                    
                    //Important: Call original onStart to perform initialiation, or else it would not work
                    //! The invocation must be here - as the last action!
                    if (oldStart) oldStart.call(this);
                };
                
                //Attach to onEnd and prevent onEnd from being replaced multiple times on each animation play
                var oldEnd = animation.onEnd;
                animation.onEnd = function()
                {                        
                    if (oldEnd) oldEnd.call(this);
                    if (_this.onEnd) _this.onEnd(isHideSequence);
                    
                    //Cleanup
                    if (true == isHideSequence)
                    {
                        _this._onAfterHide();
                    }
                    else
                    {                                  
                        _this._onAfterShow();          
                    }
                    
                    //Run finalizing code
                    if (isHideSequence) _this.onHideEnd();
                    else _this.onShowEnd();           
                }            
            }
            
            //NEW: Reset the duration
            animation.set_duration(this._duration);
          
            //Play animation            
            animation.play();    
        }
                
        this._runningAnimation = animation;                
    },
    
    set_startBounds : function(bounds)
    {
        this._startBounds = bounds;
    },

    set_endBounds : function(bounds)
    {
        this._endBounds = bounds;
    },
        
    dispose : function()
    {
        this.stop();
        if (this._showAnimation) this._showAnimation.dispose();
        if (this._hideAnimation) this._hideAnimation.dispose();
    },
    
    stop : function()
    {
        if (this._runningAnimation)
        {
            this._runningAnimation.stop();
            this._runningAnimation = null;
        }
    },
    
    //NEW: Pause functionality
    pause : function()
    {
        if (this._runningAnimation)
        {
            this._runningAnimation.pause();
            
        }
    },
    
    resume : function()
    {
        if (this._runningAnimation)
        {
            this._runningAnimation.play();
            
        }
    },
    
    //NEW: API methods    
    set_position : function(value)
    {
        this._position = value;
    },
    
    set_duration : function(value)
    {
        this._duration = value;        
        if (this._showAnimation) this._showAnimation.set_duration(this._duration);
        if (this._hideAnimation) this._hideAnimation.set_duration(this._duration);
    
    },
    
    get_startBounds : function()
    {
        return this._startBounds;
    },
    
    get_endBounds : function()
    {
        return this._endBounds;
    }
        
}
Telerik.Web.UI.Animations.ShowHideAnimation.registerClass('Telerik.Web.UI.Animations.ShowHideAnimation', null);


/****************************************************************************************************************
 *                                                  Resize animation 
 ****************************************************************************************************************/
Telerik.Web.UI.Animations.ResizeAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    Telerik.Web.UI.Animations.ResizeAnimation.initializeBase(this, [controller, duration, fps, animatedElement, position, sourceElement]);    
    
    var duration = this._duration;
    var fps = this._fps;
    var target =  this._animatedElement; 
    
    //Fake values for easier initialiation    
    //var width = 100, height = 100, startY = 0, endY = 100, startX = 0, endX = 100;
    var width, height, startY, endY, startX, endX;
    
	//_showAnimation			
    var resizeAnimation = new Telerik.Web.Animation.ResizeAnimation(target, duration, fps, width, height, 'px');    
    var leftAnimation = new Telerik.Web.Animation.LengthAnimation(target, duration, fps, "style", "left", startX, endX, "px");
    var topAnimation = new Telerik.Web.Animation.LengthAnimation(target, duration, fps, "style", "top", startY, endY, "px");							        
    var fadeAnimation = new Telerik.Web.Animation.FadeInAnimation(target, duration, fps, .3, 1, false);	    						

    this._showAnimation = new Telerik.Web.Animation.ParallelAnimation(target, duration, fps, 		    
                          [resizeAnimation, leftAnimation, topAnimation, fadeAnimation]
                        );                                   
    
    //_hideAnimation
    this._hideAnimation = new Telerik.Web.Animation.FadeInAnimation(this._animatedElement, this._duration, this._fps, 1, 0, false);	               	    
};

Telerik.Web.UI.Animations.ResizeAnimation.prototype = 
{    
    //Break into pieces, some of which will be overridden in ineriting animations
    _configureAnimatedElement : function()
    {
        var target = this._animatedElement;        
        target.style.overflow = "hidden";
        target.style.display = "";
        target.style.visibility = "visible";     
        target.style.width = "1px";
        target.style.height = "1px";        
    },
              
    _configureAnimation : function(animValues)
    {        
        //Configure the animations before you run the parent animation
		var anims = this._showAnimation.get_animations();
		var resizeAnim = anims[0];
		resizeAnim.set_width(animValues.width);
		resizeAnim.set_height(animValues.height);

        var leftAnim = anims[1];     
        leftAnim.set_startValue(animValues.startX);
        leftAnim.set_endValue(animValues.endX);
   
        var topAnim = anims[2];
        topAnim.set_startValue(animValues.startY);
        topAnim.set_endValue(animValues.endY);
    },
        
        
    _getStartBounds : function()
    {
        var startBounds = null;
        if (this._startBounds) startBounds = this._startBounds;
		else if (this._sourceElement) startBounds = $telerik.getBounds(this._sourceElement);
		else startBounds = new Sys.UI.Bounds(1,1,1,1); 	
		return startBounds;
    },
    
    _getEndBounds : function()
    {
        return this._endBounds;
    },
    
    //Can be overridden in subclasses
	_modifyAnimationValues : function(animValues)
    {      			
		//Additional smooth out - if the source element is smaller than tooltip, use the source element as starting size
		var target = this._animatedElement;
		var startBounds = this._getStartBounds();
			                   		
		if(startBounds.width < animValues.width) 
		{
		    animValues.startX = startBounds.x;
		    target.style.width = startBounds.width;
		}
		
		if(startBounds.height < animValues.height) 
		{
		    //Only if position is in center! Other than that -> if position top - start from top, position bottom start from bottom
		    animValues.startY = startBounds.y;				    
            target.style.height = startBounds.height;
		}
	},
		
    _setHorizontalValues : function(animValues)
    {
        var horSide = this._getHorizontalPosition();
        var popupBounds = this._getEndBounds();
        switch(horSide)
        {
            //Center
            case 2:                            
                animValues.startX = popupBounds.x + Math.floor(popupBounds.width/2);  
                animValues.endX = popupBounds.x;
                break;
            //Right
            case 3:              
                animValues.startX = popupBounds.x;
                animValues.endX = popupBounds.x;
                break;                
            //Left            
            case 1:
                animValues.startX = popupBounds.x + popupBounds.width;  
                animValues.endX = popupBounds.x;          
        }
    },
    
    _setVerticalValues : function(animValues)
    {
        var verSide = this._getVerticalPosition();                
        var popupBounds = this._getEndBounds();
         //Compute the vertical coordinate
        switch(verSide)
        {
            //Middle
            case 2:                                               
               animValues.startY = popupBounds.y + Math.floor(popupBounds.height/2);
               animValues.endY = popupBounds.y;
               break;
            //Top    
            case 1:               
               animValues.startY = popupBounds.y + popupBounds.height;
               animValues.endY = popupBounds.y;                
                break;
            //Bottom
            case 3:
               animValues.startY = popupBounds.y;
               animValues.endY = popupBounds.y;             
        }
    },
    
    _setSizeValues : function(animValues)
    {
        var popupBounds = this._endBounds;
        animValues["width"] = popupBounds.width;
		animValues["height"] = popupBounds.height;
    },
    
    //Inherit from parent class
    _onBeforeShow : function()
    {    
		//Create animation object
		var animValues = {};				
		this._setHorizontalValues(animValues);
		this._setVerticalValues(animValues);
		this._setSizeValues(animValues);
	
	    //Configure the element to be animated
		this._configureAnimatedElement();
						                
		//Overridden method - allow for value and target element modification
		this._modifyAnimationValues(animValues);
        //alert("Start x=" + animValues.startX + " , y = " + animValues.startY);
		//Configure the child animation objects using the supplied values
		this._configureAnimation(animValues);
    },
    
    _onAfterShow : function()
    {           
       this._animatedElement.style.overflow = "";        
       //Remove trasnparency filter(s) to make callout visible! Bug in IE         
       this._animatedElement.style.filter = "";               
    }            
}

Telerik.Web.UI.Animations.ResizeAnimation.registerClass('Telerik.Web.UI.Animations.ResizeAnimation', Telerik.Web.UI.Animations.ShowHideAnimation);


/****************************************************************************************************************
 *                                                  Slide animation 
 ****************************************************************************************************************/
 Telerik.Web.UI.Animations.SlideAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    Telerik.Web.UI.Animations.SlideAnimation.initializeBase(this, [controller, duration, fps, animatedElement, position, sourceElement]);            
};

Telerik.Web.UI.Animations.SlideAnimation.prototype = 
{         
    _modifyAnimationValues : function(animValues)
    {      					
	},
	
	 _configureAnimatedElement : function()
    {
        var target = this._animatedElement;        
        target.style.overflow = "hidden";
        target.style.display = "";
        target.style.visibility = "visible";     
        
        var verSide = this._getVerticalPosition();        
        if (verSide == 2)
        {
           target.style.width = "1px";
        }
        else target.style.height = "1px"; 
    },
		
   _setHorizontalValues : function(animValues)
    {
        var horSide = this._getHorizontalPosition();
        var popupBounds = this._getEndBounds();
        switch(horSide)
        {
            //Center
            case 2:                            
                animValues.startX = popupBounds.x;// + Math.floor(popupBounds.width/2);  
                animValues.endX = popupBounds.x;
                break;
            //Right
            case 3:              
                animValues.startX = popupBounds.x;
                animValues.endX = popupBounds.x;
                break;                
            //Left            
            case 1:
                var startX = popupBounds.x;
                
                if (2 == this._getVerticalPosition())  //Only if vertical pos is middle!
                        startX += popupBounds.width;
                
                animValues.startX = startX;
                                    
                animValues.endX = popupBounds.x;          
        }
    },
    
    _setVerticalValues : function(animValues)
    {
        var verSide = this._getVerticalPosition();                
        var popupBounds = this._getEndBounds();
         //Compute the vertical coordinate
        switch(verSide)
        {
            //Middle
            case 2:                                               
               animValues.startY = popupBounds.y;// + Math.floor(popupBounds.height/2);
               animValues.endY = popupBounds.y;
               break;
            //Top    
            case 1:               
               animValues.startY = popupBounds.y + popupBounds.height;
               animValues.endY = popupBounds.y;                
                break;
            //Bottom
            case 3:
               animValues.startY = popupBounds.y;
               animValues.endY = popupBounds.y;             
        }
    }
}

Telerik.Web.UI.Animations.SlideAnimation.registerClass('Telerik.Web.UI.Animations.SlideAnimation', Telerik.Web.UI.Animations.ResizeAnimation);
 
/****************************************************************************************************************
*                                                  FlyIn animation 
****************************************************************************************************************/
Telerik.Web.UI.Animations.FlyInAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    Telerik.Web.UI.Animations.FlyInAnimation.initializeBase(this, [controller, duration, fps, animatedElement, position, sourceElement]);    
};

Telerik.Web.UI.Animations.FlyInAnimation.prototype = 
{         
	_modifyAnimationValues : function(animValues)
    {      					
	},
		
    _setHorizontalValues : function(animValues)
    {    
        var horSide = this._getHorizontalPosition();
        var popupBounds = this._getEndBounds();
        
        var browserBounds = $telerik.getClientBounds();
        
        switch(horSide)
        {
            //Center
            case 2:                            
                animValues.startX = popupBounds.x;
                animValues.endX = popupBounds.x;
                break;
            //Right
            case 3:              
                animValues.startX = browserBounds.width;
                animValues.endX =  popupBounds.x;
                break;                
            //Left            
            case 1:
                animValues.startX = browserBounds.x;  
                animValues.endX = popupBounds.x;          
        }
                
    },
    
    _setVerticalValues : function(animValues)
    {
        var verSide = this._getVerticalPosition();                
        var popupBounds = this._getEndBounds();
        var browserBounds = $telerik.getClientBounds();
        
         //Compute the vertical coordinate
        switch(verSide)
        {
            //Middle
            case 2:                                               
               animValues.startY = popupBounds.y;
               animValues.endY = popupBounds.y;
               break;
            //Top    
            case 1:               
               animValues.startY = browserBounds.y - popupBounds.height;
               animValues.endY = popupBounds.y;                
                break;
            //Bottom
            case 3:
               animValues.startY = browserBounds.height;
               animValues.endY = popupBounds.y;             
        }                
    }
}

Telerik.Web.UI.Animations.FlyInAnimation.registerClass('Telerik.Web.UI.Animations.FlyInAnimation', Telerik.Web.UI.Animations.ResizeAnimation);
 
  
/****************************************************************************************************************
*                                                  Fade animation 
****************************************************************************************************************/
Telerik.Web.UI.Animations.FadeAnimation = function(controller, duration, fps, animatedElement) 
{                 
    Telerik.Web.UI.Animations.FadeAnimation.initializeBase(this, [controller, duration, fps, animatedElement]);    
    
    this._showAnimation = new Telerik.Web.Animation.FadeInAnimation(this._animatedElement, this._duration, this._fps, .5, 1, false);	      
    this._hideAnimation = new Telerik.Web.Animation.FadeInAnimation(this._animatedElement, this._duration, this._fps, .9, 0, false);	               
};

Telerik.Web.UI.Animations.FadeAnimation.prototype = 
{      
    _onAfterShow : function()
    {                            
        //Remove trasnparency filter(s) to make callout visible! Bug in IE         
        this._animatedElement.style.filter = "";       
    }       
}

Telerik.Web.UI.Animations.FadeAnimation.registerClass('Telerik.Web.UI.Animations.FadeAnimation', Telerik.Web.UI.Animations.ShowHideAnimation);

/****************************************************************************************************************
 *                                                  SimpleResize animation 
 ****************************************************************************************************************/
 Telerik.Web.UI.Animations.SimpleResizeAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    Telerik.Web.UI.Animations.SimpleResizeAnimation.initializeBase(this, [controller, duration, fps, animatedElement, position, sourceElement]);            
};

Telerik.Web.UI.Animations.SimpleResizeAnimation.prototype = 
{         
    _modifyAnimationValues : function(animValues)
    {      					
	},
	
	_configureAnimation : function(animValues)
    {        
        Telerik.Web.UI.Animations.SimpleResizeAnimation.callBaseMethod(this, '_configureAnimation', [animValues]);

		var anims = this._showAnimation.get_animations();
		var resizeAnim = anims[0];
		
		var startBounds = this._getStartBounds();
		// Modify the onStart of the resize animation as it sets as start(end)Width(Height) the offsetWidth(Height).
		// This is not correct in case the animated element has borders.
		resizeAnim.onStart = function()
		{
		     $TWA.ResizeAnimation.callBaseMethod(this, 'onStart');
        
            // Set the start and end values of the animations by getting
            // the element's current width and height
            var element = this.get_target();
            this._horizontalAnimation.set_startValue(startBounds.width);
            this._verticalAnimation.set_startValue(startBounds.height);
            this._horizontalAnimation.set_endValue((this._width !== null && this._width !== undefined) ?
                this._width : element.offsetWidth);
            this._verticalAnimation.set_endValue((this._height !== null && this._height !== undefined) ?
                this._height : element.offsetHeight);
		};
    },
	
	_configureAnimatedElement : function()
    {
        var target = this._animatedElement;        
        target.style.overflow = "hidden";
        target.style.display = "";
        target.style.visibility = "visible";  
    },
		
   _setHorizontalValues : function(animValues)
    {
        var horSide = this._getHorizontalPosition();
        var startBounds = this._getStartBounds();
        var endBound = this._getEndBounds();
                          
        animValues.startX = startBounds.x;
        animValues.endX = endBound.x;
    },
    
    _setVerticalValues : function(animValues)
    {
        var verSide = this._getVerticalPosition();                
        var startBounds = this._getStartBounds();
        var endBound = this._getEndBounds();
                                            
       animValues.startY = startBounds.y;
       animValues.endY = endBound.y;
    }
}

Telerik.Web.UI.Animations.SimpleResizeAnimation.registerClass('Telerik.Web.UI.Animations.SimpleResizeAnimation', Telerik.Web.UI.Animations.ResizeAnimation);
 
 

 
Telerik.Web.UI.Animations.ScrollAnimation = function(controller, duration, fps, animatedElement, position, sourceElement) 
{                 
    Telerik.Web.UI.Animations.ScrollAnimation.initializeBase(this, [controller, duration, fps, animatedElement, position, sourceElement]);            
    
    //HACK: Remove the fade animation - after the FUTURES we will rework the TelerikAnimations!
    var anims = this._showAnimation.get_animations();    
    if (anims[3])
    {        
        this._showAnimation.remove(anims[3]);
    }
    
};

Telerik.Web.UI.Animations.ScrollAnimation.prototype = 
{         
    //Override to empty
    _modifyAnimationValues : function(animValues)
    {      					
	},
	
	//Override to empty
	 _configureAnimatedElement : function()
    {
         //Called too late, so do not set anything to the element here         
    },
		
   _setHorizontalValues : function(animValues)
    {                  
        var startBounds = this._getStartBounds();                
        var popupBounds = this._getEndBounds();

        var horSide = this._getHorizontalPosition();                               
        switch(horSide)
        {
            //Center - currently not used, but with two dimensions it will!
            case 2:                            
                animValues.startX = startBounds.x;
                animValues.endX = startBounds.x;
                break;
            
            //Right
            case 3:              
                animValues.startX = startBounds.x;
                animValues.endX = startBounds.x + popupBounds.x;
                break;                
            //Left            
            case 1:                                                 
                animValues.startX = startBounds.x;                                    
                animValues.endX = startBounds.x - popupBounds.x;          
        }
        //alert(horSide +  " Start x=" + animValues.startX + " " +   animValues.endX);      
    },
    
    _setVerticalValues : function(animValues)
    {
        var verSide = this._getVerticalPosition();                
        
        var startBounds = this._getStartBounds();   
        var popupBounds = this._getEndBounds();
         //Compute the vertical coordinate
        switch(verSide)
        {
            //Middle
            case 2:                                               
               animValues.startY = popupBounds.y;
               animValues.endY = popupBounds.y;
               break;
            //Top    
            case 1:               
               animValues.startY = startBounds.y;
               animValues.endY = startBounds.y - popupBounds.y;
               break;
            //Bottom
            case 3:
               animValues.startY = startBounds.y;
               animValues.endY = startBounds.y + popupBounds.y;             
        }
        
        //alert(verSide + " Vertical values =" + animValues.startY + " " +   animValues.endY);              
    }
};

Telerik.Web.UI.Animations.ScrollAnimation.registerClass('Telerik.Web.UI.Animations.ScrollAnimation', Telerik.Web.UI.Animations.ResizeAnimation);;
/* END Telerik.Web.UI.Common.Animation.AnimationScripts.js */
/* START Telerik.Web.UI.Common.Navigation.NavigationScripts.js */
Type.registerNamespace("Telerik.Web.UI");

// ---------- AnimationType Enum ----------
Telerik.Web.UI.AnimationType = function () { };

Telerik.Web.UI.AnimationType.prototype =
{
	None: 0,
	Linear: 1,

	InQuad: 2,
	OutQuad: 3,
	InOutQuad: 4,

	InCubic: 5,
	OutCubic: 6,
	InOutCubic: 7,

	InQuart: 8,
	OutQuart: 9,
	InOutQuart: 10,

	InQuint: 11,
	OutQuint: 12,
	InOutQuint: 13,

	InSine: 14,
	OutSine: 15,
	InOutSine: 16,

	InExpo: 17,
	OutExpo: 18,
	InOutExpo: 19,

	InBack: 20,
	OutBack: 21,
	InOutBack: 22,

	InBounce: 23,
	OutBounce: 24,
	InOutBounce: 25,

	InElastic: 26,
	OutElastic: 27,
	InOutElastic: 28
}

Telerik.Web.UI.AnimationType.registerEnum("Telerik.Web.UI.AnimationType");

Telerik.Web.UI.AnimationFunctions = function () { };

Telerik.Web.UI.AnimationFunctions.CalculateAnimationPoints = function(animationSettings, startPosition, finalPosition, fps)
{
	if (startPosition == finalPosition) 
	{
		return [finalPosition + "px"];
	}
	
	var duration = animationSettings.get_duration() / 1000;
	var totalFrames = Math.round((duration) * fps);
	var animationFunction = Telerik.Web.UI.AnimationFunctions[animationSettings.get_type()];
	
	var points = new Array();
	var distance = Math.max(startPosition, finalPosition) - Math.min(startPosition, finalPosition);
	
	var direction = startPosition < finalPosition ? 1 : -1;
	var lastValue = 0;
	points[0] = startPosition + "px";
	for (var frameIx = 0; frameIx < totalFrames; frameIx++) 
	{
		var currentValue = animationFunction(frameIx / fps, 0, distance, duration);
		
		if (frameIx > 0) 
		{
			var lastPoint = parseInt(points[frameIx - 1]);
			var delta = direction * (Math.round(currentValue) - Math.round(lastValue));
			points[frameIx] = (lastPoint + delta) + "px";
		}
		
		lastValue = currentValue;
	}
	
	// Not all animation functions end the sequence at the exact desired position.
	points[totalFrames - 1] = finalPosition + "px";
	
	return points;
}

/*
Easing Equations v1.5
Open source under the BSD License.

Copyright � 2001 Robert Penner
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// simple linear tweening - no easing
// t: current time, b: beginning value, c: change in value, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.Linear] = function (t, b, c, d) {
	return c*t/d + b;
};


 ///////////// QUADRATIC EASING: t^2 ///////////////////

// quadratic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be in frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuad] = function (t, b, c, d) {
	return c*(t/=d)*t + b;
};

// quadratic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuad] = function (t, b, c, d) {
	return -c *(t/=d)*(t-2) + b;
};

// quadratic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuad] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};


 ///////////// CUBIC EASING: t^3 ///////////////////////

// cubic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InCubic] = function (t, b, c, d) {
	return c*(t/=d)*t*t + b;
};

// cubic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutCubic] = function (t, b, c, d) {
	return c*((t=t/d-1)*t*t + 1) + b;
};

// cubic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutCubic] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t + b;
	return c/2*((t-=2)*t*t + 2) + b;
};


 ///////////// QUARTIC EASING: t^4 /////////////////////

// quartic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuart] = function (t, b, c, d) {
	return c*(t/=d)*t*t*t + b;
};

// quartic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuart] = function (t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

// quartic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuart] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
	return -c/2 * ((t-=2)*t*t*t - 2) + b;
};


 ///////////// QUINTIC EASING: t^5  ////////////////////

// quintic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuint] = function (t, b, c, d) {
	return c*(t/=d)*t*t*t*t + b;
};

// quintic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuint] = function (t, b, c, d) {
	return c*((t=t/d-1)*t*t*t*t + 1) + b;
};

// quintic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuint] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
	return c/2*((t-=2)*t*t*t*t + 2) + b;
};



 ///////////// SINUSOIDAL EASING: sin(t) ///////////////

// sinusoidal easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InSine] = function (t, b, c, d) {
	return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
};

// sinusoidal easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutSine] = function (t, b, c, d) {
	return c * Math.sin(t/d * (Math.PI/2)) + b;
};

// sinusoidal easing in/out - accelerating until halfway, then decelerating
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutSine] = function (t, b, c, d) {
	return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
};


 ///////////// EXPONENTIAL EASING: 2^t /////////////////

// exponential easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InExpo] = function (t, b, c, d) {
	return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
};

// exponential easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutExpo] = function (t, b, c, d) {
	return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};

// exponential easing in/out - accelerating until halfway, then decelerating
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutExpo] = function (t, b, c, d) {
	if (t==0) return b;
	if (t==d) return b+c;
	if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
	return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
};


 /////////// CIRCULAR EASING: sqrt(1-t^2) //////////////

// circular easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InCirc] = function (t, b, c, d) {
	return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
};

// circular easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutCirc] = function (t, b, c, d) {
	return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
};

// circular easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutCirc] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
	return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
};


 /////////// ELASTIC EASING: exponentially decaying sine wave  //////////////

// t: current time, b: beginning value, c: change in value, d: duration, a: amplitude (optional), p: period (optional)
// t and d can be in frames or seconds/milliseconds

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
};

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
};

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
};


 /////////// BACK EASING: overshooting cubic easing: (s+1)*t^3 - s*t^2  //////////////

// back easing in - backtracking slightly, then reversing direction and moving to target
// t: current time, b: beginning value, c: change in value, d: duration, s: overshoot amount (optional)
// t and d can be in frames or seconds/milliseconds
// s controls the amount of overshoot: higher s means greater overshoot
// s has a default value of 1.70158, which produces an overshoot of 10 percent
// s==0 produces cubic easing with no overshoot
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158;
	return c*(t/=d)*t*((s+1)*t - s) + b;
};

// back easing out - moving towards target, overshooting it slightly, then reversing and coming back to target
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158;
	return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
};

// back easing in/out - backtracking slightly, then reversing direction and moving to target,
// then overshooting target, reversing, and finally coming back to target
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};


 /////////// BOUNCE EASING: exponentially decaying parabolic bounce  //////////////

// bounce easing in
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBounce] = function (t, b, c, d) {
	return c - Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] (d-t, 0, c, d) + b;
};

// bounce easing out
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] = function (t, b, c, d) {
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};

// bounce easing in/out
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutBounce] = function (t, b, c, d) {
	if (t < d/2) return Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBounce] (t*2, 0, c, d) * .5 + b;
	return Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] (t*2-d, 0, c, d) * .5 + c*.5 + b;
};

Telerik.Web.UI.AnimationFunctions.registerClass('Telerik.Web.UI.AnimationFunctions');;Type.registerNamespace("Telerik.Web.UI");

// ---------- AnimationSettings Class ----------
Telerik.Web.UI.AnimationSettings = function(serializedAnimationSettings)
{
	this._type = Telerik.Web.UI.AnimationType.OutQuart;
	this._duration = 300;
	
	if (typeof(serializedAnimationSettings.type) != "undefined")
	{
		this._type = serializedAnimationSettings.type;
	}
	
	if (typeof(serializedAnimationSettings.duration) != "undefined")
	{
		this._duration = serializedAnimationSettings.duration;
	}
}

Telerik.Web.UI.AnimationSettings.prototype =
{
	get_type : function ()
	{
		return this._type;
	},
	
	set_type : function(value)
	{
		this._type = value;
	},

	get_duration : function ()
	{
		return this._duration;
	},
	
	set_duration : function(value)
	{
		this._duration = value;
	}
}

Telerik.Web.UI.AnimationSettings.registerClass('Telerik.Web.UI.AnimationSettings');;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.AttributeCollection = function (owner)
{
	this._owner = owner;
	this._data = {};
	this._keys = [];
}

Telerik.Web.UI.AttributeCollection.prototype = 
{
	getAttribute : function (key)
	{
		return this._data[key];
	},
	
	setAttribute : function (key, value)
	{
		this._add(key, value);
		
		var attributeEntry = {};
		attributeEntry[key] = value;

		this._owner._notifyPropertyChanged("attributes", attributeEntry);
	},
	
	_add : function (key, value)
	{
		if (Array.indexOf(this._keys, key) < 0)
			Array.add(this._keys, key);
			
		this._data[key] = value;
	},
	
	removeAttribute : function (key)
	{
		Array.remove(this._keys, key);
		
		delete this._data[key];
	},
	
	_load : function (json)
	{
		for (var key in json)
			this._add(key, json[key]);
	},
	
	get_count : function ()
	{
		return this._keys.length;
	}
}

Telerik.Web.UI.AttributeCollection.registerClass('Telerik.Web.UI.AttributeCollection');;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ChangeLog = function ()
{
	this._opCodeInsert = 1;
	this._opCodeDelete = 2;
	this._opCodeClear = 3;
	this._opCodePropertyChanged = 4;
	
	this._logEntries = null;
}

Telerik.Web.UI.ChangeLog.prototype =
{
	initialize : function ()
	{
		this._logEntries = [];
		this._serializedEntries = null;
	},
	
	logInsert : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeInsert;
		logEntry.Index = item._getHierarchicalIndex();
		logEntry.Data = item._getData();
		
		Array.add(this._logEntries, logEntry);
	},
	
	logDelete : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeDelete;
		logEntry.Index = item._getHierarchicalIndex();
		
		Array.add(this._logEntries, logEntry);
	},
	
	logClear : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeClear;
		
		if (item._getHierarchicalIndex)
		{
			logEntry.Index = item._getHierarchicalIndex();
		}
		
		Array.add(this._logEntries, logEntry);
	},
	
	logPropertyChanged : function (item, propertyName, propertyValue)
	{
		var logEntry = {};
		logEntry.Type = this._opCodePropertyChanged;
		logEntry.Index = item._getHierarchicalIndex();
		logEntry.Data = {};
		logEntry.Data[propertyName] = propertyValue;
		
		Array.add(this._logEntries, logEntry);
	},
	
	serialize : function ()
	{	
		if(this._logEntries.length == 0)
		{
			if(this._serializedEntries == null)
			{
				return "[]";
			}

			return this._serializedEntries;
		}
	
		var newEntries = Sys.Serialization.JavaScriptSerializer.serialize(this._logEntries);		
	
		if(this._serializedEntries == null)
		{
			this._serializedEntries = newEntries;
		}
		else
		{
			this._serializedEntries = this._serializedEntries.substring(0, this._serializedEntries.length - 1) + ',' + newEntries.substring(1);
		}
		
		this._logEntries = [];
		
		return this._serializedEntries;
	}	
}

Telerik.Web.UI.ChangeLog.registerClass("Telerik.Web.UI.ChangeLog");;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.PropertyBag = function (owner)
{
    this._data = {};
    this._owner = owner;
}

Telerik.Web.UI.PropertyBag.prototype = {
  getValue : function (propertyName, defaultValue)
  {
    var value = this._data[propertyName];
    
    if (typeof(value) === "undefined")
        return defaultValue;
    
    return value;
  },
  
  setValue : function (propertyName, value, notify)
  {
    this._data[propertyName] = value;
    
    if (notify)
        this._owner._notifyPropertyChanged(propertyName, value);
  },
  
  load : function (data)
  {
    this._data = data;
  }
};

Telerik.Web.UI.ControlItem = function()
{
	this._element = null;
	this._parent = null;
	this._text = null;
	this._children = null;
	this._childControlsCreated = false;
	this._itemData = null;
	this._control = null;
	this._properties = new Telerik.Web.UI.PropertyBag(this);
}

Telerik.Web.UI.ControlItem.prototype = 
{
	_shouldNavigate: function()
	{
		var navigateUrl = this.get_navigateUrl();
		if (!navigateUrl) return false;
		
		return !navigateUrl.endsWith("#");
	},
	
	_getNavigateUrl : function ()
	{
		if (this.get_linkElement())
		    return this._properties.getValue("navigateUrl", this.get_linkElement().getAttribute("href", 2));
		
		return this._properties.getValue("navigateUrl", null);
	},
	
	_initialize: function(json, element)
	{
		this.set_element(element);
		this._properties.load(json);
		
		if (json["attributes"])
			this.get_attributes()._load(json["attributes"]);
			
		this._itemData = json["items"];
	},
		
	_dispose: function()
	{
		if (this._children) 
			this._children.forEach(function(child) { child._dispose(); } );
		
		if (this._element) 
		{
			this._element._item = null;
			this._element = null;
		}
		
		if (this._control) 
			this._control = null;
	},


	// Public methods

	_initializeRenderedItem: function()
	{
		var childItems = this._children;
		if (!childItems || childItems.get_count() < 1) 
			return;
		
		var childElements = this._getChildElements();
		Sys.Debug.assert(childItems.get_count() == childElements.length, "Length of elements and child items must be the same!");
		
		for (var i = 0, length = childItems.get_count(); i < length; i++) 
		{
			var childItem = childItems.getItem(i);
			if (!childItem.get_element()) 
			{
				childItem.set_element(childElements[i]);
				if (this._shouldInitializeChild(childItem)) 
				{
					childItem._initializeRenderedItem();
				}
			}
		}
	},
	
	findControl : function (id)
	{
		return $telerik.findControl(this.get_element(), id);
	},
	
	get_attributes : function ()
	{
		if (!this._attributes)
		    this._attributes = new Telerik.Web.UI.AttributeCollection(this);
		return this._attributes;
	},
	
	// Public properties
	
	get_element: function()
	{
		return this._element;
	},
	
	set_element: function(value)
	{
		this._element = value;
		this._element._item = this;
        this._element._itemTypeName = Object.getTypeName(this);
	},
	
	get_parent: function()
	{
		return this._parent;
	},
	
	set_parent: function(value)
	{
		this._parent = value;
	},
	
	get_text : function ()
	{
		 if (this._text !== null) return this._text;

        if (this._text = this._properties.getValue("text", ""))
            return this._text;
		
		if (!this.get_element())
			return "";
		
		var textElement = this.get_textElement();
		if (!textElement)
			return "";

		if (typeof(textElement.innerText) != "undefined")
			this._text = textElement.innerText;
		else
			this._text = textElement.textContent;
			
		if($telerik.isSafari2)
		{
			this._text = textElement.innerHTML;
		}
		return this._text;
	},

	set_text : function (text)
	{ 
	    var textElement = this.get_textElement();
	    if (textElement)
			textElement.innerHTML = text;
	    
	    this._text = text;
	    this._properties.setValue("text", text, true);	    
	},
		
	get_value: function()
	{
		return this._properties.getValue("value", null);
	},
	
	set_value: function(value)
	{
		this._properties.setValue("value", value, true);
	},
	
	get_itemData: function()
	{
		return this._itemData;
	},
	
	get_index : function ()
	{
		if (!this.get_parent())
			return -1;
			
		return this.get_parent()._getChildren().indexOf(this);
	},
	
	set_enabled: function(value)
	{
		this._properties.setValue("enabled", value, true);
	},
	
	get_enabled: function()
	{
		return this._properties.getValue("enabled", true) == true;
	},
	
	get_isEnabled : function()
	{
		var control = this._getControl();
		if (control)
			return control.get_enabled() && this.get_enabled();
		
		return this.get_enabled();
	},
	
	set_visible: function(value)
	{
		this._properties.setValue("visible", value);
	},
	
	get_visible: function()
	{
		return this._properties.getValue("visible", true);
	},
	
	get_level : function ()
	{
		var parent = this.get_parent();
		var level = 0;
			
		while (parent) 
		{
			
			if (Telerik.Web.UI.ControlItemContainer.isInstanceOfType(parent)) 
			{
				return level;
			}
			
			level++;
			parent = parent.get_parent();
		}
		
		return level;
	},
	
	get_isLast : function()
	{
		return this.get_index() == this.get_parent()._getChildren().get_count() - 1;
	},
	
	get_isFirst : function()
	{
		return this.get_index() == 0;
	},
	
	get_nextSibling : function ()
	{
		if (!this.get_parent())
			return null;
		return this.get_parent()._getChildren().getItem(this.get_index() + 1);
	},
	
	get_previousSibling : function ()
	{
		if (!this.get_parent())
			return null;
		
		return this.get_parent()._getChildren().getItem(this.get_index() - 1);
	},
	
	// Private methods
	_getHierarchicalIndex : function () 
	{
		var indexes = [];
		var current = this;
		
		while (!Telerik.Web.UI.ControlItemContainer.isInstanceOfType(current))
		{
			Array.insert(indexes, 0, current.get_index());
			current = current.get_parent();
		}
		
		return indexes.join(":");
	},
	
	_getChildren : function()
	{
		this._ensureChildControls();
		return this._children;
	},
	
	_ensureChildControls: function()
	{
		if (!this._childControlsCreated) 
		{
			this._createChildControls();
			this._childControlsCreated = true;
		}
	},

	_setCssClass : function(element, cssClass)
	{
		if (element.className != cssClass)
			element.className = cssClass;
	},

	_createChildControls: function()
	{
		this._children = this._createItemCollection();
	},
	
	_createItemCollection : function()
	{
	},
	
	_getControl: function()
	{
		if (!this._control) 
		{
			var parent = this.get_parent();
			
			if (parent) 
			{
				if (Telerik.Web.UI.ControlItemContainer.isInstanceOfType(parent)) 
				{
					this._control = parent;
				}
				else 
				{
					this._control = parent._getControl();
				}
			}
		}
		
		return this._control;
	},
	
	_getAllItems: function()
	{
		var items = [];
		this._getAllItemsRecursive(items, this);
		return items;
	},
	
	_getAllItemsRecursive: function(items, currentItem)
	{
		var children = currentItem._getChildren();
		for (var i = 0; i < children.get_count(); i++) 
		{
			var child = children.getItem(i);
			Array.add(items, child);
			this._getAllItemsRecursive(items, child);
		}
	},
	
	_getData: function()
	{
		var data = this._properties._data;
		
		//we don't need this - it comes from the initial JSON
		delete data.items;	
		
		data["text"] = this.get_text()
		
		if (this.get_attributes().get_count() > 0)
			data["attributes"] = this.get_attributes()._data;
		
		return data;
	},
	
	_notifyPropertyChanged: function(property, value)
	{
		var control = this._getControl();
		if (control) 
			control._itemPropertyChanged(this, property, value);
	},
	
	_loadFromDictionary : function (data)
	{
		if (typeof(data.Text) != "undefined")
			this.set_text(data.Text);

		if (typeof(data.Value) != "undefined" && data.Value !== "")
			this.set_value(data.Value);
		
		if (typeof(data.Enabled) != "undefined" && data.Enabled !== true)
			this.set_enabled(data.Enabled);

		var attributes = this.get_attributes();
		for (var attributeKey in data.Attributes)
		{
			attributes.setAttribute(attributeKey, data.Attributes[attributeKey]);
		}
	},
	
	_createDomElement: function()
	{
		var itemElementParent = document.createElement("ul");
		var html = [];
		
		this._render(html);
		
		itemElementParent.innerHTML = html.join("");
		return itemElementParent.firstChild;
	}
}

Telerik.Web.UI.ControlItem.registerClass('Telerik.Web.UI.ControlItem');;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ControlItemCollection = function (parent)
{
	this._array = new Array();
	this._parent = parent;
	this._control = null;
}

Telerik.Web.UI.ControlItemCollection.prototype = 
{
	add : function (item)
	{	
		var index = this._array.length;
		this.insert(index, item);
	},
	
	insert : function (index, item)
	{
		var itemParent = item.get_parent();
		var control = this._parent._getControl();
		
		if(itemParent)
			itemParent._getChildren().remove(item);
		
		if (control)
			control._childInserting(index, item, this._parent);
			
		Array.insert(this._array, index, item);
		item.set_parent(this._parent);

		if (control)
		{
			control._childInserted(index, item, this._parent);
			control._logInserted(item);
		}
	},
	
	remove : function (item)
	{
		var control = this._parent._getControl();
		if (control)
			control._childRemoving(item);
		
		Array.remove(this._array, item);
		
		if (control)
			control._childRemoved(item, this._parent);
			
		item.set_parent(null);
		item._control = null;
	},
	
	removeAt : function (index)
	{
		var item = this.getItem(index);
		if (item)
			this.remove(item);
	},
	
	clear : function ()
	{
		var control = this._parent._getControl();
		if (control)
		{
			control._logClearing(this._parent);
			control._childrenCleared(this._parent);
		}
		
		this._array = new Array();
	},
	
	get_count : function ()
	{
		return this._array.length;
	},
	
	getItem : function(index)
	{
		return this._array[index];
	},
	
	indexOf : function (item)
	{
		return Array.indexOf(this._array, item);
	},

	forEach : function (lambda)
	{
	    for (var i = 0, count = this.get_count(); i < count; i++)
	    {
	        lambda(this._array[i]);
	    }
	}
}

Telerik.Web.UI.ControlItemCollection.registerClass("Telerik.Web.UI.ControlItemCollection");;function WebForm_CallbackComplete() 
{  
    for (var i = 0; i < __pendingCallbacks.length; i++) {
  
        var callbackObject = __pendingCallbacks[i];
        if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
            __pendingCallbacks[i] = null;
            WebForm_ExecuteCallback(callbackObject);
            if (!callbackObject.async) {
                __synchronousCallBackIndex = -1;
            }
            
            var callbackFrameID = "__CALLBACKFRAME" + i;
            var xmlRequestFrame = document.getElementById(callbackFrameID);
            if (xmlRequestFrame) {
                xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
            }
        }
    }
}

Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ControlItemContainer = function (element)
{
	Telerik.Web.UI.ControlItemContainer.initializeBase(this, [element]);
	
	this._childControlsCreated = false;
	this._enabled = true;
	this._log = new Telerik.Web.UI.ChangeLog();
	this._enableClientStatePersistence = false;
	this._eventMap = new Telerik.Web.UI.EventMap();
	this._attributes = new Telerik.Web.UI.AttributeCollection(this);
	this._children = null;
}

Telerik.Web.UI.ControlItemContainer.prototype =
{
	initialize : function ()
	{
		Telerik.Web.UI.ControlItemContainer.callBaseMethod(this, 'initialize');

		this._ensureChildControls();
		this._log.initialize();
		this._initializeEventMap();
	},
	
	dispose : function ()
	{	
		this._eventMap.dispose();

        if(this._childControlsCreated)
        {
		    for (var i = 0; i < this._getChildren().get_count(); i++)
		    {
			    this._getChildren().getItem(i)._dispose();
		    }
		}

		Telerik.Web.UI.ControlItemContainer.callBaseMethod(this, 'dispose');
	},
	
	trackChanges : function ()
	{
		this._enableClientStatePersistence = true;
	},
	
	set_enabled: function(value)
	{
		this._enabled = value;
	},
	
	get_enabled: function()
	{
		return this._enabled;
	},
	
	commitChanges : function ()
	{
		this.updateClientState();
		this._enableClientStatePersistence = false;
	},
	
	get_attributes : function ()
	{
		return this._attributes;
	},
	
	set_attributes : function (value)
	{
		this._attributes._load(value);
	},
	
	
	/*------------- Private Methods -----------*/
	_initializeEventMap : function()
	{
		this._eventMap.initialize(this);
	},

	_getChildren : function ()
	{
		this._ensureChildControls();
		return this._children;
	},
	
	_extractErrorMessage : function (error)
	{
		if (error.get_message)
		{
			// AJAX Exception
			return error.get_message();
		}
		else
		{		
			// ASP.NET callback return error messages in the following form:
			// <exception message><eventValidationLength>|<eventValidationString> e.g.
			// Object reference not set to an instance of an object.56|/wEWAwLM2oLGBwLs0bLrBgLs0fbZDC3VMN/DL8xzHgo9Pw1ztfesraLy
			return error.replace(/(\d*\|.*)/,"");
		}
	},

	_notifyPropertyChanged : function (propertyName, propertyValue)
	{
		
	},
	
	_childInserting : function (index, item, parent)
	{
		
	},
	
	_childInserted : function (index, item, parent)
	{
		if (!parent._childControlsCreated) return;
		if (!parent.get_element()) return;
		
		itemElement = item._createDomElement();
		var parentListElement = parent.get_childListElement();
		
		if (!parentListElement) 
			parentListElement = parent._createChildListElement();
		
		var nextItem = item.get_nextSibling();
		var nextItemElement = nextItem ? nextItem.get_element() : null;
		parent.get_childListElement().insertBefore(itemElement, nextItemElement);
		
		if (!item.get_element()) 
		{
			item.set_element(itemElement);
			item._initializeRenderedItem();
		}
		else 
		{
			item.set_element(itemElement);
		}
	},
	
	_childrenCleared : function (parent)
	{
		for(var i = 0; i < parent._getChildren().get_count(); i++)
		{
			parent._getChildren().getItem(i)._dispose();
		}
		
		var childListElement = parent.get_childListElement();
		if(childListElement)
			childListElement.innerHTML = "";
	},
	
	_childRemoving : function (child)
	{
		this._logRemoving(child);
	},
	
	_childRemoved : function (item, parent)
	{
		item._dispose();
	},

	_createChildListElement : function()
	{
		throw Error.notImplemeneted();
	},

	_createDomElement : function()
	{
		throw Error.notImplemented();
	},

	_getControl : function ()
	{
		return this;
	},
	
	_logInserted : function (item)
	{
		if (!item.get_parent()._childControlsCreated || !this._enableClientStatePersistence) return;
		
		this._log.logInsert(item);
		
		var children = item._getAllItems();
		for (var i = 0; i < children.length; i++)					
		{
			this._log.logInsert(children[i]);
		}
	},
	
	_logRemoving : function (item)
	{
		if (this._enableClientStatePersistence)
			this._log.logDelete(item);
	},
	
	_logClearing : function (item)
	{
		if (this._enableClientStatePersistence)
			this._log.logClear(item);
	},
	
	_itemPropertyChanged : function (item, property, value)
	{
		if (this._enableClientStatePersistence)
			this._log.logPropertyChanged(item, property, value);
	},
	
	_ensureChildControls : function ()
	{
		if (!this._childControlsCreated)
		{		
			this._createChildControls();
			this._childControlsCreated = true;
		}
	},
	
	_extractItemFromDomElement : function (element)
	{
        this._ensureChildControls();
		while (element && element.nodeType !== 9)
		{
			if (element._item && this._verifyChildType(element._itemTypeName))
				return element._item;
				
			element = element.parentNode;
		}
		return null;
	},
	
	_verifyChildType : function (targetTypeName)
	{
		return targetTypeName === this._childTypeName;
	},
	
	_getAllItems : function ()
	{
		var allItems = [];
		for (var i = 0; i < this._getChildren().get_count(); i++)
		{
			var item = this._getChildren().getItem(i);
			Array.add(allItems, item);
			Array.addRange(allItems, item._getAllItems());
		}
		
		return allItems;
	},
	
	_findItemByText : function (text)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_text() == text)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByValue : function (value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_value() == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByAttribute : function(attributeName, value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_attributes().getAttribute(attributeName) == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByAbsoluteUrl: function (value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_linkElement() && allItems[i].get_linkElement().href == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByUrl: function (value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_navigateUrl() == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByHierarchicalIndex : function (index)
	{
		var currentItem = null;
		var container = this;
		var indexes = index.split(":");
		for (var i = 0; i < indexes.length; i++)
		{
			var currentIndex = parseInt(indexes[i]);
			if (container._getChildren().get_count() <= currentIndex)
				return null;

			currentItem = container._getChildren().getItem(currentIndex);
			container = currentItem;
		}

		return currentItem;
	}
}

Telerik.Web.UI.ControlItemContainer.registerClass("Telerik.Web.UI.ControlItemContainer", Telerik.Web.UI.RadWebControl);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.EventMap = function ()
{
	this._owner = null;
	this._element = null;
	this._eventMap = {};
	this._onDomEventDelegate = null;
	this._browserHandlers = {};
}

Telerik.Web.UI.EventMap.prototype = 
{	
	initialize : function (owner, element)
	{
		this._owner = owner;
		if (!element)
			element = this._owner.get_element();
		this._element = element;
	},

	dispose : function ()
	{
		if (this._onDomEventDelegate)
		{
			for (var eventName in this._eventMap)
			{
				if (this._shouldUseEventCapture(eventName))
				{
					var browserHandler = this._browserHandlers[eventName];
					this._element.removeEventListener(eventName, browserHandler, true);
				}
				else
				{
					$removeHandler(this._element, eventName, this._onDomEventDelegate);
				}
			}
			
			this._onDomEventDelegate = null;
			this._element._events = null;
		}
	},
	
	// Public methods
	addHandlerForClassName : function (eventName, className, handler)
	{
		if (typeof(this._eventMap[eventName]) == "undefined")
		{
			this._eventMap[eventName] = {};
			
			if (this._shouldUseEventCapture(eventName))
			{
				var domEventHandler = this._getDomEventDelegate();
				var element = this._element;
				var browserHandler = function(e) { return domEventHandler.call(element, new Sys.UI.DomEvent(e)); }
				this._browserHandlers[eventName] = browserHandler;
				element.addEventListener(eventName, browserHandler, true);
			}
			else
			{
				$addHandler(this._element, eventName, this._getDomEventDelegate());
			}
		}
		
		var eventHandlers = this._eventMap[eventName];
		eventHandlers[className] = handler;
	},
	
	// Private methods
	_onDomEvent: function(e)
	{
		var dispatchees = this._eventMap[e.type];
		if (!dispatchees) 
			return;
		
		var target = e.target;
		while (target && target.nodeType !== 9) 
		{
			var className = target.className;
			var subClasses = className.split(' ');
			
			var dispatchee = null;
			
			for (var i = 0; i < subClasses.length; i++)
			{
				dispatchee = dispatchees[subClasses[i]];
				if (dispatchee) break;
			}
			
			if (dispatchee) 
			{
				this._fillEventFields(e, target);
				if (dispatchee.call(this._owner, e) != true) 
				{
					if (!target.parentNode) 
					{
						// The target was removed from the DOM in the event handler.
						// Event propagation in this case causes "Unspecified error" in IE6.
						e.stopPropagation();
					}
					
					return;
				}
			}
			
			if (target == this._element) 
			{
				return;
			}
			
			target = target.parentNode;			
		}
	},
	
	_fillEventFields : function (e, currentTarget)
	{
		e.eventMapTarget = currentTarget;
		if (e.rawEvent.relatedTarget)
		{
			e.eventMapRelatedTarget = e.rawEvent.relatedTarget;
		}
		else
		{
			if (e.type == "mouseover")
			{
				e.eventMapRelatedTarget = e.rawEvent.fromElement;
			}
			else
			{	
				e.eventMapRelatedTarget = e.rawEvent.toElement;
			}
		}
		
		if (!e.eventMapRelatedTarget)
			return;
		
		try 
		{
			// Fix for FireFox "_moz_editor_bogus_node" problem.
			// Happens on mouseout and mouseover when the related target is an input element.
			// For some reason input elements have an "anonymous" div as a child:
			// <div class="anonymous-div" style="white-space: pre;" _moz_editor_bogus_node="TRUE" _moz_dirty="">
			// Accessing *any* attribute of such a node will throw "permission denied" error.
			var className = e.eventMapRelatedTarget.className;
		} 
		catch (ex) 
		{
			// Skip to the parent element.
			e.eventMapRelatedTarget = this._element;
		}		
	},
	
	_shouldUseEventCapture : function(eventName)
	{
		return (eventName == "blur" || eventName == "focus") && $telerik.isFirefox && Sys.Browser.version >= 3;
	},
	
	_getDomEventDelegate : function ()
	{
		if (!this._onDomEventDelegate)
		{
			this._onDomEventDelegate = Function.createDelegate(this, this._onDomEvent);
		}
		
		return this._onDomEventDelegate;
	}
}

Telerik.Web.UI.EventMap.registerClass('Telerik.Web.UI.EventMap');;Type.registerNamespace("Telerik.Web.UI");


// ---------- Overlay Class ----------
Telerik.Web.UI.Overlay = function(targetElement)
{
	this._targetElement = targetElement;
	this._element = null;
}

Telerik.Web.UI.Overlay.IsSupported = function ()
{
	return $telerik.isIE;
}

Telerik.Web.UI.Overlay.prototype = 
{
	initialize: function()
	{
		//Using this workaround to set the contents of the iframe (required for sectio 508 compliance)
		
		var placeholder = document.createElement("div");
		placeholder.innerHTML = "<iframe>Your browser does not support inline frames or is currently configured not to display inline frames.</iframe>";
		this._element = placeholder.firstChild;
		this._element.src = "javascript:'';";
		this._targetElement.parentNode.insertBefore(this._element, this._targetElement);
		
		if (this._targetElement.style.zIndex > 0)
		{
			this._element.style.zIndex = this._targetElement.style.zIndex - 1;
		}
		
		this._element.style.position = "absolute";	
		this._element.style.border = "0px";	
		this._element.frameBorder = 0;
		this._element.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		this._element.tabIndex = -1;
		
		if (!$telerik.isSafari)
			placeholder.outerHTML = null;
			
		this.updatePosition();
	},
	
	dispose: function()
	{
		if (this._element.parentNode)
		{
			this._element.parentNode.removeChild(this._element);
		}

		this._targetElement = null;
		this._element = null;
	},
	
	get_targetElement : function ()
	{
		return this._targetElement;
	},
	
	set_targetElement : function (value)
	{
		this._targetElement = value;
	},
	
	updatePosition: function()
	{
		this._element.style.top = this._toUnit(this._targetElement.style.top);
		this._element.style.left = this._toUnit(this._targetElement.style.left);
		this._element.style.width = this._targetElement.offsetWidth + "px";
		this._element.style.height = this._targetElement.offsetHeight + "px";	
	},
	
	_toUnit: function(value)
	{
		if (!value) return "0px";
		return parseInt(value) + "px";
	}
}

Telerik.Web.UI.Overlay.registerClass('Telerik.Web.UI.Overlay', null, Sys.IDisposable);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI._PostbackWrapper = function ()
{
	this._doPostbackReplaced = false;
	this._events = new Sys.EventHandlerList();
	this._originalDoPostBack = null;
	this._onWindowUnloadHandler = null;
	this._postbackEventRaised = false;
	this._beginRequestHandler = null;
	this._onsubmitHandler = null;
	this._partialRenderingEnabledChecked = false;
	this._partialRenderingEnabled = false;
}

Telerik.Web.UI._PostbackWrapper.prototype =
{
	initialize : function()
	{
        this._onWindowUnloadHandler = Function.createDelegate(this, this._onWindowUnload);

        Sys.UI.DomEvent.addHandler(window, 'unload', this._onWindowUnloadHandler);
	},

	_raiseBeforePostback : function(eventArgs)
	{
		var handler = this._events.getHandler("beforePostback");
		if (handler)
		{
			if (!eventArgs)
			{
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
		}
		this._postbackEventRaised = true;
	},
	
	_doPostback : function(eventTarget, eventArgument)
	{
		this._raiseBeforePostback(Sys.EventArgs.Empty);
		this._originalDoPostBack(eventTarget, eventArgument);
	},
	
	_onSubmit : function(e)
	{
		return this._handleNormalSubmit(e);
	},
	
	_handleNormalSubmit : function(e)
	{
		if (!this._postbackEventRaised)
		{
			this._raiseBeforePostback(Sys.EventArgs.Empty);
		}
		return true;
	},
	
	_endRequest : function()
	{
		this._postbackEventRaised = false;
	},
	
	_isPartialRenderingEnabled : function()
	{
		if (!this._partialRenderingEnabledChecked)
		{
			this._partialRenderingEnabled = true;
			if (typeof(Sys) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (typeof(Sys.WebForms) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (typeof(Sys.WebForms.PageRequestManager) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (!Sys.WebForms.PageRequestManager.getInstance())
			{
			    this._partialRenderingEnabled = false;
			}
			this._partialRenderingEnabledChecked = true;
		}
		return this._partialRenderingEnabled;
	},
	
	add_beforePostback : function(handler)
	{
		if (!this._isPartialRenderingEnabled())
		{
			return;
		}
		if (!this._onsubmitHandler)
		{
			this._onsubmitHandler = Function.createDelegate(this, this._onSubmit);
			Array.add(Sys.WebForms.PageRequestManager.getInstance()._onSubmitStatements, this._onsubmitHandler);
		}
		if (!this._endRequestHandler)
		{
			this._endRequestHandler = Function.createDelegate(this, this._endRequest);
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this._endRequestHandler);
		}
		if (!this._doPostbackReplaced)
		{
			this._replaceDoPostback();
		}
		this._events.addHandler("beforePostback", handler);
	},

	remove_beforePostback : function(handler)
	{
		this._events.removeHandler("beforePostback", handler);
	},

	_replaceDoPostback : function()
	{
		if (typeof(Page_IsValid) != "undefined")
		{
			return;
		}
		this._originalDoPostBack = window.__doPostBack;
		if (this._originalDoPostBack)
		{
			window.__doPostBack = Function.createDelegate(this, this._doPostback);
        }

		this._doPostbackReplaced = true;
	},
	
    _onWindowUnload : function(rawEvent)
    {
        this.dispose();
    },

    dispose : function()
    {
		Sys.UI.DomEvent.removeHandler(window, 'unload', this._onWindowUnloadHandler);
		if (this._endRequestHandler)
		{
			Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler);
			this._endRequestHandler = null;
		}

        if (this._originalDoPostBack)
        {
			window.__doPostBack = this._originalDoPostBack;
			this._originalDoPostBack = null;
        }
    }
}

Telerik.Web.UI._PostbackWrapper.registerClass("Telerik.Web.UI._PostbackWrapper");

Telerik.Web.UI.PostbackWrapper = new Telerik.Web.UI._PostbackWrapper();
Telerik.Web.UI.PostbackWrapper.initialize();;Type.registerNamespace("Telerik.Web.UI");


// ---------- SlideDirection Enum ----------
Telerik.Web.UI.SlideDirection = function()
{
};
Telerik.Web.UI.SlideDirection.prototype = 
{
	Up: 1,
	Down: 2,
	Left: 3,
	Right: 4
}
Telerik.Web.UI.SlideDirection.registerEnum("Telerik.Web.UI.SlideDirection");


// ---------- Slide Class ----------
Telerik.Web.UI.Slide = function(animatedElement, expandAnimation, collapseAnimation, enableOverlay)
{
	// Constants
	this._fps = 60;
	
	this._animatedElement = animatedElement;
	this._element = animatedElement.parentNode;
	this._expandAnimation = expandAnimation;
	this._collapseAnimation = collapseAnimation;
	this._direction = Telerik.Web.UI.SlideDirection.Down;
	this._animation = null;
	this._expanding = null;
	
	if (enableOverlay == null)
	{
		this._enableOverlay = true;
	}
	else
	{
		this._enableOverlay = enableOverlay;
	}
	
	this._events = null;
	this._overlay = null;

	this._animationEndedDelegate = null;
	this._expandAnimationStartedDelegate = null;
	this._updateOverlayDelegate = null;
}

Telerik.Web.UI.Slide.prototype = 
{
	initialize: function()
	{
		if (Telerik.Web.UI.Overlay.IsSupported() && this._enableOverlay) 
		{
			var animatedElement = this.get_animatedElement();
			this._overlay = new Telerik.Web.UI.Overlay(animatedElement);
			this._overlay.initialize();
		}

		this._animationEndedDelegate = Function.createDelegate(this, this._animationEnded);
		this._expandAnimationStartedDelegate = Function.createDelegate(this, this._expandAnimationStarted);
		this._updateOverlayDelegate = Function.createDelegate(this, this._updateOverlay);
	},
	
	dispose: function()
	{
		this._animatedElement = null;
		this._events = null;

		this._disposeAnimation();

		if (this._overlay) 
		{
			this._overlay.dispose();
			this._overlay = null;
		}

		this._animationEndedDelegate = null;
		this._expandAnimationStartedDelegate = null;
		this._updateOverlayDelegate = null;
	},
	
	
	// Properties
	get_element : function ()
	{
		return this._element;
	},
	
	get_animatedElement: function()
	{
		return this._animatedElement;
	},
	
	set_animatedElement: function(value)
	{
		this._animatedElement = value;
		
		if (this._overlay)
		{
			this._overlay.set_targetElement(this._animatedElement);
		}
	},
	
	get_direction: function()
	{
		return this._direction;
	},
	
	set_direction: function(value)
	{
		this._direction = value;
	},
	
	get_events: function ()
	{
		if (!this._events)
		{
			this._events = new Sys.EventHandlerList();
		}
		
		return this._events;
	},
	
	// Public methods
	updateSize: function()
	{
		var animatedElement = this.get_animatedElement();
		var element = this.get_element();
		
		var top = 0;
		if (animatedElement.style.top) 
		{
			top = Math.max(parseInt(animatedElement.style.top), 0);
		}
		
		var left = 0;
		if (animatedElement.style.left) 
		{
			left = Math.max(parseInt(animatedElement.style.left), 0);
		}
		
		var height = animatedElement.offsetHeight + top;
		if (element.style.height != height + "px") 
		{
			element.style.height = Math.max(height, 0) + "px";
		}
		
		var width = animatedElement.offsetWidth + left;
		if (element.style.width != width + "px") 
		{
			element.style.width = Math.max(width, 0) + "px";
		}
		
		if (this._overlay)
		{
			this._updateOverlay();
		}
	},
	
	show: function()
	{
		this._showElement();
	},
	
	expand: function()
	{	
		this._expanding = true;

		// Hide element before doing the calculations to prevent flicker.
		this.get_animatedElement().style.visibility = "hidden";

		this._resetState(true);

		var startPosition = null;
		var finalPosition = null;
		
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Left:
				startPosition = parseInt(this._getSize());
				finalPosition = 0;
				break;
				
			case Telerik.Web.UI.SlideDirection.Down:
			case Telerik.Web.UI.SlideDirection.Right:
				startPosition = parseInt(this._getPosition());
				finalPosition = 0;
				break;
		}
	
		if (this._animation)
		{
			this._animation.stop();
		}

		if ((startPosition == finalPosition) ||
			(this._expandAnimation.get_type() == Telerik.Web.UI.AnimationType.None))
		{
			this._expandAnimationStarted();
			this._setPosition(finalPosition);		
			this._animationEnded();
			this.get_animatedElement().style.visibility = "visible";
		}
		else 
		{
			this._playAnimation(this._expandAnimation, startPosition, finalPosition);
		}
	},
	
	collapse: function()
	{
		this._resetState();
		this._expanding = false;
		
		var startPosition = null;
		var finalPosition = null;
		var size = parseInt(this._getSize());
		var position = parseInt(this._getPosition());

		switch (this.get_direction())
		{							
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Left:
				startPosition = 0;
				finalPosition = size;
			break;

			case Telerik.Web.UI.SlideDirection.Down:
			case Telerik.Web.UI.SlideDirection.Right:
				startPosition = 0;
				finalPosition = position - size;
				break;
		}
	
		if (this._animation)
		{
			this._animation.stop();
		}
		
		if ((startPosition == finalPosition) ||
			(this._collapseAnimation.get_type() == Telerik.Web.UI.AnimationType.None))
		{
			this._setPosition(finalPosition);
			this._animationEnded();
		}
		else 
		{
			this._playAnimation(this._collapseAnimation, startPosition, finalPosition);
		}
	},
	
	
	// Events
	add_collapseAnimationEnded : function(handler)
	{
		this.get_events().addHandler('collapseAnimationEnded', handler);
	},
	
	remove_collapseAnimationEnded : function(handler)
	{
		this.get_events().removeHandler('collapseAnimationEnded', handler);        
	},
	
	add_expandAnimationEnded : function(handler)
	{
		this.get_events().addHandler('expandAnimationEnded', handler);
	},
	
	remove_expandAnimationEnded : function(handler)
	{
		this.get_events().removeHandler('expandAnimationEnded', handler);        
	},
	
	add_expandAnimationStarted : function(handler)
	{
		this.get_events().addHandler('expandAnimationStarted', handler);
	},
	
	remove_expandAnimationStarted : function(handler)
	{
		this.get_events().removeHandler('expandAnimationStarted', handler);        
	},
	
	
	// Private methods
	_playAnimation: function(animationSettings, startPosition, finalPosition)
	{
		var duration = animationSettings.get_duration();
		var animatedProperty = this._getAnimatedStyleProperty();
		var points = Telerik.Web.UI.AnimationFunctions.CalculateAnimationPoints(animationSettings, startPosition, finalPosition, this._fps);
		var animatedElement = this.get_animatedElement();

		// Show the animatedElement after the calculations have been done.		
		animatedElement.style.visibility = "visible";
		
		if (this._animation)
		{
			this._animation.set_target(animatedElement);
			this._animation.set_duration(duration / 1000);
			this._animation.set_propertyKey(animatedProperty);
			this._animation.set_values(points);
		}
		else
		{
			this._animation = new $TWA.DiscreteAnimation(animatedElement, duration / 1000, this._fps, "style", animatedProperty, points);
			this._animation.add_started(this._expandAnimationStartedDelegate);
			this._animation.add_ended(this._animationEndedDelegate);
		
			if (this._overlay) 
			{
				this._animation.add_onTick(this._updateOverlayDelegate);
			}
		}
		
		this._animation.play();
	},
	
	_animationEnded: function()
	{
		if (this._expanding)
		{
			this.get_element().style.overflow = "visible";					
			this._raiseEvent('expandAnimationEnded', Sys.EventArgs.Empty);
		}
		else
		{
			this.get_element().style.display = "none";
			this._raiseEvent('collapseAnimationEnded', Sys.EventArgs.Empty);
		}
	
		if (this._overlay)
		{
			this._updateOverlay();
		}
	},
	
	_expandAnimationStarted: function()
	{
		this._raiseEvent('expandAnimationStarted', Sys.EventArgs.Empty);
	},
	
	_updateOverlay : function ()
	{
		this._overlay.updatePosition();
	},
	
	_showElement: function()
	{
		var animatedElement = this.get_animatedElement();
		var element = this.get_element();
		
		if (!element) 
			return;
		
		if (!element.style) 
			return;
		
		// Table elements do not work well with "block" display.
		element.style.display = (element.tagName.toUpperCase() != "TABLE") ? "block" : "";
		animatedElement.style.display = (animatedElement.tagName.toUpperCase() != "TABLE") ? "block" : "";
		
		element.style.overflow = "hidden";
	},
	
	_resetState: function(resetPosition)
	{
		this._stopAnimation();
		this._showElement();
	
		if (resetPosition) 
		{
			var animatedElement = this.get_animatedElement();
			switch (this.get_direction())
			{
				case Telerik.Web.UI.SlideDirection.Up:
					animatedElement.style.top = "0px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Down:
					animatedElement.style.top = -animatedElement.offsetHeight + "px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Left:
					animatedElement.style.left = animatedElement.offsetWidth + "px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Right:
					animatedElement.style.left = -animatedElement.offsetWidth + "px";
					break;
					
				default:
					Error.argumentOutOfRange("direction", this.get_direction(), "Slide direction is invalid. Use one of the values in the Telerik.Web.UI.SlideDirection enumeration.");
					break;
			}
		}
	},
	
	_getSize : function ()
	{
		var animatedElement = this.get_animatedElement();
		
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Down:
				return animatedElement.offsetHeight;
				break;

			case Telerik.Web.UI.SlideDirection.Left:
			case Telerik.Web.UI.SlideDirection.Right:
				return animatedElement.offsetWidth;
				break;
				
			default:
				return 0;
		}
	},
	
	_setPosition : function (value)
	{
		var animatedElement = this.get_animatedElement();
		var animatedProperty = this._getAnimatedStyleProperty();
		animatedElement.style[animatedProperty] = value;		
	},
	
	_getPosition: function()
	{
		var animatedElement = this.get_animatedElement();
		var animatedProperty = this._getAnimatedStyleProperty();
		
		return animatedElement.style[animatedProperty];
	},
	
	_getAnimatedStyleProperty: function()
	{
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Down:
				return "top";
				
			case Telerik.Web.UI.SlideDirection.Left:
			case Telerik.Web.UI.SlideDirection.Right:
				return "left";
		}
	},
	
	_stopAnimation : function()
	{
		if (this._animation) 
		{
			this._animation.stop();
		}
	},
	
	_disposeAnimation: function()
	{
		if (this._animation) 
		{
			this._animation.dispose();
			this._animation = null;
		}
	},
	
	_raiseEvent : function (eventName, eventArgs)
	{
		var handler = this.get_events().getHandler(eventName);        

		if (handler)
		{
			if (!eventArgs)
			{
				eventArgs = Sys.EventArgs.Empty;
			}

			handler(this, eventArgs);
		}
	}
}

Telerik.Web.UI.Slide.registerClass('Telerik.Web.UI.Slide', null, Sys.IDisposable);;
/* END Telerik.Web.UI.Common.Navigation.NavigationScripts.js */
/* START Telerik.Web.UI.ComboBox.RadComboBoxScripts.js */
// ---------- RadComboBoxEventArgs Class ----------
Telerik.Web.UI.RadComboBoxEventArgs = function (e)
{
	Telerik.Web.UI.RadComboBoxEventArgs.initializeBase(this);
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxEventArgs.prototype =
{ 

	get_domEvent : function ()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadComboBoxEventArgs.registerClass('Telerik.Web.UI.RadComboBoxEventArgs', Sys.EventArgs);


// ---------- RadComboBoxEventArgs Class ----------
Telerik.Web.UI.RadComboBoxCancelEventArgs = function (e)
{
	Telerik.Web.UI.RadComboBoxCancelEventArgs.initializeBase(this);
	
	this._domEvent = e;
}
Telerik.Web.UI.RadComboBoxCancelEventArgs.prototype =
{ 
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadComboBoxCancelEventArgs.registerClass('Telerik.Web.UI.RadComboBoxCancelEventArgs', Sys.CancelEventArgs);


// ---------- RadComboBoxItemEventArgs Class ----------
Telerik.Web.UI.RadComboBoxItemEventArgs = function(item, e)
{
	Telerik.Web.UI.RadComboBoxItemEventArgs.initializeBase(this);
	
	this._item = item;
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxItemEventArgs.prototype =
{
	get_item : function ()
	{
		return this._item;
	},
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadComboBoxItemEventArgs.registerClass('Telerik.Web.UI.RadComboBoxItemEventArgs', Sys.EventArgs);


// ---------- RadComboBoxItemCancelEventArgs Class ----------
Telerik.Web.UI.RadComboBoxItemCancelEventArgs = function (item, e)
{
	Telerik.Web.UI.RadComboBoxItemCancelEventArgs.initializeBase(this);
	this._item = item;
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxItemCancelEventArgs.prototype = 
{
	get_item : function ()
	{
		return this._item;
	},
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}

Telerik.Web.UI.RadComboBoxItemCancelEventArgs.registerClass('Telerik.Web.UI.RadComboBoxItemCancelEventArgs', Sys.CancelEventArgs);


// ---------- RadComboBoxRequestEventArgs Class ----------
Telerik.Web.UI.RadComboBoxRequestEventArgs = function (text, e)
{
	Telerik.Web.UI.RadComboBoxRequestEventArgs.initializeBase(this);
	this._text = text;
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxRequestEventArgs.prototype = 
{
	get_text : function ()
	{
		return this._text;
	},
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}

Telerik.Web.UI.RadComboBoxRequestEventArgs.registerClass('Telerik.Web.UI.RadComboBoxRequestEventArgs', Sys.EventArgs);


// ---------- RadComboBoxRequestCancelEventArgs Class ----------
Telerik.Web.UI.RadComboBoxRequestCancelEventArgs = function (text, context, e)
{
	Telerik.Web.UI.RadComboBoxRequestCancelEventArgs.initializeBase(this);

	this._text = text;
	this._context = context;
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxRequestCancelEventArgs.prototype = 
{
	get_text : function ()
	{
		return this._text;
	},

	get_context : function ()
	{
		return this._context;
	},
	
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}

Telerik.Web.UI.RadComboBoxRequestCancelEventArgs.registerClass('Telerik.Web.UI.RadComboBoxRequestCancelEventArgs', Sys.CancelEventArgs);


// ---------- RadComboBoxItemsRequestFailedEventArgs Class ----------
Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs = function(text, errorMessage, e)
{
	Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs.initializeBase(this);
	
	this._text = text;
	this._errorMessage = errorMessage;
	this._domEvent = e;
}

Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs.prototype =
{
	get_text : function ()
	{
		return this._text;
	},

	get_errorMessage : function ()
	{
		return this._errorMessage;
	},
	get_domEvent : function ()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs.registerClass('Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs', Telerik.Web.UI.RadComboBoxCancelEventArgs);;Type.registerNamespace("Telerik.Web.UI");

// ---------- Telerik.Web.UI.Keys Enum ----------
Telerik.Web.UI.Keys = function (){}
Telerik.Web.UI.Keys.prototype = 
{
	Shift : 16,
	Escape: 27,
	Up : 38,
	Down : 40,
	Left : 37,
	Right : 39,
	Enter : 13,
	Tab : 9,
	Space : 32,
	PageUp : 33,
	Del : 46,
	F1: 112,
	F12 : 123
}
Telerik.Web.UI.Keys.registerEnum("Telerik.Web.UI.Keys");

Telerik.Web.UI.RadComboBoxFilter = function (){}
Telerik.Web.UI.RadComboBoxFilter .prototype = 
{
	None : 0,
	Contains : 1,
	StartsWith : 2
}

Telerik.Web.UI.RadComboBoxFilter.registerEnum("Telerik.Web.UI.RadComboBoxFilter");


// ---------- RadComboBox Class ----------
Telerik.Web.UI.RadComboBox = function (element)
{
	Telerik.Web.UI.RadComboBox.initializeBase(this, [element]);
	
	this._callbacktext = "";
	this._changeText = true;
	this._children = null;
	this._virtualScroll = true;
	this._itemData = null;
	this._selectedItem =  null;
	this._selectedIndex=  null;
	this._highlightedItem =  null;
	this._dropDownVisible = false;
	this._enableLoadOnDemand = false;
	this._enableTextSelection = true;
	
	this._enableItemCaching = false;
	this._openDropDownOnLoad = false;
	this._appendItems = false;
	this._allowCustomText = false;
	this._markFirstMatch =  false;
	this._filter =  0;
	this._originalText = this.get_inputDomElement().value;
	this._cachedText = this._originalText;
	this._text = "";
	this._value = null;
	this._isCaseSensitive = false;
	this._autoCompleteSeparator = null;
	this._postBackReference = null;
	this._dropDownElement = null;
	this._inputDomElement = null;
	this._imageDomElement = null;
	this._tableElement = null;
	this._itemRequestTimeout = 300;
	this._isTemplated = false;
	this._requestTimeoutID = 0;
	this._highlightTemplatedItems = false;
	this._clientState = { value: "", text: "", enabled: true, logEntries: [] };
	this._uniqueId = null;
	this._rightToLeft = false;
	this._isDetached = false;
	this._offsetX = 0;
	this._offsetY = 0;
	this._overlay = null;
	this._enableScreenBoundaryDetection = true;
	this._suppressChange = false;
	this._lastKeyCode = null;
	this._loadingDiv = null;
	this._loadingMessage = "Loading...";
	this._showMoreResultsBox = false;
	this._closeDropDownOnBlur = true;
	this._focused = false;
	this._causesValidation = true;
	this.get_inputDomElement().setAttribute("autocomplete", "off");
	this._errorMessage = "CallBack Error!";
	this._showMoreMessage = "";
	this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings({});
	this._webServiceLoader = null;
	this._clientDataString = null;
	this._scrollbarWidth = 16;
	this._enabled = true;
	this._fireEvents = this._enabled ;
	this._slide = null;
	this._expandAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._expandDelay = 100;
	this._collapseAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._collapseDelay = 500;
	this._slideDirection = Telerik.Web.UI.SlideDirection.Down;
	this._expandAnimationEndedDelegate = null;
	this._expandAnimationStartedDelegate = null;
	this._showDropDownOnTextboxClick = true;
	this._dropDownWidth = "";
	this._height = "";
	this._childListElementWrapper = null;
	this._skin = "";
	this._skipLoadingItems = false;
	this._ajaxRequest = false;
	this._endOfItems = false;
	this._emptyMessage = null;
	this._disposed = false;
	this._disposeChildElements = true;
	this.lodHashTable =     
            {
            };

}

Telerik.Web.UI.RadComboBox.ComboBoxes = [];

Telerik.Web.UI.RadComboBox._createChildControls = function (parent, items)
{
	
	var itemData = parent.get_itemData();

	if (!itemData) return;
	
	var  childListElement = parent.get_childListElement();
	
	if (!childListElement) return;
	
	var childElements = $telerik.getChildrenByTagName(parent.get_childListElement(), "li");
	var itemsLength = childElements.length;
	var startIndex = 0;
	
	//Handle the case when a loading message appears
	if( childElements.length > 0 && childElements[0].className == "rcbLoading" )
	{
		itemsLength = itemsLength - 1;
		startIndex = 1;
	}
	
	Sys.Debug.assert(itemData.length == itemsLength, "Length of elements and json must be the same!");	
	
	for (var i = startIndex; i < childElements.length; i++)
	{
		var item = new Telerik.Web.UI.RadComboBoxItem();
		items.add(item);
		item._initialize(itemData[i-startIndex], childElements[i]);
		
	}	
}

Telerik.Web.UI.RadComboBox.prototype =
{
	initialize : function ()
	{
		Telerik.Web.UI.RadComboBox.callBaseMethod(this, 'initialize');
		
		this._clientState.value = this._value;
		this._clientState.text = this._text;
		this.updateClientState();
		
		if (this._requiresRightToLeft())
		{
			this._initRightToLeft();
		}
		
		if(this.get_childListElement())
		{
			this._onDropDownClickDelegate = Function.createDelegate(this, this._onDropDownClick);
			$addHandler(this.get_childListElement(), "click", this._onDropDownClickDelegate);
		
			this._onDropDownHoverDelegate = Function.createDelegate(this, this._onDropDownHover);
			$addHandler(this.get_childListElement(), "mouseover", this._onDropDownHoverDelegate);
			
			this._cancelDelegate = Function.createDelegate(this, this._cancelEvent);
			$addHandler(this.get_childListElement(), "selectstart", this._cancelDelegate);
			$addHandler(this.get_childListElement(), "dragstart", this._cancelDelegate);
			
			this._onDropDownOutDelegate = Function.createDelegate(this, this._onDropDownOut);
			$addHandler(this.get_childListElement(), "mouseout", this._onDropDownOutDelegate);
		}
		
		this._onTableHoverDelegate = Function.createDelegate(this, this._onTableHover);
		$addHandler(this.get_tableElement(), "mouseover", this._onTableHoverDelegate);
		
		this._onTableOutDelegate = Function.createDelegate(this, this._onTableOut);
		$telerik.addExternalHandler(this.get_tableElement(), "mouseout", this._onTableOutDelegate);
	
		
		this._onPropertyChangeDelegate = Function.createDelegate(this, this._onInputPropertyChange);
		$addHandler(this.get_inputDomElement(), "propertychange", this._onPropertyChangeDelegate);
		
		this._onFocusDelegate = Function.createDelegate(this, this._onFocus);
		$addHandler(this.get_inputDomElement(), "focus", this._onFocusDelegate);
		
		this._onDocumentClickDelegate = Function.createDelegate(this, this._onDocumentClick);
		
		// There is a bug in ASP.NET AJAX in IE6, the workaround is to attach the handler directly
		if($telerik.isIE)
		{
		    document.attachEvent("onmousedown",this._onDocumentClickDelegate);
		    document.attachEvent("oncontextmenu",this._onDocumentClickDelegate);
		}
		else
		{
			$addHandler(document, "mousedown", this._onDocumentClickDelegate);
			$addHandler(document, "contextmenu", this._onDocumentClickDelegate);
		}
		
		this._onDropDownScrollDelegate = Function.createDelegate(this, this._onDropDownScroll);
		$addHandler(this.get_childListElementWrapper(), "scroll", this._onDropDownScrollDelegate);
		
		this._eventMap.addHandlerForClassName("click", "rcbInput", this._onInputClick);	
		this._eventMap.addHandlerForClassName("keydown", "rcbInput", this._onKeyDown);
				
		if(!$telerik.isIE)
		    this._eventMap.addHandlerForClassName("input", "rcbInput", this._onInputChange);
		
		if(this.get_imageDomElement())
		{
		    this._onImageClickDelegate = Function.createDelegate(this, this._onImageClick);
		    $addHandler(this.get_imageDomElement(), "click", this._onImageClickDelegate);
		}
		
		this._onWindowResizeDelegate = Function.createDelegate(this, this._onWindowResize);
		$addHandler(window, "resize", this._onWindowResizeDelegate);
		
		this._onWindowUnloadDelegate = Function.createDelegate(this, this._onWindowUnload);
		$addHandler(window, "unload", this._onWindowUnloadDelegate);
		
		if (this._openDropDownOnLoad)
		{
			this._onOpenOnLoad = Function.createDelegate(this, this.showDropDown);
			$addHandler(window, "load", this._onOpenOnLoad);
		}
		
		if (this.get_moreResultsBoxElement())
		{
			this._onMoreResultsBoxClickDelegate = Function.createDelegate(this, this._onMoreResultsBoxClick);
			$addHandler(this.get_moreResultsBoxElement(), "click", this._onMoreResultsBoxClickDelegate);
			
			this._onMoreResultsBoxOverDelegate = Function.createDelegate(this, this._onMoreResultsBoxOver);
			$addHandler(this.get_moreResultsBoxElement(), "mouseover", this._onMoreResultsBoxOverDelegate);
			
			this._onMoreResultsBoxOutDelegate = Function.createDelegate(this, this._onMoreResultsBoxOut);
			$addHandler(this.get_moreResultsBoxElement(), "mouseout", this._onMoreResultsBoxOutDelegate);
		}
	
		//select the first match
		var item = this.findItemByText(this._text);
		if (item && !item.get_isSeparator())
		{
			this.set_selectedItem(item);
		}
		this._initializeAnimation();
		if (this._openDropDownOnLoad && !this.get_dropDownVisible())
		{
			this.showDropDown();
		}
		
		var me = this;
		
		Array.add(Telerik.Web.UI.RadComboBox.ComboBoxes, this);
		
		if(this._fireEvents)
		{
			this.raiseEvent("load", null);
		}
		
		// Set an expando property "value" in order to be validated correctly.
 		this.get_element().value = this._text;
 		
 		//set zIndex
 		var zIndex = this.get_element().style.zIndex;
 		var zDropDownIndex = this.get_dropDownElement().parentNode.style.zIndex;
 		if(zIndex == 0)
 		{
 			zIndex = zDropDownIndex;
 		}
 		
 		this.get_dropDownElement().parentNode.style.zIndex = zIndex;
	},
	
	_initializeAnimation: function()
	{
		var animatedElement = this._getAnimatedElement();

		if (animatedElement) 
		{
			this._slide = new Telerik.Web.UI.Slide(animatedElement, this.get_expandAnimation(), this.get_collapseAnimation());
			this._slide.initialize();
			this._slide.set_direction(this.get_slideDirection());
		}
		
		this._expandAnimationEndedDelegate = Function.createDelegate(this, this._onExpandAnimationEnded);
		this._slide.add_expandAnimationEnded(this._expandAnimationEndedDelegate);
		
		this._expandAnimationStartedDelegate = Function.createDelegate(this, this._onExpandAnimationStarted);
		this._slide.add_expandAnimationStarted(this._expandAnimationStartedDelegate);

	},
	
	_onExpandAnimationEnded : function (sender, e)
	{
		if(window.netscape && !window.opera)
		{
			this.get_childListElementWrapper().style.overflow = "auto";
			
			if(this.get_selectedItem())
			{   
				this.get_selectedItem().scrollOnTop();
			}
		}
	},
	
	_onExpandAnimationStarted : function (sender, e)
	{
		if(window.netscape && !window.opera)
		{
			this.get_childListElementWrapper().style.overflow = "hidden";
		}
	},
	
	_requiresRightToLeft : function ()
	{
		var currentElement = this.get_element();
		while (currentElement.nodeType !== 9)
		{
			if (currentElement.dir == "rtl")
				return true;
			
			currentElement = currentElement.parentNode;
		}
		return false;
	},
	
	_initRightToLeft : function ()
	{
		
		this._rightToLeft = true;
		if (this._skin)
		{
			
			this.get_element().className = String.format("{0} RadComboBox_{1}_rtl", 
				this.get_element().className, this._skin);
				
			this.get_dropDownElement().className = String.format("{0} RadComboBoxDropDown_{1}_rtl", this.get_dropDownElement().className,this._skin);
		}
		if(this.get_imageDomElement())
		{
			if (Sys.UI.DomElement.containsCssClass(this.get_imageDomElement().parentNode,"rcbArrowCellRight"))
			{
				this._replaceCssClass(this.get_imageDomElement().parentNode,"rcbArrowCellRight", "rcbArrowCellLeft");
				this.get_inputDomElement().parentNode.className= "rcbInputCell rcbInputCellRight";
			}
			else
			{
				this._replaceCssClass(this.get_imageDomElement().parentNode,"rcbArrowCellLeft", "rcbArrowCellRight");
				this.get_inputDomElement().parentNode.className= "rcbInputCell rcbInputCellLeft";
			}
		}
		
	},
	
	_replaceCssClass : function (element, oldClass, newClass)
	{
		element.className = element.className.replace(oldClass, newClass);
	},
	
	dispose : function ()
	{
		Array.remove(Telerik.Web.UI.RadComboBox.ComboBoxes, this);
		
		if (this._expandAnimationEndedDelegate) 
		{
			if (this._slide) 
			{
				this._slide.remove_expandAnimationEnded(this._expandAnimationEndedDelegate);
			}
			
			this._expandAnimationEndedDelegate = null;
		}
		
		if (this._expandAnimationStartedDelegate) 
		{
			if (this._slide) 
			{
				this._slide.remove_expandAnimationStarted(this._expandAnimationStartedDelegate);
			}
			
			this._expandAnimationStartedDelegate = null;
		}
		
		$removeHandler(window, "unload", this._onWindowUnloadDelegate);
		$removeHandler(window, "resize", this._onWindowResizeDelegate);
		$removeHandler(this.get_inputDomElement(), "propertychange", this._onPropertyChangeDelegate);
		$removeHandler(this.get_inputDomElement(), "focus", this._onFocusDelegate);
		
		if($telerik.isIE)
		{
		    document.detachEvent("onmousedown",this._onDocumentClickDelegate);
		    document.detachEvent("oncontextmenu",this._onDocumentClickDelegate);
		}
		else
		{
			$removeHandler(document, "mousedown", this._onDocumentClickDelegate);
			$removeHandler(document, "contextmenu", this._onDocumentClickDelegate);
		}
		if(this.get_childListElement())
		{
			$removeHandler(this.get_childListElement(), "click", this._onDropDownClickDelegate);
			$removeHandler(this.get_childListElement(), "mouseover", this._onDropDownHoverDelegate);
			$removeHandler(this.get_childListElement(), "mouseout", this._onDropDownOutDelegate);
		    $removeHandler(this.get_childListElement(), "selectstart", this._cancelDelegate);
			$removeHandler(this.get_childListElement(), "dragstart", this._cancelDelegate);
		}
		
		if(this.get_tableElement())
		{
			$removeHandler(this.get_tableElement(), "mouseover", this._onTableHoverDelegate);
			$telerik.removeExternalHandler(this.get_tableElement(), "mouseout", this._onTableOutDelegate);
		}
		
		if(this.get_imageDomElement())
		{
		    $removeHandler(this.get_imageDomElement(), "click", this._onImageClickDelegate);
		}
		
		if (this._openDropDownOnLoad)
		{
			$removeHandler(window, "load", this._onOpenOnLoad);
		}
		
		if (this.get_moreResultsBoxElement())
		{
			$removeHandler(this.get_moreResultsBoxElement(), "click", this._onMoreResultsBoxClickDelegate);
			$removeHandler(this.get_moreResultsBoxElement(), "mouseover", this._onMoreResultsBoxOverDelegate);
			$removeHandler(this.get_moreResultsBoxElement(), "mouseout", this._onMoreResultsBoxOutDelegate);
		}
		$removeHandler(this.get_childListElementWrapper(), "scroll", this._onDropDownScrollDelegate);
		
		if (this._slide) 
		{
			this._slide.dispose();
			this._slide = null;
		}
		this._removeDropDown();
		this._disposed = true;
		
		Telerik.Web.UI.RadComboBox.callBaseMethod(this, 'dispose');
		
		this._tableElement._events = null;
		this._inputDomElement._events = null;
		this._imageDomElement._events = null;
		this._childListElementWrapper._events = null;
	},
	
	_cancelEvent : function(e)
	{
	    e.preventDefault();
		return false;
	},
	
	_onDropDownScroll : function (e)
	{
		if(!this._virtualScroll || this._ajaxRequest ||this._endOfItems)
		{
			return;
		}
		var itemsCount = this.get_items().get_count();
		var itemHeight = 22;
		var itemScroll = 0;	
		
	    if(itemsCount > 0)
	    {
			itemHeight = this.get_items().getItem(0).get_element().offsetHeight;
			itemScroll = this.get_items().getItem(itemsCount-1).get_element().offsetTop;
	    }
		var emptyElement = $telerik.getFirstChildByTagName(this.get_childListElement(), "div",0);
		if(emptyElement)
		{
			var height = emptyElement.offsetHeight;
			if(this.get_childListElementWrapper().scrollTop + height>=this.get_childListElement().offsetHeight - height)
			{
				this.requestItems(this.get_text(), true);
			}
		}
		
	},
	
	_detachDropDown : function()
	{
		
		if ( (!document.readyState || document.readyState == "complete") && (!this._isDetached))
		{
			var parentElement = this._findParentForm();
			
			var dropDown = this.get_dropDownElement();
			var slide = this.get_dropDownElement().parentNode;
			slide.parentNode.removeChild(slide);
			slide.style.marginLeft = "0";
			
			parentElement.insertBefore(slide, parentElement.firstChild);
		    
			this._isDetached = true;
		}
	},
	
	_removeDropDown : function()
	{
		var slide = this.get_dropDownElement().parentNode;
		slide.parentNode.removeChild(slide);
		if (this._disposeChildElements)
		{
		    Sys.WebForms.PageRequestManager.getInstance()._destroyTree(slide);
		}
		
		if (!$telerik.isSafari)
			slide.outerHTML = null;
		this._dropDownElement = null;	  
	},
	
	//dropdown needs to be attached during ajax request in some cases(when the postbacks fires from templated item)
	attachDropDown : function()
	{
		var slide = this.get_dropDownElement().parentNode;
	    slide.parentNode.removeChild(slide);
	    this.get_tableElement().parentNode.appendChild(slide);  
	},
	_findParentForm : function()
	{
		var currentElement = this.get_element();
		while (currentElement.tagName.toLowerCase() != "form")
		{
			currentElement = currentElement.parentNode;
		}
		
		return currentElement;
	},
	
	_findNearestItem : function(element)
	{
		while (element.nodeType !== 9)
		{
			if (element._item && Telerik.Web.UI.RadComboBoxItem.isInstanceOfType(element._item))
			{
				return element._item ;
			}
			element = element.parentNode;
		}
		
		return null;
	},
	

	_positionDropDown : function()
	{
		this._detachDropDown();
		
		var startElement = this.get_element();
		var slide = this._getAnimationContainer();
		
		slide.style.position = "absolute";
		
		var position = $telerik.getLocation(startElement);
		
		var dropDown = this.get_dropDownElement();
		var dropDownWidth = this.get_element().offsetWidth;
	
		if(this._dropDownWidth)
		{
			dropDownWidth = this._dropDownWidth;
		}
		
		var childListElement = this.get_childListElement();
		
		var childListElementWrapper = this.get_childListElementWrapper();
		
	
		
		var slideTop = position.y + this.get_offsetY() + this.get_element().offsetHeight;
		
		slide.style.top = slideTop + "px";
		slide.style.left = position.x + this.get_offsetX()+ "px";
		
		if(this._rightToLeft && document.body.dir =="rtl")
		{
			slide.style.left = "";
			slide.style.left = position.x + this.get_offsetX() - this._getScrollBarWidth() + "px";
		}
		
		dropDown.style.display = "block";
		
		dropDown.style.width = dropDownWidth + "px";
		
		var difference = 0;
		
		if(!this._dropDownWidth)
		{
			difference = dropDown.offsetWidth - dropDownWidth;
		}
		
		
		if (difference > 0 && difference < dropDownWidth)
		{
			dropDown.style.width = dropDownWidth - difference + "px";
		}
	
		if (this._rightToLeft)
		{
			dropDown.dir = "rtl";
		}
		
		this._determineScreenBoundaryDetection();
		
	},
	
	
	_calculateDropDownAutoHeight : function()
	{
		var dropDown = this.get_dropDownElement();
		var animationContainer = this._getAnimationContainer();
		var position = $telerik.getLocation(this.get_element());
		var animationContainer = this._getAnimationContainer();
		var animationContainerPosition = $telerik.getLocation(animationContainer);
		var screenSize = $telerik.getViewPortSize();
        var y = position.y - dropDown.offsetHeight;
		var downSpace = screenSize.height - animationContainerPosition.y ;
		var upSpace = animationContainerPosition.y - this.get_element().offsetHeight;
		var height = downSpace;
		var additionalElements =false;
		var chHeight = 0;
		
		if(this._getHeaderElement())
		{
			chHeight = chHeight + this._getHeaderElement().offsetHeight;
			additionalElements = true;
		}
	
	    if(this._getFooterElement())
		{
			chHeight = chHeight + this._getFooterElement().offsetHeight;
			additionalElements = true;
		}
	
		if(this.get_moreResultsBoxElement())
		{
			chHeight = chHeight + this.get_moreResultsBoxElement().offsetHeight;
			additionalElements = true;
		}
		if(this._enableScreenBoundaryDetection && downSpace<upSpace)
		{
			height= upSpace;
		}
		if (!(height >=0 && (this.get_childListElement().offsetHeight + chHeight)  >=height))
		{
			height = this.get_childListElement().offsetHeight + chHeight;
		}
		
		if(additionalElements && chHeight < height )
		{
			this.get_childListElementWrapper().style.height = height - chHeight +"px";
		}
		else
		{
			this.get_childListElementWrapper().style.height = height + "px";
		}
		return height;
	},
	
	_determineScreenBoundaryDetection : function()
	{
		var dropDown = this.get_dropDownElement();
		var animationContainer = this._getAnimationContainer();
		var position = $telerik.getLocation(this.get_element());
		var animationContainer = this._getAnimationContainer();
		var animationContainerPosition = $telerik.getLocation(animationContainer);
		
		
			var screenSize = $telerik.getViewPortSize();
			var height =dropDown.offsetHeight;
			if(this._height == "" && this.get_childListElement())
			{
				height = this._calculateDropDownAutoHeight();
			}
			
			if(this._enableScreenBoundaryDetection)
			{
				if (this._elementOverflowsBottom(screenSize, dropDown, this.get_inputDomElement()))
				{
					var y = position.y - height;
					
					if (y >= 0)
					{
						this.set_slideDirection(Telerik.Web.UI.SlideDirection.Up);
						this._getAnimationContainer().style.height = this.get_dropDownElement().offsetHeight;
						this._getAnimationContainer().style.top = position.y - this.get_offsetY() - dropDown.offsetHeight + "px";
						if (window.netscape && !window.opera)
						{
							this._getAnimationContainer().style.top = position.y - this.get_offsetY() - dropDown.offsetHeight + 2 + "px";
						}
						if(this._height == "" && height==animationContainerPosition.y - this.get_element().offsetHeight )
						{
							this._getAnimationContainer().style.top = "0px";
						}
					}
					else
					{
						this.set_slideDirection(Telerik.Web.UI.SlideDirection.Down);
						
					}
	           }
	           else
			   {
					this.set_slideDirection(Telerik.Web.UI.SlideDirection.Down);
					
			   }
				
			}
		
		this.set_dropDownVisible(true);
		
	},
	_getScrollBarWidth : function()
	{
			var offsetWidth, clientWidth = 0;

			var outerDiv = document.createElement('div');
			outerDiv.style.position = 'absolute';
			outerDiv.style.top = '-1000px';
			outerDiv.style.left = '-1000px';
			outerDiv.style.width = '100px';
			outerDiv.style.height = '50px';
			outerDiv.style.overflow = 'hidden';

			var innerDiv = document.createElement('div');
			innerDiv.style.width = '100%';
			innerDiv.style.height = '200px';

			outerDiv.appendChild(innerDiv);
			document.body.appendChild(outerDiv);
			
			var widthNoScroll =	innerDiv.offsetWidth;
									
			outerDiv.style.overflow = 'auto';
			
			var widthScroll = innerDiv.offsetWidth;
			
			this._scrollbarWidth = widthNoScroll - widthScroll;					
			
			if(this._scrollbarWidth <= 0)
			{
				innerDiv.style.width = '300px';									
			
				offsetWidth = outerDiv.offsetWidth;

				clientWidth = outerDiv.clientWidth;
				
				this._scrollbarWidth = offsetWidth - clientWidth;
			}								
						    
			if(this._scrollbarWidth <= 0)
			{
				this._scrollbarWidth = 16;
			}
			
			document.body.removeChild(document.body.lastChild);
			return this._scrollbarWidth;
	},
	
	_elementOverflowsBottom : function (screenSize, element, startingElement)
	{
		var bottomEdge = $telerik.getLocation(startingElement).y + element.offsetHeight;		
		return bottomEdge > screenSize.height;
	},
	
	_selectFirstMatch : function()
	{
		var itemToSelect = this._findItemToSelect();
		
		if (itemToSelect && itemToSelect.get_enabled()&& !itemToSelect.get_isSeparator())
		{
			itemToSelect.highlight();
			itemToSelect.scrollOnTop();
			this.set_selectedItem(itemToSelect);
		}
	},
	
	_findItemToSelect : function ()
	{
		//Required to support multiple items with the same text.
		var itemToSelect = this.findItemByValue(this.get_value());
		
		if (!itemToSelect)
			itemToSelect = this.findItemByText(this.get_text());
		
		return itemToSelect;
	},
	
	
	clearItems : function() 
	{
		this.get_items().clear();
		this._itemData = null;
		
	},
	
	clearSelection : function()
	{
		this.set_text("");
		this.set_value("");
		this.set_selectedItem(null);
		this.set_highlightedItem(null);
	},
	
	decodeText :function (value)
    {
        var result = value;
        var escapedSymbols = {'&lt;':'<', '&gt;':'>', '&amp;':'&', '&quot;':'"'};

        for(var symbol in escapedSymbols)
        result = result.replace(new RegExp(symbol, 'g'), escapedSymbols[symbol]);

        return result;
    },
    
	_findNextAvailableIndex : function(index, letter)
	{
		var  items = this.get_visibleItems();
		
		for (var i = index; i < items.length; i++)
		{
			if (items[i].get_enabled()&& !items[i].get_isSeparator())
			{
				if(letter == null)
				{
					return i;
				}
				if(letter && items[i].get_text().indexOf(letter) == 0)
				{
					return i;
				}
			}
		}
		
		return items.length;
	},

	_findPrevAvailableIndex : function(index)
	{
		var  items = this.get_visibleItems();
		
		if (items.length < 1) return -1;
		
		for (var i = index; i >= 0; i--)
		{
			if ( items[i].get_enabled()&& !items[i].get_isSeparator())
			{
				return i;
			}
		}
		
		return -1;
	},
	_onDropDownClick : function (e)
	{
		if (!this._enabled) return;
		
		var item = this._findNearestItem(e.target);
		if (!item ||!item.get_enabled()||item.get_isSeparator()) return;
        this.get_inputDomElement().focus();
		this._hideDropDown(e);
		this._performSelect(item,e);
		    
	},
	
	_onDropDownHover : function (e)
	{
		if (!this._enabled ||this._ajaxRequest) return;
		
		var item = this._findNearestItem(e.target);
		
		if (!item ||!item.get_enabled()||item.get_isSeparator()) return;
		item.highlight();
	},
	
	_onDropDownOut : function (e)
	{
		if (!this._enabled) return;
		
		if (!e) e = event;
		var relatedTarget;
		try
		{
			relatedTarget = e.toElement ||e.relatedTarget || e.fromElement;	
			while (relatedTarget.nodeType !== 9)
			{
				if (relatedTarget.parentNode == this.get_dropDownElement())
				{
					return;
				}
				relatedTarget = relatedTarget.parentNode;
			}
		}
		catch (e)
		{
		}

		var highlightedItem = this.get_highlightedItem();
		if (highlightedItem)
		{
			highlightedItem.unHighlight();
		}
	},
	
	_onTableHover : function (e)
	{
		if (!this._enabled) return;
		
		var table = this.get_tableElement();
		if(table!=null && table.className!="rcbFocused")
		{
			table.className = "rcbHovered";
			
		}
	},
	
	
	_onTableOut : function (e)
	{
		if (!this._enabled) return;
		
		if (!e) e = event;
		var table = this.get_tableElement();
		var target =e.target ||e.srcElement;
		var relatedTarget = e.toElement ||e.relatedTarget || e.fromElement;
		
		while (relatedTarget && relatedTarget.nodeType !== 9)
		{
			if (relatedTarget.parentNode && relatedTarget.parentNode == table)
			{
				return ;
			}
			relatedTarget = relatedTarget.parentNode;
		}
		
		if(table!=null && table.className == "rcbHovered")
		{
			table.className = "";
		}
	},
	
	_onDocumentClick : function(e)
	{
		if (!e) e = event;
		
		var target = e.target || e.srcElement;
		
		while (target.nodeType !== 9)
		{
			if (target.parentNode == null ||target == this.get_element() || target == this.get_dropDownElement())
			{
				return;
			}
			target = target.parentNode;
		}
		
		if (this.get_dropDownVisible() && this.get_closeDropDownOnBlur())
		{
			this._hideDropDown(e);
		}
		if (this._focused)
		{
			this._raiseClientBlur(e);
			this._selectItemOnBlur(e);
			this._focused = false;
		}
	},

	_selectItemOnBlur : function (e)
	{
		var itemToSelect = this._findItemToSelect();
		if (!itemToSelect && !this.get_allowCustomText() && this.get_items().get_count() > 0)
		{
			if (this.get_markFirstMatch() )
			{
				if(this.get_text() == "")
				{
					this.set_text(this._originalText);
				}
				this.highlightMatches();
				
			    this.selectText(0, 0);
                
				itemToSelect = this.get_highlightedItem();
			}
			
		}
		if (!this.get_allowCustomText()&& !this.get_enableLoadOnDemand()&& this.get_filter()!=Telerik.Web.UI.RadComboBoxFilter.None)
		{
		
			itemToSelect = this.get_highlightedItem();
			if(this.get_highlightedItem()==null && this.get_selectedItem())
			{
			   itemToSelect =  this.get_selectedItem();
			}
			else if(!this.get_highlightedItem() && this.get_visibleItems().length > 0)
			{
			    itemToSelect = this.get_visibleItems()[0];
			}
		}
		
	   if (this.get_filter()!=Telerik.Web.UI.RadComboBoxFilter.None)
       {
           this.setAllItemsVisible(true);
       }
	   	
		this._performSelect(itemToSelect,e);
	},
	
	_onWindowResize : function ()
	{
		if (this.get_dropDownVisible())
		{
			this._positionDropDown();
			
		}
	},
	
	_onWindowUnload : function ()
	{
		this._disposeChildElements = false;
	},
	_onKeyDown : function (e)
	{
		if (!this._fireEvents || this._ajaxRequest) return;
		
		if (!e) e = event;
			
			this.raise_onClientKeyPressing(e);
			
			var keyCode = e.keyCode || e.which;

			this._lastKeyCode = keyCode;
			
			var letter = String.fromCharCode(keyCode);
			
			if (keyCode == Telerik.Web.UI.Keys.Escape && this.get_dropDownVisible())
			{
				if (this.get_dropDownVisible())
				{
					this._hideDropDown(e);
				}
				return;
			}
			else if (keyCode === Telerik.Web.UI.Keys.Enter)
			{
				if (this.get_dropDownVisible())
				{
					this._hideDropDown(e);
				}
				this._performSelect(this.get_highlightedItem(),e);
				e.returnValue = false;
				if (e.preventDefault)
				{
					e.preventDefault();
				}
				return;
			}
			else if (keyCode === Telerik.Web.UI.Keys.Down)
			{
				e.returnValue = false;
				if (e.altKey)
				{
					this._toggleDropDown(e);
					return;
				}
				this.highlightNextItem(null);
				if (e.preventDefault)
				{
					e.preventDefault();
				}
				return;
			}
			else if (keyCode === Telerik.Web.UI.Keys.Up)
			{
				e.returnValue = false;
				if (e.altKey)
				{
					this._toggleDropDown(e);
					return;
				}
				this.highlightPreviousItem();
				if (e.preventDefault)
				{
					e.preventDefault();
				}
				return;
			}
			else if (keyCode === Telerik.Web.UI.Keys.Tab)
			{ 
				if (this.get_dropDownVisible())
				{
					this._hideDropDown(e);
				}
				this._raiseClientBlur(e);
				this._selectItemOnBlur(e);
				this._focused = false;

				return;
			}
		
			if (keyCode == Telerik.Web.UI.Keys.Left || keyCode == Telerik.Web.UI.Keys.Right)
			{
				return;
			}
			
			if (letter && !(this.get_enableLoadOnDemand() ||!this.get_readOnly()))
			{
				this.highlightNextItem(letter);
				return;
			}
	},
	
	_onImageClick : function (e)
	{
		if (this._enabled)
		{
		    if(!this.get_dropDownVisible())
		    {
			    this._selectFirstMatch();
			}
			this._toggleDropDown(e);
		}
	},
	
	_onInputClick : function (e)
	{
		if (this._enabled)
		{
			this._selectFirstMatch();
			
			this.selectText(0, this.get_text().length);
            
			if (!this.get_dropDownVisible()&& this._showDropDownOnTextboxClick)
			{
				this._showDropDown(e);
			}
			return true;
		}
	},
	
	_onMoreResultsBoxClick : function (e)
	{
		this.requestItems(this.get_text(), true);
	},
	
	_onMoreResultsBoxOver : function (e)
	{
		this.get_moreResultsBoxElement().style.cursor = "pointer";
	},
	
	_onMoreResultsBoxOut : function (e)
	{
		this.get_moreResultsBoxElement().style.cursor = "default";
	},
	_onFocus : function (e)
	{
		if (this._focused)
			return;
		
		if (this.get_emptyMessage() && this.get_emptyMessage()== this.get_text())
		{	
			this._suppressChange =  true;
			this.get_inputDomElement().value = this._text;
			this.get_inputDomElement().className = "rcbInput";
			this._suppressChange =  false;
		}	
		
		var table = this.get_tableElement();
		if(table!=null)
		{
			table.className =  "rcbFocused";
		}
		
		if (!e) e = event;
		
		this._focused = true;
		
		this.raise_onClientFocus(e);
		return true;
	},
	
	_raiseClientBlur : function (e)
	{
		if (this._focused)
		{
			var table = this.get_tableElement();
			if(table!=null)
			{
				table.className =  "";
			}
			this._applyEmptyMessage();
			this.raise_onClientBlur(e);  
		}
	},
	
	_applyEmptyMessage: function()
	{
		if (this.get_emptyMessage() && this.get_text()=="")
		{
			this._suppressChange =  true;
			this.get_inputDomElement().value = this.get_emptyMessage();
			this.get_inputDomElement().className += " rcbEmptyMessage";
			this._suppressChange =  false;
		}	
	},
	
	
	_onInputChange : function()
	{ 
	   //Reset the value (required to support multiple items with the same text)
	    this.set_value("");
		
		var text = this.get_text();
		if( this.get_emptyMessage()!="" && text!=this.get_emptyMessage())
		{
			this._text = text;
		}
		
		// Set an expando property "value" in order to be validated correctly.
 		this.get_element().value = this._text;
 		
		this.updateClientState();
		if (this.get_enableLoadOnDemand() && !this._suppressChange)
		{
	 		var me = this;
		 	
	 		if (this._requestTimeoutID > 0)
 			{
 				window.clearTimeout(this._requestTimeoutID);
 				this._requestTimeoutID = 0;
 			}
 			if(!this._showDropDownOnTextboxClick )
			{
				this._skipLoadingItems = true;
			}
			if (!this.get_dropDownVisible())
			{
				this.showDropDown();
			}
		
			this._requestTimeoutID = window.setTimeout(function(){ if (me._disposed) {return;}me.requestItems(me.get_text(), false);}, me.get_itemRequestTimeout());
			return;
		}
		if (!this._suppressChange && this._shouldHighlight())
		{
			this.highlightMatches();
		}
		if (!this._suppressChange)
		{
		  this.highlightAllMatches(this.get_text());
		}
	},
	_onInputPropertyChange : function()
	{
	
		 if (event.propertyName == "value")
		{
			var text = this.get_text();
			if (this._cachedText != text)
			{
				this._cachedText = text;
				this._onInputChange();
			}
		}
		
	},
	
	_shouldHighlight : function()
	{
		if (this._lastKeyCode < Telerik.Web.UI.Keys.Space)
		{
			return false;
		}

		if (this._lastKeyCode >=  Telerik.Web.UI.Keys.PageUp && this._lastKeyCode <=  Telerik.Web.UI.Keys.Del)
		{
			return false;
		}
	
		if (this._lastKeyCode >=  Telerik.Web.UI.Keys.F1 && this._lastKeyCode <=  Telerik.Web.UI.Keys.F12)
		{
			return false;
		}
	
		return true;
	},
	
	_showDropDown : function(e)
	{	
		if (this.raise_dropDownOpening(e) == true )
		{
			return;
		}
		var animationContainer = this._getAnimationContainer();
		if (!animationContainer) 
		{
			return;
		}
		
		var text = this.get_text();
		if(this.get_emptyMessage()==this.get_text())
		{
			text = "";
		}
		if (this.get_enableLoadOnDemand()&& this.get_items().get_count() == 0 && !this._skipLoadingItems)
		{
			this.requestItems(text, false);
		}
		// Hide the animation container until its size is fixed.
		animationContainer.style.visibility = "hidden";
		this.get_dropDownElement().style.visibility = "hidden";
		this._slide.show();
		this._resetAnimatedElementPosition();	
		this._slide.set_direction(this.get_slideDirection());
		// Show the animation container after its size has been fixed.
		
		this.get_inputDomElement().focus();
		this._onFocus(e);
		
		
		this.set_dropDownVisible(true);
		
		this._positionDropDown();
		var dropDown =this.get_dropDownElement();
		dropDown.style.top = - dropDown.offsetHeight + "px";//position for animation
		this._slide.updateSize();
		animationContainer.style.visibility = "visible";
		
		this._slide.expand();
		this.raise_dropDownOpened(e);
	},
	
	_toggleDropDown: function(e)
	{
		if (this.get_dropDownVisible())
		{
			this._hideDropDown(e);
		}
		else
		{
			this._showDropDown(e);
			if (this.get_highlightedItem())
			{
				this.get_highlightedItem().scrollIntoView();
			}
		}
	},
	
	_hideDropDown: function(e)
	{ 
	   if (this.raise_dropDownClosing(e) == true)
	   {
			return;
	   }
	   
	   this.get_dropDownElement().style.display = "none";
   		
   		if (!this._getAnimationContainer()) 
		{
			return;
		}
		
	   this._slide.collapse();
	   this.set_dropDownVisible(false);
	   
	   if (this.get_filter()!=Telerik.Web.UI.RadComboBoxFilter.None)
	   {
	       this._removeEmTagsFromAllItems();
	   }
	   
	   this.raise_dropDownClosed(e);
	   
	},
	
	get_dropDownElement : function()
	{
		if(!this._dropDownElement)
		{
			this._dropDownElement = this._getChildElement("DropDown");
		}
		return this._dropDownElement;
	},
	
	get_inputDomElement : function()
	{
		if (!this._inputDomElement)
		{ 
			this._inputDomElement = this._getChildElement("Input");
		}
		return this._inputDomElement;
	},

	get_moreResultsBoxMessageElement : function()
	{
		var box = this.get_moreResultsBoxElement();
		var message = $telerik.getFirstChildByTagName(box, 
		"span", 0);
		return message;
	},
	
	 get_moreResultsBoxElement : function()
	{
		var box = this._getChildElement("MoreResultsBox");
		return box;
	},
	
	get_emptyMessage : function() 
    {
        return this._emptyMessage;
    },
    
    set_emptyMessage : function(value) 
    {
        if (this._emptyMessage !== value) 
        {
            this._emptyMessage = value;
        }
        this._applyEmptyMessage();
    },
    get_imageDomElement: function()
	{
		if (!this._imageDomElement)
		{ 
			this._imageDomElement = this._getChildElement("Arrow");
		}
		
		return this._imageDomElement;
	},
	
	get_slideDirection : function()
	{
		return this._slideDirection;
	},
	
	set_slideDirection : function(value)
	{
		this._slideDirection = value;
		this._slide.set_direction(value);
	},
	
	hideDropDown : function ()
	{ 
		this._hideDropDown(null);
	},

	showDropDown : function ()
	{ 
		this._showDropDown(null);
	},

	toggleDropDown : function ()
	{  
		this._toggleDropDown(null);
	},

	_resetAnimatedElementPosition : function ()
	{
		var animatedElement = this._getAnimatedElement();
		animatedElement.style.top = "0px";
		animatedElement.style.left = "0px";
	},
	
	get_readOnly : function ()
	{
	   return !(this.get_allowCustomText()|| this.get_markFirstMatch()) && this.get_filter()==Telerik.Web.UI.RadComboBoxFilter.None;
	}, 
	
	_performSelect : function (item, e)
	{   
		if(item && item != this.get_selectedItem() && !this.get_enableLoadOnDemand())
		{ 
			item._select(e);
			return;
		}
	    
		if (item && item == this.get_selectedItem() && this.getLastWord(this.get_text()) != item.get_text() && !this.get_readOnly())
		{
			this.set_text(item.get_text());
			return;
		}
	    
		if (item && item == this.get_selectedItem())
		{
			return;
		}
	    
		if (item && this.get_originalText() != item.get_text())
		{
			item._select(e);
			return;
		}
	    
		//Required to support multiple items with the same text load on demand
		if (item && (!this.get_selectedItem() || this.get_selectedItem().get_value() != item.get_value()))
		{
			item._select(e);
			return;
		}
		
		if (this.get_originalText() != this.get_text() )
		{
			if (this.get_highlightedItem())
			{
				this.get_highlightedItem().unHighlight();
			}
		    if(this.raise_textChange(this, e) == true)
		    {
                return;
            }
			var command = {Command:"TextChanged"};
			this.postback(command);
		}
	},

	
	set_value : function (value)
	{
		this._value = value;
		
		this.updateClientState();
	},

	get_value : function ()
	{
		return this._value;
	},

	set_text : function (value)
	{
		value = this.decodeText(value);// Set an expando property "value" in order to be validated correctly.
 		this.get_element().value = value;
 		
		this._suppressChange = true;
		var inputElement = this.get_inputDomElement();
		inputElement.value = value;
		this.set_value("");
		

		if (inputElement.fireEvent && document.createEventObject) 
		{
			var eventObject = document.createEventObject();
			inputElement.fireEvent("onchange", eventObject);
		} 
		else if (inputElement.dispatchEvent)
		{
			var canBubble = true;
			var eventObject = document.createEvent("HTMLEvents");
			eventObject.initEvent("change", canBubble, true);
			inputElement.dispatchEvent(eventObject);
		}
	    
		this._suppressChange = false;
		this._text = value;
		this.updateClientState();
    },
	
	get_webServiceSettings: function()
	{
		/// <exclude/>
		
		return this._webServiceSettings;
	},
	
	set_webServiceSettings: function(value)
	{
		/// <exclude/>
		
		var deserializedWebServiceSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings(deserializedWebServiceSettings);
	},

	get_text : function()
	{
		return this.get_inputDomElement().value;
	},

	enable : function()
	{
		this.get_inputDomElement().disabled = false;	
		var table = this.get_tableElement();
		if(table!=null)
		{
			table.className =  "";
		}		
		
		this.set_enabled(true);
		this.enableEvents()
		var itemCount = this._children.get_count();
		for (var i = 0; i < itemCount; i++)
		{
			this._children.getItem(i).enable();
		}
	},

	disable : function()
	{
		var table = this.get_tableElement();
		if(table!=null)
		{
			table.className =  "rcbDisabled";
		}		
		
		this.set_enabled(false);
		this.get_inputDomElement().disabled = "disabled";	
		this.disableEvents()
		var itemCount = this._children.get_count();
		for (var i = 0; i < itemCount; i++)
		{
			this._children.getItem(i).disable();
		}
	},
	
	set_enabled: function(value)
	{
		this._enabled = value;
		this.updateClientState();
	},
	
	get_enabled: function()
	{
		return this._enabled;
	},
	
	disableEvents: function()
	{
		this._fireEvents = false;
	},
	
	enableEvents: function()
	{
		this._fireEvents = true;
	},
	findItemByText : function(theText)
	{
		var items = this.get_items();
	    
		for (var i=0; i<items.get_count(); i++)
		{
			if (items.getItem(i).get_text() == theText)
			{
				return items.getItem(i);
			}
		}
		
		return null;
	},

	findItemByValue : function(theValue)
	{
		if (!theValue) return null;
		
		var items = this.get_items();
		
		for (var i=0; i < items.get_count(); i++)
		{
			if (items.getItem(i).get_value() == theValue)
			{
				return items.getItem(i);
			}
		}
		
		return null;
	},
	
	_getAnimationContainer: function()
	{
		if (!this._animationContainer) 
		{
			if(this.get_dropDownElement())
			{
				this._animationContainer = this.get_dropDownElement().parentNode;
			}
			
		}
		
		return this._animationContainer;
	},
	
	highlightPreviousItem : function ()
	{
		var items = this.get_visibleItems();
	    
		var currentItem = this.get_highlightedItem();
	    
		var proposedIndex = 0;
	    
		if (currentItem)
		{
		    var length = items.length;
			for (var i=0;  i < length; i++)
            {
                if(items[i]==currentItem)
                {
                    proposedIndex = i - 1;
                }
            }
			
		}
	    
		proposedIndex = this._findPrevAvailableIndex(proposedIndex);
	    
	   if (proposedIndex >= 0)
	   {
			items[proposedIndex].highlight();
			items[proposedIndex].scrollIntoView();
    		var lastSeparatorIndex = this._getLastSeparatorIndex(this.get_text());
			//Append the item text after the last separator
			var textToSet = this.get_text().substring(0, lastSeparatorIndex + 1) + items[proposedIndex].get_text();
		    if(this.get_changeText())
		    {
				this.set_text(textToSet);
				this.set_value(items[proposedIndex].get_value());
			}
			
	   }
	},

	highlightNextItem : function (letter)
	{
		var items = this.get_visibleItems();
		
		var currentItem = this.get_highlightedItem(); 
		var proposedIndex = 0;
	  
		if (currentItem)
		{
		    var length = items.length;
			for (var i=0;i < length; i++)
            {
                if(items[i]==currentItem)
                {
                    proposedIndex = i + 1;
                }
            }
		}
	    
		proposedIndex = this._findNextAvailableIndex(proposedIndex, letter);
	    if(letter && proposedIndex == items.length)
	    {
			proposedIndex = this._findNextAvailableIndex(0, letter);
	    }
		if (proposedIndex < items.length)
		{
			items[proposedIndex].highlight();
			items[proposedIndex].scrollIntoView();
			var lastSeparatorIndex = this._getLastSeparatorIndex(this.get_text());
			 //Append the item text after the last separator
			var textToSet = this.get_text().substring(0, lastSeparatorIndex + 1) +items[proposedIndex].get_text();
		   
			if(this.get_changeText())
		    {
				this.set_text(textToSet);
				this.set_value(items[proposedIndex].get_value());
			}
		}
    },

	findFirstMatch : function (text)
	{
		if (!text) return null;
		var items = this.get_items();
		
		for (var i = 0; i < items.get_count(); i++)
		{
			if (items.getItem(i).get_text().length < text.length)
			{
				continue;
			}
			
			if(items.getItem(i).get_enabled() == false ||items.getItem(i).get_isSeparator())
			{
				continue;
			}
				    
			var match = items.getItem(i).get_text().substring(0, text.length);
			
			if (!this.get_isCaseSensitive())
			{
				if (match.toLowerCase() == text.toLowerCase())
				{
					return items.getItem(i);
				}
			}
			else
			{
				if (match == text)
				{
					return items.getItem(i);
				}
			}
		}
			
		return	null;
	},
	
    highlightAllMatches : function(text)
	{
	    if (this.get_filter()== Telerik.Web.UI.RadComboBoxFilter.None) return;
	    
		if (this.get_highlightedItem())
		{
			this.get_highlightedItem().unHighlight();
		}

		var stext = this.getLastWord(text);
		
		if (this._getLastSeparator(text)== text.charAt(text.length - 1))
		{
		    this._removeEmTagsFromAllItems();
		    this.setAllItemsVisible(true);
			return;
		}
		this.get_items().forEach(function(item, text){ item._markText(stext); });
	},
	
	 setAllItemsVisible: function(value)
	{
	
	    var value = value;
		this.get_items().forEach(function(item){ item.set_visible(value); });
	},
	
	_removeEmTagsFromAllItems: function()
	{
	    if(this.get_isTemplated() || this.get_filter()== Telerik.Web.UI.RadComboBoxFilter.None)
	        return;
	        
		this.get_items().forEach(function(item){ item.set_text(item.get_text()); });
	},
	highlightMatches : function()
	{
		if (!this.get_markFirstMatch()) return;
	
		var text = this.get_text();
		var lastWord = this.getLastWord(text);
		
		if (this._getLastSeparator(text)== text.charAt(text.length - 1))
		{
			return;
		}
		
		var matchingItem = this.findFirstMatch(lastWord);
		
		if (this.get_highlightedItem())
		{
			this.get_highlightedItem().unHighlight();
		}

		if (!matchingItem)
		{
			if (!this.get_allowCustomText()&& !this.get_enableLoadOnDemand())
			{
				if (text)
				{
					var lastSeparatorIndex = this._getLastSeparatorIndex(text);
					if (lastSeparatorIndex < text.length - 1)
					{
						this.set_text(text.substring(0, text.length - 1));
						
						this.highlightMatches();
					}
				}
			}
			
			return;
		}
		matchingItem.highlight();
		matchingItem.scrollOnTop();
		
		var lastSeparatorIndex = this._getLastSeparatorIndex(text);
		var newText = text.substring(0, lastSeparatorIndex + 1) + matchingItem.get_text();
		
		if (text != newText)
		{
			this.set_text(newText);
		}
		
		this.set_value(matchingItem.get_value());
		
		var startIndex = lastSeparatorIndex + lastWord.length + 1;
		var endIndex = newText.length - startIndex;
					
		this.selectText(startIndex, endIndex);
        
	},
	
	postback : function (command)
	{
	   if (!this._postBackReference)
			return;
			
		var postbackFunction = this._postBackReference.replace("arguments", 
				Sys.Serialization.JavaScriptSerializer.serialize(command));
		
		eval(postbackFunction);
	},
	
	_getLastSeparator : function(text)
	{		
		if (!this.get_autoCompleteSeparator()) return null
	    
		var lastIndex = this._getLastSeparatorIndex(text);
		return text.charAt(lastIndex);
	},
	
	getLastWord : function(text)
	{
		var lastSeparatorIndex = -1;
		if (this.get_autoCompleteSeparator() != null)
		{
			lastSeparatorIndex = this._getLastSeparatorIndex(text);
		}		
		var lastWord = text.substring(lastSeparatorIndex+1, text.length);	
		return lastWord;
	},

	_getLastSeparatorIndex : function(text)
	{	
		var lastIndex = -1;	
		
		if (!this.get_autoCompleteSeparator()) return lastIndex;
		
		for (var i=0; i<this.get_autoCompleteSeparator().length;i++)
		{
			var currentSeparator = this.get_autoCompleteSeparator().charAt(i);		
			var currentIndex = text.lastIndexOf(currentSeparator);
			if (currentIndex > lastIndex && !this._checkIsThisPartOfWord(currentIndex,currentSeparator))
			{
			   		
				    lastIndex = currentIndex;
			    
			}
		}	
		
		return lastIndex;
	},
	
	_checkIsThisPartOfWord : function(index,currentSeparator)
	{
           var word = "";
           
           if(this.get_selectedItem())
           {
                word =this.get_selectedItem().get_text();
           }
        	
		    var currentIndex = word.lastIndexOf(currentSeparator);
		    if (currentIndex > -1 && currentIndex== index)
		    {			
			     return true;
		    }
		    
	    return false;	
	},

	selectText : function (startIndex, endIndex)
	{
	    if (!this.get_enableTextSelection())
	        return;
	     
		if (this.get_inputDomElement().createTextRange)
		{
			var textRange = this.get_inputDomElement().createTextRange();
		
			if (startIndex == 0 && endIndex == 0)
			{
				textRange.collapse(true);
				return;
			}
			textRange.moveStart("character", startIndex);
			textRange.moveEnd("character", endIndex);
			textRange.select();
		}
		else
		{
			this.get_inputDomElement().setSelectionRange(startIndex, startIndex + endIndex);
		}
	},
	
	
	_childRemoving : function (child)
	{
	 
		var index = child.get_index();
	    if(this._itemData)
        Array.remove(this._itemData,  this._itemData[index]);  
	
		Telerik.Web.UI.RadComboBox.callBaseMethod(this, "_childRemoving", [child]);
    },
	
	_childRemoved : function (item ,parent)
	{
	 
		var childElement = item.get_element();
		if (item == this.get_selectedItem())
		{
			this.set_selectedItem(null);
			this.set_highlightedItem(null);
			this.set_text("");
			
		}
		if( parent.get_items().get_count() == 0 && !this._getHeaderElement()&& !this._getFooterElement())
		{
			childElement = parent._childListElement;
			parent._childListElement = null;
			//parent.get_element().innerHTML = "";
		}
		if(childElement)
		{
			childElement.innerHTML = "";
			
			if (childElement.parentNode)
			{
				childElement.parentNode.removeChild(childElement);
			}
			childElement = null;
		}
		Telerik.Web.UI.RadComboBox.callBaseMethod(this, "_childRemoved", [item, parent]);
    },
    
    _childrenCleared: function(parent)
	{
		
		
		this.set_selectedItem(null);
		this.set_highlightedItem(null);
		
		var childListElement = parent.get_childListElement();
		if(childListElement && !this._getHeaderElement() && !this._getFooterElement())
		{
			for(var i = 0; i < parent.get_items().get_count(); i++)
			{
				parent.get_items().getItem(i)._dispose();
			}
			childListElement.innerHTML = "";
			childListElement = null;
		}
		else if(childListElement)
		{
			for(var i = 0; i < parent.get_items().get_count(); i++)
			{
				this._childRemoved(parent.get_items().getItem(i),parent);
			}
		}
	},
	
	_createChildControls : function ()
	{
		this._children = new Telerik.Web.UI.RadComboBoxItemCollection(this);
		Telerik.Web.UI.RadComboBox._createChildControls(this, this._children);
	},
	
	_createChildListElement : function ()
	{
		var childListElement = document.createElement("ul");
		childListElement.className = "rcbList";
		this.get_childListElementWrapper().appendChild(childListElement);
		
		this._onDropDownClickDelegate = Function.createDelegate(this, this._onDropDownClick);
		$addHandler(this.get_childListElement(), "click", this._onDropDownClickDelegate);
	
		this._onDropDownHoverDelegate = Function.createDelegate(this, this._onDropDownHover);
		$addHandler(this.get_childListElement(), "mouseover", this._onDropDownHoverDelegate);
		
		this._cancelDelegate = Function.createDelegate(this, this._cancelEvent);
		$addHandler(this.get_childListElement(), "selectstart", this._cancelDelegate);
		$addHandler(this.get_childListElement(), "dragstart", this._cancelDelegate);
						
		this._onDropDownOutDelegate = Function.createDelegate(this, this._onDropDownOut);
		$addHandler(this.get_childListElement(), "mouseout", this._onDropDownOutDelegate);
		
	},
	
	get_childListElement : function()
	{
		if (!this._childListElement)
		{ 
			var dropDownWrapper = this.get_childListElementWrapper();
			this._childListElement = $telerik.getFirstChildByTagName(dropDownWrapper, "ul", 0);
		}
		return this._childListElement;
	},
	
	get_childListElementWrapper : function()
	{
		if (!this._childListElementWrapper)
		{
			var wrapper = this.get_dropDownElement();
			if (this._getHeaderElement())
			{
				this._childListElementWrapper = $telerik.getFirstChildByTagName(wrapper, "div", 1);
			}
			else
			{
				this._childListElementWrapper = $telerik.getFirstChildByTagName(wrapper, "div", 0);
			}
		}
		return this._childListElementWrapper;
	},
	
	_getHeaderElement :function ()
	{
		if (this.get_dropDownElement())
		{
			return  $telerik.getChildByClassName(this.get_dropDownElement(),"rcbHeader",0);
		}
		
		return null;
	},
	
	_getFooterElement :function ()
	{
		if (this.get_dropDownElement())
		{
			return  $telerik.getChildByClassName(this.get_dropDownElement(),"rcbFooter",0);
		}
		
		return null;
	},
	
	get_tableElement : function ()
	{
	
		if (!this._tableElement)
		{ 
			this._tableElement = $telerik.getFirstChildByTagName(this.get_element(), "table", 0);
		}
		return this._tableElement;
	},
	
	get_expandAnimation: function()
	{
		/// <exclude/>
		
		return this._expandAnimation;
	},
	
	set_expandAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._expandAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	get_collapseAnimation: function()
	{
		/// <exclude/>
		
		return this._collapseAnimation;
	},
	
	set_collapseAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._collapseAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	_getAnimatedElement: function()
	{
		if (!this._animatedElement) 
		{
			this._animatedElement = this.get_dropDownElement();
		}
		
		return this._animatedElement;
	},
	
	get_items : function ()
	{
		return this._getChildren();
	},
	
	get_visibleItems : function ()
	{
	   var visibleItems = [];
		for (var i = 0; i < this._getChildren().get_count(); i++)
		{
			var item = this._getChildren().getItem(i);
			if (item.get_visible())
			{
			     Array.add(visibleItems, item);
			}
		}
		
		return visibleItems;
	},
	
	set_items : function(value)
	{
		this._children = value;
	},
	
	get_itemData : function ()
	{
		return this._itemData;
	},
	
	set_itemData: function (value)
	{
		this._itemData = value;
	},
	get_itemRequestTimeout : function ()
	{
		return this._itemRequestTimeout;
	},
	set_itemRequestTimeout : function (value)
	{
		this._itemRequestTimeout = value;
	},
	get_appendItems : function ()
	{
		return this._appendItems;
	},
	
	set_appendItems: function (value)
	{
		this._appendItems = value;
	},
	
	get_selectedItem : function ()
	{
		return this._selectedItem;
	},
	
	set_selectedItem: function (value)
	{
		this._selectedItem = value;
	},
	
	get_selectedIndex : function ()
	{	
		var selectedItem = this.get_selectedItem();
		if(selectedItem)
		{
			return selectedItem.get_index();
		}
		return this._selectedIndex;
	},
	
	set_selectedIndex: function (value)
	{
		this._selectedIndex = value;
	},
	get_causesValidation : function ()
	{
		return this._causesValidation;
	},
	
	set_causesValidation : function (value)
	{
		this._causesValidation = value;
	},
	get_closeDropDownOnBlur : function ()
	{
		return this._closeDropDownOnBlur;
	},
	
	set_closeDropDownOnBlur: function (value)
	{
		this._closeDropDownOnBlur = value;
	},
	get_isTemplated : function ()
	{
		return this._isTemplated;
	},
	
	set_isTemplated: function (value)
	{
		this._isTemplated = value;
	},
	
	get_highlightTemplatedItems : function ()
	{
		return this._highlightTemplatedItems;
	},
	
	set_highlightTemplatedItems: function (value)
	{
		this._highlightTemplatedItems = value;
	},
	
	get_enableLoadOnDemand : function ()
	{
		return this._enableLoadOnDemand;
	},
	
	set_enableLoadOnDemand: function (value)
	{
		this._enableLoadOnDemand = value;
	},
	
	get_enableItemCaching : function ()
	{
		return this._enableItemCaching;
	},
	
	set_enableItemCaching : function (value)
	{
		this._enableItemCaching = value;
	},
	
	get_allowCustomText : function ()
	{
		return this._allowCustomText;
	},
	
	set_allowCustomText: function (value)
	{
		this._allowCustomText = value;
	},

	get_changeText : function ()
	{
		return this._changeText;
	},
	
	set_changeText: function (value)
	{
		this._changeText = value;
	},
	get_markFirstMatch : function ()
	{
		return this._markFirstMatch;
	},
	
	set_markFirstMatch: function (value)
	{
		this._markFirstMatch = value;
	},
	
	
	get_filter : function ()
	{
		return this._filter;
	},
	
	set_filter: function (value)
	{
		this._filter = value;
	},
	
	get_enableTextSelection : function ()
	{
		return this._enableTextSelection;
	},
	
	set_enableTextSelection: function (value)
	{
		this._enableTextSelection = value;
	},
	get_originalText : function ()
	{
		return this._originalText;
	},
	
	set_originalText: function (value)
	{
		this._originalText = value;
	},
	
	get_highlightedItem : function ()
	{
		return this._highlightedItem;
	},
	
	set_highlightedItem: function (value)
	{
		this._highlightedItem = value;
	},
	
	get_isCaseSensitive :function ()
	{
	    return this._isCaseSensitive;
	},
	
	set_isCaseSensitive : function (value)
	{
	    this._isCaseSensitive = value;
	},
	
	get_dropDownVisible :function ()
	{
	    return this._dropDownVisible;
	},
	
	set_dropDownVisible : function (value)
	{
	    this._dropDownVisible = value;
	},
	
	get_autoCompleteSeparator :function ()
	{
	    return this._autoCompleteSeparator;
	},
	
	set_autoCompleteSeparator : function (value)
	{
	    this._autoCompleteSeparator = value;
	},
	
	get_showMoreMessage :function ()
	{
	    return this._showMoreMessage;
	},
	
	set_showMoreMessage : function (value)
	{
	    this._showMoreMessage = value;
	},
	
	get_loadingMessage :function ()
	{
	    return this._loadingMessage;
	},
	
	set_loadingMessage : function (value)
	{
	    this._loadingMessage = value;
	},
	
	get_errorMessage :function ()
	{
	    return this._errorMessage;
	},
	
	set_errorMessage : function (value)
	{
	    this._errorMessage = value;
	},
	
	set_endOfItems : function (value)
	{
	    this._endOfItems  = value;
	},
	
	get_endOfItems :function ()
	{
	    return this._endOfItems ;
	},
	
	get_clientDataString :function ()
	{
	    return this._clientDataString;
	},
	
	set_clientDataString : function (value)
	{
	   
	    this._clientDataString = value;
	},
	
	get_offsetX :function ()
	{
	    return this._offsetX;
	},
	
	set_offsetX : function (value)
	{
	    this._offsetX = value;
	},
	
	get_offsetY :function ()
	{
	    return this._offsetY;
	},
	
	set_offsetY : function (value)
	{
	    this._offsetY = value;
	},
	add_keyPressing : function (eventHandler)
	{
		this.get_events().addHandler("keyPressing", eventHandler);
	},
	remove_keyPressing : function (eventHandler)
	{
		this.get_events().removeHandler("keyPressing", eventHandler);
	},
	
	raise_keyPressing : function (eventArgs)
	{
		this.raiseEvent("keyPressing", eventArgs);
	},
	add_textChange : function (eventHandler)
	{
		this.get_events().addHandler("textChange", eventHandler);
	},
	remove_textChange : function (eventHandler)
	{
		this.get_events().removeHandler("textChange", eventHandler);
	},
	
	raise_textChange : function (eventArgs,e)
	{
	    var eventArgs = new Telerik.Web.UI.RadComboBoxCancelEventArgs(e);
		this.raiseEvent("textChange", eventArgs);
		return eventArgs.get_cancel();
	},
	add_selectedIndexChanging : function (eventHandler)
	{
		this.get_events().addHandler("selectedIndexChanging", eventHandler);
	},
	
	remove_selectedIndexChanging : function (eventHandler)
	{
		this.get_events().removeHandler("selectedIndexChanging", eventHandler);
	},
	
	raise_selectedIndexChanging : function (item, e)
	{
		var eventArgs = new Telerik.Web.UI.RadComboBoxItemCancelEventArgs(item, e);
		this.raiseEvent("selectedIndexChanging", eventArgs);
		return eventArgs.get_cancel();
	},
	
	add_selectedIndexChanged : function (eventHandler)
	{
		this.get_events().addHandler("selectedIndexChanged", eventHandler);
	},
	
	remove_selectedIndexChanged : function (eventHandler)
	{
		this.get_events().removeHandler("selectedIndexChanged", eventHandler);
	},
	
	raise_selectedIndexChanged : function (item, e)
	{
		var eventArgs = new Telerik.Web.UI.RadComboBoxItemEventArgs(item, e);
		this.raiseEvent("selectedIndexChanged", eventArgs);
	},
	
	add_itemsRequesting : function (eventHandler)
	{
		this.get_events().addHandler("itemsRequesting", eventHandler);
	},
	
	remove_itemsRequesting : function (eventHandler)
	{
		this.get_events().removeHandler("itemsRequesting", eventHandler);
	},
	
	add_itemsRequested : function (eventHandler)
	{
		this.get_events().addHandler("itemsRequested", eventHandler);
	},
	
	remove_itemsRequested : function (eventHandler)
	{
		this.get_events().removeHandler("itemsRequested", eventHandler);
	},
	
	raise_itemsRequested : function (text, e)
	{
		var eventArgs = new Telerik.Web.UI.RadComboBoxRequestEventArgs(text, e);
		this.raiseEvent("itemsRequested", eventArgs);
	},
	
	add_dropDownOpening : function (eventHandler)
	{
		this.get_events().addHandler("dropDownOpening", eventHandler);
	},
	
	remove_dropDownOpening : function (eventHandler)
	{
		this.get_events().removeHandler("dropDownOpening", eventHandler);
	},
	
	raise_dropDownOpening : function (e)
	{   
	    var eventArgs = new Telerik.Web.UI.RadComboBoxCancelEventArgs(e);
		this.raiseEvent("dropDownOpening", eventArgs);
		return eventArgs.get_cancel();
	},
	
	add_dropDownClosing : function (eventHandler)
	{
		this.get_events().addHandler("dropDownClosing", eventHandler);
	},
	
	remove_dropDownClosing : function (eventHandler)
	{
		this.get_events().removeHandler("dropDownClosing", eventHandler);
	},
	add_dropDownOpened : function (eventHandler)
	{
		this.get_events().addHandler("dropDownOpened", eventHandler);
	},
	
	remove_dropDownOpened : function (eventHandler)
	{
		this.get_events().removeHandler("dropDownOpened", eventHandler);
	},
	
	raise_dropDownOpened : function (e)
	{   
	    var eventArgs = new Telerik.Web.UI.RadComboBoxEventArgs(e);
		this.raiseEvent("dropDownOpened", eventArgs);
	},
	
	add_dropDownClosed : function (eventHandler)
	{
		this.get_events().addHandler("dropDownClosed", eventHandler);
	},
	
	remove_dropDownClosed : function (eventHandler)
	{
		this.get_events().removeHandler("dropDownClosed", eventHandler);
	},
	
	raise_dropDownClosed : function (e)
	{   
	    var eventArgs = new Telerik.Web.UI.RadComboBoxEventArgs(e);
		this.raiseEvent("dropDownClosed", eventArgs);
	},
	add_itemsRequestFailed : function (eventHandler)
	{
		this.get_events().addHandler("itemsRequestFailed", eventHandler);
	},
	
	remove_itemsRequestFailed : function (eventHandler)
	{
		this.get_events().removeHandler("itemsRequestFailed", eventHandler);
	},
	
	raise_itemsRequestFailed : function (text, errorMessage, e)
	{   
		 var eventArgs = new Telerik.Web.UI.RadComboBoxItemsRequestFailedEventArgs(text, errorMessage, e);
		 this.raiseEvent("itemsRequestFailed", eventArgs);
		 return eventArgs.get_cancel();
	},
	
	raise_dropDownClosing : function (e)
	{   
	    var eventArgs = new Telerik.Web.UI.RadComboBoxCancelEventArgs(e);
		this.raiseEvent("dropDownClosing", eventArgs);
		return eventArgs.get_cancel();
	},
	
	add_onClientFocus : function (eventHandler)
	{
		this.get_events().addHandler("onClientFocus", eventHandler);
	},
	
	remove_onClientFocus : function (eventHandler)
	{
		this.get_events().removeHandler("onClientFocus", eventHandler);
	},
	
	raise_onClientFocus : function (e)
	{  
		 var eventArgs = new Telerik.Web.UI.RadComboBoxEventArgs(e);
		 this.raiseEvent("onClientFocus", eventArgs);
	},
	
	add_onClientBlur : function (eventHandler)
	{
		this.get_events().addHandler("onClientBlur", eventHandler);
	},
	
	remove_onClientBlur : function (eventHandler)
	{
		this.get_events().removeHandler("onClientBlur", eventHandler);
	},
	
	raise_onClientBlur : function (e)
	{  
		var eventArgs = new Telerik.Web.UI.RadComboBoxEventArgs(e);
		this.raiseEvent("onClientBlur", eventArgs);
	},
	
	add_onClientKeyPressing : function (eventHandler)
	{
		this.get_events().addHandler("keyPressing", eventHandler);
	},
	
	remove_onClientKeyPressing : function (eventHandler)
	{
		this.get_events().removeHandler("keyPressing", eventHandler);
	},
	
	raise_onClientKeyPressing : function (e)
	{  
		var eventArgs = new Telerik.Web.UI.RadComboBoxEventArgs(e);
		this.raiseEvent("keyPressing", eventArgs);
	},
	add_load: function(handler)
	{
		this.get_events().addHandler("load", handler);
	},
	
	remove_load: function(handler)
	{
		this.get_events().removeHandler("load", handler);
	},
	
	_logInserted : function (item)
	{
		if (!item.get_parent()._childControlsCreated || !this._enableClientStatePersistence) return;
		
		this._log.logInsert(item);
	},

	saveClientState : function()
	{
		var logEntriesArray = this._log._logEntries;
		var clientState = 
		{
			logEntries: logEntriesArray,
			value:this._value,
			text:this._text,
			enabled:this._enabled
		};
		return Sys.Serialization.JavaScriptSerializer.serialize(clientState);
	},
	
	/*------- Load On Demand --------*/
    
    requestItems : function (text, appendItems)
    {   
        if (this._disposed) {return;}
		text = text.replace(/'/g,"&squote");
		text = encodeURIComponent(text);
		this._ajaxRequest = true;
		var userContext = { };
		this.set_appendItems(appendItems);
		
		userContext.NumberOfItems = 0;
		if(this.get_appendItems())
		{
			userContext.NumberOfItems = this.get_items().get_count(); 
		}
		userContext.Text = decodeURIComponent(text);
		
		var requestingEventArgs = new Telerik.Web.UI.RadComboBoxRequestCancelEventArgs(text, userContext);
		this.raiseEvent("itemsRequesting", requestingEventArgs);
		if (requestingEventArgs.get_cancel())
		{
            return;
        }
		if(this.get_highlightedItem())
		{
			 this.get_highlightedItem().unHighlight();
		}

       
        
		if (!this._loadingDiv)
		{
			this._loadingDiv = document.createElement("li");
			this._loadingDiv.className = "rcbLoading";
			this._loadingDiv.id = this.get_id() + "_LoadingDiv";
			this._loadingDiv.innerHTML = this.get_loadingMessage();
			if(! this.get_childListElement())
			{
				this._createChildListElement();
			}
			this.get_childListElement().insertBefore(this._loadingDiv, this.get_childListElement().firstChild);
		}
	
		this._callbacktext = text;
		if(this.get_webServiceSettings().get_method())
		{
			this._doLoadOnDemandFromWebService(text, userContext);
		}
		else
		{
			this._doLoadOnDemand(text, userContext);
		}
    },
    
    _doLoadOnDemand : function (text, userContext)
	{
	
		var numberOfItems = 0;
		if(this.get_appendItems())
		{
		  numberOfItems = this.get_items().get_count(); 
		}
		
		var command = {
			Command:"LOD",
			Text: text,
			ClientState: this._clientState,
			Context: userContext,
			NumberOfItems: numberOfItems
		};
		
		var onCallback = Function.createDelegate(this, this._onCallbackResponse);
		
		var onError = Function.createDelegate(this, this._onErrorReceived);
		
		if(this.get_enableItemCaching() && this.lodHashTable[text+"$"+numberOfItems]!=null)
		{
	    	this._onCallbackResponse(this.lodHashTable[text+"$"+numberOfItems]);
		}
		else
		{
		    WebForm_DoCallback(this._uniqueId, 
			Sys.Serialization.JavaScriptSerializer.serialize(command),
			onCallback, text, onError, true);
        }
	},
	
	_onCallbackResponse : function (response)
	{
	    if (this._disposed) {return;}
		this.set_selectedItem(null);
		this.set_highlightedItem(null);
		var oldLength = this._children.get_count();
		var text = this.get_text();
		var numberOfItems = 0;
		var receivedText = response.split("_$$_")[4];
		if (this._callbacktext != receivedText)
	    {  
	        this.requestItems(this._callbacktext, this.get_appendItems());
	        return;
	    }
	
		if(this.get_appendItems())
		{
		  numberOfItems = this.get_items().get_count(); 
		}
		if(this.get_enableItemCaching() && this.lodHashTable[text+"$"+numberOfItems]==null)
		{
	    	this.lodHashTable[text+"$"+numberOfItems] = response;
		}
		var responseComponents = response.split("_$$_");
		var receivedItemData;
		if (responseComponents[0] == "[]")
		{
			receivedItemData = null;
		}
		else
		{
			receivedItemData = eval(responseComponents[0]);
		}
		
		if(responseComponents[3] == "True")
		{
			this._endOfItems = true;
		}
		else
		{
		   this._endOfItems = false;
		}
		
		if(this.get_appendItems() && this._itemData && receivedItemData)
		{
			 Array.addRange(this._itemData, receivedItemData);
		}
		else
		{
			this._itemData = receivedItemData;
		}
		
		if (this._loadingDiv)
		{	
			if (this._loadingDiv.parentNode)
				this._loadingDiv.parentNode.removeChild(this._loadingDiv);
				
			this._loadingDiv = null;
		}
		
		var childListElement = this.get_childListElement();
		if (!childListElement)
		{
			childListElement = this._createChildListElement();
		}
		
		var oldInnerHTML = childListElement.innerHTML;
		
		var headerMessage = this._getHeaderElement();
		var footerMessage = this._getFooterElement();
		
		this._childControlsCreated = true;
	
		var emptyElement = $telerik.getFirstChildByTagName(childListElement, "div",0);
		if(emptyElement)
		{
			emptyElement.parentNode.removeChild(emptyElement);
		}
		
		if (this.get_appendItems())
		{
			var ulElement = document.createElement("ul");
			ulElement.innerHTML = responseComponents[1];
			var childElements = $telerik.getChildrenByTagName(ulElement, "li");
			
			var itemsLength = childElements.length;
		
			for (var i = 0; i < childElements.length; i++)
			{
				
				childListElement.appendChild(childElements[i]);
				this._childControlsCreated = false;
				var item = new Telerik.Web.UI.RadComboBoxItem();
				this._children.add(item);
				item._initialize(receivedItemData[i], childElements[i]);
			}	
			
			if(this._virtualScroll)
			{
				this._setUpScroll(this._endOfItems,childListElement);
			}
			
			if (this._children.getItem(oldLength+1) != null)
			{	
				if(this._virtualScroll)
				{
					this._virtualScroll = false;			
					this._children.getItem(oldLength+1).scrollIntoView();
					this._virtualScroll = true;
				}
			}
			
		}
		else
		{
			this._children.clear();
			
			if(headerMessage)
			{
				//childListElement.appendChild(headerMessage);
				childListElement.innerHTML = childListElement.innerHTML + responseComponents[1];
			}
			else
			{
				childListElement.innerHTML = responseComponents[1];
				
			}
		
			this._childControlsCreated = false;
		    this._createChildControls();
		    
		   if(this._virtualScroll)
			{
				this._setUpScroll(this._endOfItems,childListElement);
			}
		}
		
		if (this._showMoreResultsBox && this.get_moreResultsBoxMessageElement()) 
		{	
			this.get_moreResultsBoxMessageElement().innerHTML = responseComponents[2];
		}
		this.highlightMatches();
		this.highlightAllMatches(this.get_text());
		this.raise_itemsRequested(this.get_text(),null);
		
		if (this.get_dropDownVisible())
		{
			if (this._slide)
			{
				// Update the slide to account for the added items.
				this._slide.updateSize();
			}

			this._positionDropDown();
		}
		this._ajaxRequest = false;
	},
	
	_setUpScroll :function(endOfItems,childListElement)
	{
			var itemHeight = 22;
			
			var numberOfItems = this.get_items().get_count();
		    if(numberOfItems > 0)
		    {
				itemHeight = this.get_items().getItem(0).get_element().offsetHeight;
		    }
			if(endOfItems)
			{
				
				var emptyElement = $telerik.getFirstChildByTagName(childListElement, "div",0);
				if(emptyElement)
				{
					emptyElement.parentNode.removeChild(emptyElement);
				}
			}
			else
			{
		        var emptyElement = document.createElement("div");
				emptyElement.style.height = this.get_childListElementWrapper().offsetHeight +"px";
				childListElement.appendChild(emptyElement);
			}
	
	},
	
	_onErrorReceived : function (error, text)
	{
		if (this._requestTimeoutID > 0)
		{
			window.clearTimeout(this._requestTimeoutID);
			this._requestTimeoutID = 0;
		}
		
		var errorMessage = this._extractErrorMessage(error);
		
		if (this.raise_itemsRequestFailed(text, errorMessage,null) == true)
		{
			return;
		}
		
		alert(errorMessage);
	},

	_initializeWebServiceLoader : function()
	{
		this._webServiceLoader = new Telerik.Web.UI.WebServiceLoader(this.get_webServiceSettings());
		this._webServiceLoader.add_loadingSuccess(Function.createDelegate(this, this._onWebServiceResponse));
		this._webServiceLoader.add_loadingError(Function.createDelegate(this, this._onWebServiceError));
	},
	
	_doLoadOnDemandFromWebService : function (text, userContext)
	{
		if (!this._webServiceLoader)
		{
			this._initializeWebServiceLoader();
		}
		
        
		var params = { context: userContext };
		var numberOfItems = userContext.NumberOfItems;
		if(this.get_enableItemCaching() && this.lodHashTable[text +"$"+ numberOfItems]!=null)
		{
	    	this._addNewItems(text,this.lodHashTable[text+"$"+numberOfItems]);
		}
		else
		{  
		    this._webServiceLoader.loadData(params, text);
		}
	},
	
	_onWebServiceResponse : function (sender, eventArgs)
	{
		var response = eventArgs.get_data();
		var text = eventArgs.get_context();
		
		var numberOfItems = 0;
		if(this.get_appendItems())
		{
		  numberOfItems = this.get_items().get_count(); 
		};
		
		if (this._callbacktext != text)
	    {  
	        this.requestItems(this._callbacktext, this.get_appendItems());
	        return;
	    }
		if(this.get_enableItemCaching())
		    this.lodHashTable[text+"$"+numberOfItems] = response;
		    
		this._addNewItems(text,response)
	},

    _addNewItems : function (text, response)
	{
		this.set_selectedItem(null);
		this.set_highlightedItem(null);
		var oldLength = this.get_items().get_count();
		this._childControlsCreated = true;
		
		if (this._loadingDiv)
		{	
			if (this._loadingDiv.parentNode)
				this._loadingDiv.parentNode.removeChild(this._loadingDiv);
				
			this._loadingDiv = null;
		}
		
		var childListElement = this.get_childListElement();
		if (!childListElement)
		{
			childListElement = this._createChildListElement();
		}
		
		if (!this.get_appendItems())
		{
			this.clearItems();
		}
		
		if(this._virtualScroll)
		{	
			this._setUpScroll(true,childListElement);
		}
		var itemsArray = null;
		
		if(Array.prototype.isPrototypeOf(response))
		{
			itemsArray = response;
		
		}
		else
		{
		    itemsArray = response.Items;
		    this._endOfItems = response.EndOfItems;
		    this._showMoreMessage = response.Message;
		}
		for (var i = 0; i < itemsArray.length; i++)
		{
			var item = new Telerik.Web.UI.RadComboBoxItem();
			var data = itemsArray[i];
			item._loadFromDictionary(data);
			this._children.add(item);
		}
		
		if(this._virtualScroll)
		{	
			this._setUpScroll(this._endOfItems,childListElement);
		}
		
		if (this.get_appendItems())
		{
			
			if (this.get_items().getItem(oldLength+1) != null)
			{				
				this.get_items().getItem(oldLength+1).scrollIntoView();
			}
		}
		if (this._showMoreResultsBox && this.get_moreResultsBoxMessageElement()) 
		{	
			this.get_moreResultsBoxMessageElement().innerHTML = this.get_showMoreMessage();
		}
		this.raise_itemsRequested(text,null);
		
		if (this._shouldHighlight())
		{
			this.highlightMatches();
		}
		this.highlightAllMatches(this.get_text());
		if (this.get_dropDownVisible())
		{
			if (this._slide)
			{
				// Update the slide to account for the added items.
				this._slide.updateSize();
			}

			this._positionDropDown();
		}
		
	  this._ajaxRequest = false;
	},
	_onWebServiceError : function (sender, eventArgs)
	{
		var errorMessage = eventArgs.get_message();
		var text = eventArgs.get_context();
				
		this._onErrorReceived(errorMessage, text);
	}
}

Telerik.Web.UI.RadComboBox.registerClass('Telerik.Web.UI.RadComboBox', Telerik.Web.UI.ControlItemContainer);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadComboBoxItem = function()
{
	Telerik.Web.UI.RadComboBoxItem.initializeBase(this);
	
	this._highlighted =false;
	this._imageUrl = null;
	this._imageElement = null;
}

Telerik.Web.UI.RadComboBoxItem.prototype =
{
	_shouldInitializeChild : function (childNode)
	{
		return false;
	},

    get_text: function()
    {
        var text = Telerik.Web.UI.RadComboBoxItem.callBaseMethod(this, 'get_text');
        return this._removeEmTags(text);
    },

    get_baseText: function()
    {
        return Telerik.Web.UI.RadComboBoxItem.callBaseMethod(this, 'get_text');
     
    },

    _removeEmTags: function(text)
    {
        var indexEm=text.indexOf("<em>");
	    var indexEndEm=text.indexOf("</em>");
    	        
	    if(indexEm >= 0 && indexEndEm > indexEm)
	     {
	         text = String.format("{0}{1}{2}",text.substr(0,indexEm),text.substr(indexEm+4,indexEndEm-indexEm-4),text.substr(indexEndEm+5));  
	     }
	     return text;
    },

    set_visible: function(value)
    {
        var valueChanged = this.get_visible() != value;
		if (!valueChanged)
		{
			return;
		}
		
		Telerik.Web.UI.RadComboBoxItem.callBaseMethod(this, 'set_visible', [value]);
		if(value)
            this.get_element().style.display="";
        else
            this.get_element().style.display="none";
    },

	_markText : function(text)
	{
        var combo = this.get_comboBox();
        
	    var itemText = this.get_baseText();
	    var newText = this.get_text();
	    if (!combo.get_isTemplated())
        {
	        this.set_text(newText);
	    }
	    itemText =  newText;
	    var index = itemText.toLowerCase().indexOf(text.toLowerCase());
	    
	    var firstCondition = combo.get_filter()==Telerik.Web.UI.RadComboBoxFilter.Contains && index >= 0;
	    var secondCondition = combo.get_filter()==Telerik.Web.UI.RadComboBoxFilter.StartsWith && index == 0;
	    if(firstCondition ||secondCondition)
	    {
	        if(text!="" && !combo.get_isTemplated())
	        {
	            var newText = String.format("{0}<em>{1}</em>{2}",itemText.substr(0,index),itemText.substring(index,index+text.length),itemText.substr(index+text.length));
	            this.set_text(newText);
	        }
	        
	        this.set_visible(true);
	    }
	    else 
	    {
	        this.set_visible(false);
	    
	    }
	},
	
	_render : function (html)
	{
		html[html.length] = "<li class='";
		if (this.get_enabled())
		{
			if(this.get_isSeparator())
			{
				html[html.length] = "rcbItem rcbSeparator'>";
			}
			else
			{
				html[html.length] = "rcbItem'>";
			}
		}
		else
		{
			html[html.length] = "rcbDisabled'>";
		}
		if (this.get_imageUrl()) 
		{
			this._renderImage(html);
		}
		html[html.length] = this.get_text();
		html[html.length] = "</li>";
	},
	
	_renderImage: function(html)
	{
		html[html.length] = "<img alt='' src='" + this.get_imageUrl() + "' class='rcbImage'";
		
		if (!this.get_enabled()) 
		{
			html[html.length] = " disabled='disabled'";
		}
		
		html[html.length] = "/>";
		
		return html;
	},
	
	_updateImageSrc : function ()
	{
		var newSrc = this.get_imageUrl();
	
		
		if (!this.get_enabled() && this.get_disabledImageUrl())
		{
			newSrc = this.get_disabledImageUrl();
		}
			
		if (newSrc && this.get_element())
		{
			var imageElement = this.get_imageElement();		
			if (!imageElement)
			{
				imageElement = this._createImageElement();
			}

		    newSrc = newSrc.replace(/&amp;/ig, "&");
			if (newSrc != imageElement.src)
			{
				imageElement.src = newSrc;
			}
		}
	},

	_createImageElement : function()
	{
		this._imageElement = document.createElement("img");		
		this._imageElement.className = "rcbImage";	
		if (!this.get_enabled())
		{
			this._imageElement.disabled = "disabled";
		}
		
		var imageParent = this.get_element();
		if (imageParent.firstChild)
		{
			imageParent.insertBefore(this._imageElement, imageParent.firstChild);
		}
		else
		{
			imageParent.appendChild(this._imageElement);
		}
		
		return this._imageElement;
	},
	
	get_imageElement: function()
	{
		if (!this._imageElement)
		{
			
			var element = this.get_element();
			
			this._imageElement = $telerik.getFirstChildByTagName(element, "img", 0);
		}
		
		return this._imageElement;
	},
	get_disabledImageUrl : function ()
	{
		return this._properties.getValue("disabledImageUrl", null);
	},
	
	set_disabledImageUrl : function (value)
	{
		this._properties.setValue("disabledImageUrl", value, true);
		this._updateImageSrc();
	},
	
	get_imageUrl: function()
	{
		if(this._imageUrl = this._properties.getValue("imageUrl", null))
			return this._imageUrl;
	
		if (!this._imageUrl) 
		{
			var imageElement = this.get_imageElement();
			if (imageElement) 
			{
				this._imageUrl = imageElement.src;
			}
		}
		
		return this._imageUrl;
	},
	
	set_imageUrl : function (value)
	{
		this._imageUrl = value;
		this._properties.setValue("imageUrl", value, true);
		this._updateImageSrc();
	},
	get_value : function ()
	{
		return this._properties.getValue("value", "");
	},
	
	select : function ()
	{
		
		this._select(null);
	},
	
	hide: function()
	{
		this.set_visible(false);
	},
	
	show: function()
	{
		this.set_visible(true);
	},
	_select : function (e)
	{
		
		if (!this.get_isEnabled()|| this.get_isSeparator())
			return;
			
		var comboBox = this.get_comboBox();
	    if(comboBox.raise_selectedIndexChanging(this, e) == true)
		{
            return;
        }
        
        var text = comboBox.get_text();
        
		var lastSeparatorIndex = comboBox._getLastSeparatorIndex(text);
		//Append the item text after the last separator
		var textToSet = text.substring(0, lastSeparatorIndex + 1) + this.get_text();
		
		comboBox.set_text(textToSet);
		comboBox.set_originalText(textToSet);
		comboBox.set_value(this.get_value());
		comboBox.set_selectedItem(this);  
		comboBox.set_selectedIndex(this.get_index());
		this.highlight();
    
		comboBox.raise_selectedIndexChanged(this, e);
        var command = {Command:"Select",Index: this.get_index()};
        comboBox.postback(command);
	},
	_createChildControls : function ()
	{
		//this._items = this._createItemCollection();
	},
	
	unHighlight : function ()
	{   
	    var combobox = this.get_comboBox();
	    if (!combobox.get_isTemplated() || combobox.get_highlightTemplatedItems())
        {
            this._replaceCssClass(this.get_element(),"rcbHovered","rcbItem")	
	    }
    	
	    combobox.set_highlightedItem(null);
	    this.set_highlighted(false);
	},
	
	highlight : function ()
	{
	    if (!this.get_isEnabled()|| this.get_isSeparator())
			return;
			
		var combobox = this.get_comboBox();
	    if (!combobox.get_isTemplated() || combobox.get_highlightTemplatedItems())
        {
                var highlightedItem = combobox.get_highlightedItem();
                
		        if (highlightedItem)
		        {
			        highlightedItem.unHighlight();
		        }
    		    
                var element = this.get_element();
                
			    if (element)
			    {	
				    this._replaceCssClass(element,"rcbItem","rcbHovered")	
    			    
			    }
    		
        }
	    combobox.set_highlightedItem(this);
	    this.set_highlighted(true);
	},
	
	scrollOnTop : function ()
	{
		
		var itemScroll = this.get_element().offsetTop;
		var combo = this.get_comboBox();
		var header = combo._getHeaderElement();
		if(header)
		{
		  itemScroll= itemScroll - header.offsetHeight;
		}
		combo.get_childListElementWrapper().scrollTop = itemScroll;
	},
	
	scrollIntoView : function ()
	{
		var itemOffset = this.get_element().offsetTop;
		var itemHeight = this.get_element().offsetHeight;
		var dropDownWrapper = this.get_comboBox().get_childListElementWrapper();
		var dropDownOffset = dropDownWrapper.scrollTop;
		var dropDownVisibleHeight = dropDownWrapper.offsetHeight;
		
		if (itemOffset + itemHeight > dropDownOffset + dropDownVisibleHeight)
		{
			dropDownWrapper.scrollTop = itemOffset + itemHeight - dropDownVisibleHeight;
		}
		else if (itemOffset + itemHeight <= dropDownOffset)
		{
			dropDownWrapper.scrollTop = itemOffset;
		}
	},
	
	nextItem : function ()
	{
		return this.get_comboBox().get_items().getItem(this.get_index() + 1);
	},
	
	_replaceCssClass : function (element, oldClass, newClass)
	{
		element.className = element.className.replace(oldClass, newClass);
	},
	
	_createChildListElement : function ()
	{
		var childListElement = document.createElement("ul");
		this.get_combobox().get_dropDownElement().appendChild(childListElement);
		
	},	
	
	set_selected : function (value)
	{
		this._properties.setValue("selected", value);
	},
	
	get_selected : function ()
	{
		return this._properties.getValue("selected", false);
	},	
	
	set_highlighted : function (value)
	{
		this._highlighted = value;
	},
	
	get_highlighted : function ()
	{
		return this._highlighted;
	},
	
	disable: function()
	{
		this.set_enabled(false);
		this.get_element().className = "rcbDisabled";
	},
	
	enable: function()
	{
		this.set_enabled(true);
		this.get_element().className = "rcbItem";
	},

    set_enabled: function(value)
    {
        this._properties.setValue("enabled", value, true);
        this._updateImageSrc();
    },
    
	get_textElement : function ()
	{
		return this.get_element();
	},
	
	get_comboBox : function ()
	{
		return this._parent;
	},
	
	_getHierarchicalIndex : function()
	{
		return this.get_index();
	},	
	
	get_isSeparator: function()
	{
		return this._properties.getValue("isSeparator", false);
	},
	
	set_isSeparator : function (value)
	{
		this._properties.setValue("isSeparator", value, true);
		if(this.get_element())
	      Sys.UI.DomElement.toggleCssClass(this.get_element(),"rcbSeparator");
	}
}

Telerik.Web.UI.RadComboBoxItem.registerClass('Telerik.Web.UI.RadComboBoxItem', Telerik.Web.UI.ControlItem);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadComboBoxItemCollection = function (parent)
{
	Telerik.Web.UI.RadComboBoxItemCollection.initializeBase(this, [parent]);
}

Telerik.Web.UI.RadComboBoxItemCollection.prototype = 
{
}

Telerik.Web.UI.RadComboBoxItemCollection.registerClass("Telerik.Web.UI.RadComboBoxItemCollection", Telerik.Web.UI.ControlItemCollection);;
/* END Telerik.Web.UI.ComboBox.RadComboBoxScripts.js */
/* START Telerik.Web.UI.TreeView.RadTreeViewScripts.js */
Type.registerNamespace("Telerik.Web.UI");

// ---------- RadTreeNodeEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeEventArgs = function (node, domEvent)
{
	Telerik.Web.UI.RadTreeNodeEventArgs.initializeBase(this);
	this._node = node;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeNodeEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_domEvent : function ()
	{
	    return this._domEvent;
	}
}

Telerik.Web.UI.RadTreeNodeEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeEventArgs', Sys.EventArgs);

// ---------- RadTreeNodeCancelEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeCancelEventArgs = function (node, domEvent)
{
	Telerik.Web.UI.RadTreeNodeCancelEventArgs.initializeBase(this);
	this._node = node;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeNodeCancelEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_domEvent : function ()
	{
	    return this._domEvent;
	}
}
Telerik.Web.UI.RadTreeNodeCancelEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeCancelEventArgs', Sys.CancelEventArgs);

// ---------- RadTreeNodeErrorEventArgs Class -------------
Telerik.Web.UI.RadTreeNodeErrorEventArgs = function (node, errorMessage)
{
	Telerik.Web.UI.RadTreeNodeErrorEventArgs.initializeBase(this, [node]);
	this._errorMessage = errorMessage;
}

Telerik.Web.UI.RadTreeNodeErrorEventArgs.prototype = 
{
	get_errorMessage : function ()
	{
		return this._errorMessage;
	}
}

Telerik.Web.UI.RadTreeNodeErrorEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeErrorEventArgs', Telerik.Web.UI.RadTreeNodeCancelEventArgs);
// ---------- RadTreeNodeDraggingEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeDraggingEventArgs = function (node, domEvent)
{
	Telerik.Web.UI.RadTreeNodeDraggingEventArgs.initializeBase(this, [node, domEvent]);
}

Telerik.Web.UI.RadTreeNodeDraggingEventArgs.prototype = 
{
	get_htmlElement : function()
	{
		if (!this._domEvent)
			return null;
			
		return this._domEvent.target;
	}
}

Telerik.Web.UI.RadTreeNodeDraggingEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeDraggingEventArgs', Telerik.Web.UI.RadTreeNodeCancelEventArgs);

// ---------- RadTreeNodeDroppingEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeDroppingEventArgs = function (sourceNodes, destNode, htmlElement, dropPosition, domEvent)
{
    Telerik.Web.UI.RadTreeNodeDroppingEventArgs.initializeBase(this);
    this._sourceNodes = sourceNodes;
    this._destNode = destNode;
    this._htmlElement = htmlElement;
    this._dropPosition = dropPosition;
    this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeNodeDroppingEventArgs.prototype =
{
    get_sourceNodes : function ()
    {
        return this._sourceNodes;
    },
    
    get_sourceNode : function ()
    {
		return this._sourceNodes[0];
    },
    
    get_destNode : function ()
    {
        return this._destNode;
    },
    
    get_htmlElement : function ()
    {
        return this._htmlElement;
    },
    
    set_htmlElement : function (value)
    {
        this._htmlElement = value;
    },
    
    get_dropPosition : function ()
    {
        return this._dropPosition;
    },
    
    get_domEvent : function ()
    {
        return this._domEvent;
    }
}

Telerik.Web.UI.RadTreeNodeDroppingEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeDroppingEventArgs', Sys.CancelEventArgs);

// ---------- RadTreeNodeDroppedEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeDroppedEventArgs = function (sourceNodes, domEvent)
{
    Telerik.Web.UI.RadTreeNodeDroppedEventArgs.initializeBase(this);
    this._sourceNodes = sourceNodes;
    this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeNodeDroppedEventArgs.prototype = 
{
    get_sourceNodes : function()
    {
        return this._sourceNodes;
    },
    
    get_sourceNode : function ()
    {
		return this._sourceNodes[0];
    },
    
    get_domEvent : function ()
    {
        return this._domEvent;    
    }
}

Telerik.Web.UI.RadTreeNodeDroppedEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeDroppedEventArgs', Sys.EventArgs);

// ---------- RadTreeViewContextMenuEventArgs Class ----------
Telerik.Web.UI.RadTreeViewContextMenuEventArgs = function (node, menu, domEvent)
{
	Telerik.Web.UI.RadTreeViewContextMenuEventArgs.initializeBase(this);
	this._node = node;
	this._menu = menu;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeViewContextMenuEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_menu : function ()
	{
		return this._menu;
	},
	
	get_domEvent : function ()
	{
	    return this._domEvent;
	}
}
Telerik.Web.UI.RadTreeViewContextMenuEventArgs.registerClass('Telerik.Web.UI.RadTreeViewContextMenuEventArgs', Sys.EventArgs);

// ---------- RadTreeViewContextMenuCancelEventArgs Class ----------
Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs = function (node, menu, domEvent)
{
	Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs.initializeBase(this);
	this._node = node;
	this._menu = menu;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_menu : function()
	{
		return this._menu;
	},
	
	get_domEvent : function()
	{
		return this._domEvent;
	}
}

Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs.registerClass('Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs', Sys.CancelEventArgs);

// ---------- RadTreeViewContextMenuItemEventArgs Class ----------
Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs = function (node, menuItem, domEvent)
{
	Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs.initializeBase(this);
	this._node = node;
	this._menuItem = menuItem;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_menuItem : function ()
	{
		return this._menuItem;
	},
	
	get_domEvent : function ()
	{
	    return this._domEvent;
	}
}
Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs.registerClass('Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs', Sys.EventArgs);

// ---------- RadTreeViewContextMenuItemCancelEventArgs Class ----------
Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs = function (node, menuItem, domEvent)
{
	Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs.initializeBase(this);
	this._node = node;
	this._menuItem = menuItem;
	this._domEvent = domEvent;
}

Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs.prototype = 
{
	get_node : function ()
	{
		return this._node;
	},
	
	get_menuItem : function ()
	{
		return this._menuItem;
	},
	
	get_domEvent : function ()
	{
	    return this._domEvent;
	}
}
Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs.registerClass('Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs', Sys.CancelEventArgs);

// ---------- RadTreeNodeEditingEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeEditingEventArgs = function (node, text)
{
    Telerik.Web.UI.RadTreeNodeEditingEventArgs.initializeBase(this, [node]);
    this._newText = text;
}

Telerik.Web.UI.RadTreeNodeEditingEventArgs.prototype = 
{
    get_newText : function()
    {
        return this._newText;
    }
}

Telerik.Web.UI.RadTreeNodeEditingEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeEditingEventArgs', Telerik.Web.UI.RadTreeNodeCancelEventArgs);


// ---------- RadTreeNodePopulatingEventArgs Class ----------
Telerik.Web.UI.RadTreeNodePopulatingEventArgs = function(item, context)
{
	Telerik.Web.UI.RadTreeNodePopulatingEventArgs.initializeBase(this, [item]);

	this._context = context;
}

Telerik.Web.UI.RadTreeNodePopulatingEventArgs.prototype =
{
	get_context : function ()
	{
		return this._context;
	}
}
Telerik.Web.UI.RadTreeNodePopulatingEventArgs.registerClass('Telerik.Web.UI.RadTreeNodePopulatingEventArgs', Telerik.Web.UI.RadTreeNodeCancelEventArgs);

// ---------- RadTreeNodePopulatedEventArgs Class ----------
Telerik.Web.UI.RadTreeNodePopulatedEventArgs = function(item)
{
	Telerik.Web.UI.RadTreeNodePopulatedEventArgs.initializeBase(this, [item]);
}
Telerik.Web.UI.RadTreeNodePopulatedEventArgs.registerClass('Telerik.Web.UI.RadTreeNodePopulatedEventArgs', Telerik.Web.UI.RadTreeNodeEventArgs);


// ---------- RadTreeNodeDataBoundEventArgs Class ----------
Telerik.Web.UI.RadTreeNodeDataBoundEventArgs = function(node, dataItem)
{
	Telerik.Web.UI.RadTreeNodeDataBoundEventArgs.initializeBase(this, [node]);
	this._dataItem = dataItem;
}
Telerik.Web.UI.RadTreeNodeDataBoundEventArgs.prototype = 
{
	get_dataItem : function () 
	{
		return this._dataItem;
	}
}

Telerik.Web.UI.RadTreeNodeDataBoundEventArgs.registerClass('Telerik.Web.UI.RadTreeNodeDataBoundEventArgs', Telerik.Web.UI.RadTreeNodeEventArgs);


// ---------- RadTreeNodePopulationFailedEventArgs Class ----------
Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs = function(item, errorMessage)
{
	Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs.initializeBase(this, [item]);
	
	this._errorMessage = errorMessage;
}

Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs.prototype =
{
	get_errorMessage : function ()
	{
		return this._errorMessage;
	}
}
Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs.registerClass('Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs', Telerik.Web.UI.RadTreeNodeCancelEventArgs);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadTreeNode = function ()
{
	Telerik.Web.UI.RadTreeNode.initializeBase(this);
}

Telerik.Web.UI.RadTreeNode._fps = 60;

Telerik.Web.UI.RadTreeNode.prototype = 
{
	set_element: function(value)
	{
		this._element = value;
		this._element._item = this;
        this._element._itemTypeName = "Telerik.Web.UI.RadTreeNode";
	},
	
	get_navigateUrl : function()
	{
		if (this._navigateUrl !== null && typeof (this._navigateUrl) != "undefined") 
			return this._navigateUrl;

        if (this._navigateUrl = this._properties.getValue("navigateUrl", null))
            return this._navigateUrl;
		
		if (this.get_linkElement())
		    this._navigateUrl = this.get_linkElement().getAttribute("href", 2);
		
		return this._navigateUrl;
	},
	
	set_navigateUrl : function (value)
	{
		this._properties.setValue("navigateUrl", value, true);
		this._navigateUrl = value;
		if (this.get_linkElement())
			this.get_linkElement().href = value;
	},
	
	get_target : function ()
	{
		if (this._target !== null && typeof (this._target) != "undefined")
			return this._target;
		
		if (this._target = this._properties.getValue("target", null))
			return this._target;
			
		if (this.get_linkElement())
			this._target = this.get_linkElement().target;
		
		return this._target;
	},
	
	set_target : function (value)
	{
		this._properties.setValue("target", value);
		if (this.get_linkElement())
			this.get_linkElement().target = value;
	},
	
	get_checkable : function ()
	{
		return this._properties.getValue("checkable", true) == true;
	},
	
	set_checkable : function (value)
	{
	    this._properties.setValue("checkable", value, true);
	},
	
	get_linkElement : function ()
	{
		if (!this._linkElement)
		{
			var textElement = this.get_textElement();
			if (textElement && textElement.tagName.toLowerCase() == "a")
				this._linkElement = textElement;
		}
		return this._linkElement;
	},
	
	set_enabled : function (value)
	{
		Telerik.Web.UI.RadTreeNode.callBaseMethod(this, 'set_enabled', [value]);
		
		if (value)
		{
			this._removeClassFromContentElement("rtDisabled");
			this._removeClassFromContentElement(this.get_disabledCssClass());
			if (this.get_selected())
			{
				this._addClassToContentElement("rtSelected");
				this._addClassToContentElement(this.get_selectedCssClass());
			}
		}
		else
		{
			this._addClassToContentElement("rtDisabled");
			this._addClassToContentElement(this.get_disabledCssClass());
			if (this.get_selected())
			{
				this._removeClassFromContentElement("rtSelected");
				this._removeClassFromContentElement(this.get_selectedCssClass());
			}
		}
		
		if (this.get_checkBoxElement())
		{
			this.get_checkBoxElement().disabled = !value;
		}
		
		this._updateImageUrl();
	},
	
	get_disabledImageUrl : function ()
	{
	    if(this._disabledImageUrl) return this._disabledImageUrl;
	    
	    if(this._disabledImageUrl = this._properties.getValue("disabledImageUrl", null))
	        return this._disabledImageUrl;
	        
	    this._disabledImageUrl = this._getCurrentImageUrl();

		return this._disabledImageUrl;
	},
	
	set_disabledImageUrl : function (value)
	{
		this._disabledImageUrl = value;
		this._properties.setValue("disabledImageUrl", value, true);
		this._updateImageUrl();		
	},
	
	get_expandedImageUrl : function ()
	{
	    if (this._expandedImageUrl) return this._expandedImageUrl;
	    
	    if (this._expandedImageUrl = this._properties.getValue("expandedImageUrl", null))
	        return this._expandedImageUrl;
	    
	    this._expandedImageUrl = this._getCurrentImageUrl();
	
	    return this._expandedImageUrl;
	},
	
	set_expandedImageUrl : function (value)
	{
	    this._expandedImageUrl = value;	    	
	    this._properties.setValue("expandedImageUrl", value, true);
		this._updateImageUrl();
	},
	
	get_selectedImageUrl : function ()
	{
		if (this._selectedImageUrl) return this._selectedImageUrl;
		
		if (this._selectedImageUrl = this._properties.getValue("selectedImageUrl", null))
		    return this._selectedImageUrl;
		    		    
        this._selectedImageUrl = this._getCurrentImageUrl();
		return this._selectedImageUrl;
	},
	
	set_selectedImageUrl : function (value)
	{
		this._selectedImageUrl = value;
		this._properties.setValue("selectedImageUrl", value, true);
		this._updateImageUrl();
	},
	
	get_imageUrl: function()
	{
	    if(this._imageUrl) return this._imageUrl;
	    
	    if(this._imageUrl = this._properties.getValue("imageUrl", null))
	        return this._imageUrl;
	    
	    this._imageUrl = this._getCurrentImageUrl();
	    return this._imageUrl;	     	    
	},
	
	set_imageUrl: function(value)
	{
	    this._imageUrl = value;
		this._properties.setValue("imageUrl", value, true);
		this._updateImageUrl();
	},
		
	get_hoveredImageUrl : function ()
	{
		return this._properties.getValue("hoveredImageUrl", null);
	},
	
	set_hoveredImageUrl : function (value)
	{
	    this._properties.setValue("hoveredImageUrl", value, true);
		this._updateImageUrl();
	},
	
	get_checkState : function ()
	{
		var checkBoxElement = this.get_checkBoxElement();
		if (!checkBoxElement) return this.get_checked() ? Telerik.Web.UI.TreeNodeCheckState.Checked :
			Telerik.Web.UI.TreeNodeCheckState.Unchecked;
		
		switch (checkBoxElement.className)
		{
			case "rtChecked":
				return Telerik.Web.UI.TreeNodeCheckState.Checked;
			case "rtIndeterminate":
				return Telerik.Web.UI.TreeNodeCheckState.Indeterminate;
			case "rtUnchecked":
				return Telerik.Web.UI.TreeNodeCheckState.Unchecked;
		}
		
		return this.get_checked() ? Telerik.Web.UI.TreeNodeCheckState.Checked :
			Telerik.Web.UI.TreeNodeCheckState.Unchecked;
	},
	
	_updateParentCheckState : function (treeView)
	{
		var parent = this.get_parent();
		while (parent != treeView)
		{
			parent._refreshCheckState(treeView);
			parent = parent.get_parent();
		}
	},
	
	_refreshCheckState : function (treeView)
	{
		var checkState = this._calculateCheckState();
		var checkBoxElement = this.get_checkBoxElement();
		var checked = checkState != Telerik.Web.UI.TreeNodeCheckState.Unchecked;
		
		this._setChecked(treeView, checked);
		
		if (checkBoxElement)
			checkBoxElement.className = this._getCssClassForCheckState(checkState);
	},
	
	_getCssClassForCheckState : function (state)
	{
		switch (state)
		{
			case Telerik.Web.UI.TreeNodeCheckState.Checked:
				return "rtChecked";
			case Telerik.Web.UI.TreeNodeCheckState.Indeterminate :
				return "rtIndeterminate"
			case Telerik.Web.UI.TreeNodeCheckState.Unchecked:
				return "rtUnchecked";
		}
	},
	
	_calculateCheckState : function ()
	{
		var children = this.get_nodes();
		var childCount = children.get_count();
		
		if (childCount == 0)
			return this.get_checkState();

		var checkedCount = 0;
		var indetermCount = 0;
		
		for (var i = 0; i < childCount; i++)
		{
			var childNode = children.getNode(i);
			var childState = childNode.get_checkState();
			if (childState == Telerik.Web.UI.TreeNodeCheckState.Checked)
			{
				checkedCount++;
			}
			else if (childState == Telerik.Web.UI.TreeNodeCheckState.Indeterminate)
			{
				indetermCount++;
			}
		}
		
		var state = Telerik.Web.UI.TreeNodeCheckState.Unchecked;
		if (checkedCount == childCount)
		{
			state = Telerik.Web.UI.TreeNodeCheckState.Checked;
		}
		else if (checkedCount + indetermCount > 0)
		{
			state = Telerik.Web.UI.TreeNodeCheckState.Indeterminate;
		}

		return state;
	},
	
	_getCurrentImageUrl : function ()
	{
		var imageUrl = null;
		var imageElement = this.get_imageElement();
		if (imageElement) 
		{
			imageUrl = imageElement.src;
		}
		return imageUrl;
	},
	
	_getImageUrlToApply : function ()
	{
		var url = this.get_imageUrl();
		//Required when the expandedImageUrl is not serialized but rendered
		var expandedUrl = this.get_expandedImageUrl();
		//Required when the disabledImageUrl is not serialized but rendered
		var disabledUrl = this.get_disabledImageUrl();
		//Required when the selectedImageUrl is not serialized but rendered
		var selectedUrl = this.get_selectedImageUrl();
		
		if (this.get_expanded() && expandedUrl)
			url = expandedUrl;
		
		if (this._highLighted && this.get_hoveredImageUrl())
			url = this.get_hoveredImageUrl();
		
		if (this.get_selected() && selectedUrl)
			url = selectedUrl;
		
		if (!this.get_enabled() && disabledUrl)
			url = disabledUrl;
		
		return url;
	},
	
	_updateImageUrl : function ()
	{
		if (!this.get_element())
			return;
			
		var url = this._getImageUrlToApply();
		
		if (!url) return;
		
		var image = this.get_imageElement();
		if (!image)
		{
			image = this._createImageElement();
		}
		image.src = url;
	},
	
	_createImageElement : function()
	{
		this._imageElement = document.createElement("img");
		this._imageElement.className = "rtImg";
		var contentElement = this.get_contentElement();
		contentElement.insertBefore(this._imageElement, this.get_textElement());
		return this._imageElement;
	},
	
	get_category : function ()
	{
		return this._properties.getValue("category", null);
	},
	
	set_category : function (value)
	{
		this._properties.setValue("category", value, true);
	},
	
	get_cssClass : function ()
	{
		return this._properties.getValue("cssClass", null);
	},
	
	set_cssClass : function (value)
	{
		this._removeClassFromTextElement(this.get_cssClass());
		this._properties.setValue("cssClass", value, true);
		this._addClassToTextElement(value);
	},
	
	get_disabledCssClass : function()
	{
		return this._properties.getValue("disabledCssClass", null)
	},
	
	set_disabledCssClass : function(value)
	{
        this._properties.setValue("disabledCssClass", value, true);
	},
	
	get_selectedCssClass : function()
	{
		return this._properties.getValue("selectedCssClass", null);
	},
	
	set_selectedCssClass : function(value)
	{
		this._properties.setValue("selectedCssClass", value, true);
	},
	
	get_hoveredCssClass : function()
	{
		return this._properties.getValue("hoveredCssClass", null);
	},
	
	set_hoveredCssClass : function(value)
	{
		this._properties.setValue("hoveredCssClass", value, true);
	},
	
	get_childListElement : function()
	{
		if (!this._nodeListElement)
		{
			var element = this.get_element();
			if (!element) return null;
			this._nodeListElement = $telerik.getFirstChildByTagName(element, "ul", 1);
		}
		return this._nodeListElement;
	},
	
	get_contentElement : function ()
	{
		if (!this._contentElement)
		{
			var element = this.get_element();
			if (!element) return null;
			
			this._contentElement = $telerik.getFirstChildByTagName(element, "div", 0);
		}
		return this._contentElement;
	},
	
	get_contextMenuID : function()
	{
		return this._properties.getValue("contextMenuID", "");
	},
	
	get_resolvedContextMenuID : function()
	{
		if (!this._resolvedContextMenuID)
		{
			this._resolvedContextMenuID = this.get_treeView()._resolveContextMenuID(this.get_contextMenuID());
		}
		return this._resolvedContextMenuID;
	},
	
	set_contextMenuID : function(contextMenuID)
	{
		this._properties.setValue("contextMenuID", contextMenuID, true);
		this._resolvedContextMenuID = null;
		this._contextMenu = null;
	},
	
	get_textElement : function ()
	{
		if (!this._textElement)
		{
			var contentElement = this.get_contentElement();
			if (!contentElement) return null;
			
			this._textElement = $telerik.getChildByClassName(contentElement, "rtIn", 0);
		}
		return this._textElement;
	},
	
	get_toggleElement : function ()
	{
		if (!this._toggleElement)
		{
			var contentElement = this.get_contentElement();
			if (!contentElement) return null;
			
			this._toggleElement = $telerik.getChildByClassName(contentElement, "rtPlus", 0);
			if (!this._toggleElement)
			{
				this._toggleElement = $telerik.getChildByClassName(contentElement, "rtMinus", 0);
			}
		}
		return this._toggleElement;
	},
	
	get_inputElement : function ()
	{
	    return this._inputElement;
	},
	
	get_checkBoxElement : function ()
	{
		if (!this._checkBoxElement)
		{
			var contentElement = this.get_contentElement();
			if (!contentElement)
				return null;
			this._checkBoxElement = $telerik.getChildByClassName(contentElement, "rtChk", 0);
			
			//Tri-state
			if (!this._checkBoxElement)
			{
				this._checkBoxElement = $telerik.getChildByClassName(contentElement, "rtChecked") ||
					$telerik.getChildByClassName(contentElement, "rtUnchecked") ||
					$telerik.getChildByClassName(contentElement, "rtIndeterminate");
			}
			//Form decorator
			if (!this._checkBoxElement)
			{
				var inputElements = $telerik.getChildrenByTagName(contentElement, "input");
				for (var i = 0, l = inputElements.length; i < l; i++)
				{
					if (inputElements[i].type === "checkbox")
					{
						this._checkBoxElement = inputElements[i];
						break;
					}
				}
			}
		}
		return this._checkBoxElement;
	},
	
	get_imageElement : function ()
	{
		if (!this._imageElement)
		{
			var contentElement = this.get_contentElement();
			if (!contentElement)
				return null;
				
			this._imageElement = $telerik.getChildByClassName(contentElement, "rtImg", 0);
		}
		return this._imageElement;
	},
	
	get_previousNode : function ()
	{
		return this.get_previousSibling();
	},
	
	get_nextNode : function ()
	{
		return this.get_nextSibling();
	},
	
	expand : function ()
	{
		this.set_expanded(true);
	},
	
	collapse : function ()
	{
		this.set_expanded(false);
	},

	toggle : function ()
	{
		this.set_expanded(!this.get_expanded());
	},
	
	highlight : function ()
	{
		this._highlight();
	},
	
	unhighlight : function ()
	{
		this._unhighlight();
	},
	
	select : function ()
	{
		this.set_selected(true);
		var treeView = this.get_treeView();
		treeView._postClickCommand(this);
	},
	
	unselect : function ()
	{
		this.set_selected(false);
	},
	
	enable : function ()
	{
		this.set_enabled(true);
	},
	
	disable : function ()
	{
		this.set_enabled(false);
	},
	
	check : function ()
	{
		this.set_checked(true);
	},
	
	uncheck : function ()
	{
		this.set_checked(false);
	},
	
	startEdit : function ()
	{
		this._startEdit();
	},
	
	endEdit : function ()
	{
		this._endEdit(true);
	},
	
	scrollIntoView : function ()
	{
		var treeView = this._getControl();
		
		if(treeView)
		{
		    treeView._scrollToNode(this);
		}
	},
	
	_showContextMenu : function(domEvent)
	{
	    var contextMenu = this.get_contextMenu();
		if (contextMenu && this.get_enableContextMenu())
		{
			contextMenu.show(domEvent);
		}
	},

	_shouldInitializeChild : function (childNode)
	{
	    return true;
	},
	
	_highlight : function ()
	{
		if (!this.get_isEnabled())
			return;
		
		this._addClassToContentElement("rtHover");
		this._addClassToContentElement(this.get_hoveredCssClass());
		this._highLighted = true;
		this._updateImageUrl();
	},
	
	_unhighlight : function ()
	{
		this._removeClassFromContentElement("rtHover");
		this._removeClassFromContentElement(this.get_hoveredCssClass());
		this._highLighted = false;
		this._updateImageUrl();
	},
	
	_getChildElements : function()
	{
		return $telerik.getChildrenByTagName(this.get_childListElement(), "li");
	},
	
	get_contextMenu : function()
	{
		if (!this._contextMenu)
		{
			if (this.get_contextMenuID() == "")
			{
				var treeViewContextMenus = this.get_treeView().get_contextMenuIDs();
				if (treeViewContextMenus.length == 0)
				{
					return null;
				}
				var contextMenu = $find(this.get_treeView()._resolveContextMenuID(treeViewContextMenus[0]));
				if (!contextMenu)
				{
					//Try finding the context menu by ClientID:
					var contextMenu = $find(treeViewContextMenus[0]);
				}
				this._contextMenu = contextMenu;
			}
			else
			{
				this._contextMenu = $find(this.get_resolvedContextMenuID());
			}
		}
		return this._contextMenu;
	},
	
	get_enableContextMenu : function ()
	{
	    return this._properties.getValue("enableContextMenu", true);
	},
	
	set_enableContextMenu : function (value)
	{
	    this._properties.setValue("enableContextMenu", value, true);
	},
	
	_initialize : function (json, element)
	{	    
		Telerik.Web.UI.ControlItem.prototype._initialize.apply(this, arguments);
	
		if (this.get_expanded())
			this._ensureChildControls();
			
		this._animationEndedDelegate = Function.createDelegate(this, this._animationEnded);
	},
	
	_initializeRenderedItem : function ()
	{
	    Telerik.Web.UI.RadTreeNode.callBaseMethod(this, '_initializeRenderedItem');
	
	    this._animationEndedDelegate = Function.createDelegate(this, this._animationEnded);
	},
	
	showLoadingStatus : function (text, position)
	{
		this._loadingStatusElement = document.createElement("span");
		if (position == Telerik.Web.UI.TreeViewLoadingStatusPosition.BeforeNodeText)
		{
			this._loadingStatusElement.className = "rtLoadingBefore";
			this.get_textElement().insertBefore(this._loadingStatusElement,
				this.get_textElement().firstChild);
		}
		else if (position == Telerik.Web.UI.TreeViewLoadingStatusPosition.AfterNodeText)
		{
			this._loadingStatusElement.className = "rtLoadingAfter";
			this.get_textElement().appendChild(this._loadingStatusElement);
		}else if (position == Telerik.Web.UI.TreeViewLoadingStatusPosition.BelowNodeText)
		{
			this._loadingStatusElement.className = "rtLoadingBelow";
			this.get_textElement().appendChild(this._loadingStatusElement);
		}
		
		this._loadingStatusElement.innerHTML = text;
	},
	
	get_loadingStatusElement : function ()
	{
		return this._loadingStatusElement;
	},
	
	hideLoadingStatus : function ()
	{
		if (!this._loadingStatusElement)
			return;
		this._loadingStatusElement.parentNode.removeChild(this._loadingStatusElement);
		this._loadingStatusElement = null;
	},
	
	get_postBack : function ()
	{
	    return this._properties.getValue("postBack", true) == true;
	},
	
	set_postBack : function (value)
	{
	    this._properties.setValue("postBack", value);
	},
	
	get_expandMode : function()
	{
		return this._properties.getValue("expandMode", Telerik.Web.UI.TreeNodeExpandMode.ClientSide);
	},
	
	set_expandMode : function(value)
	{
        this._properties.setValue("expandMode", value, true);
        if (value != Telerik.Web.UI.TreeNodeExpandMode.ClientSide)
        {
			if (!this.get_toggleElement() && this.get_element())
				this._createToggleElement();
        }
	},
	
	_getData: function()
	{
	    var data = this._properties._data;
	    
	    var disabledImageUrl = this._properties.getValue("disabledImageUrl", null)
	    if(disabledImageUrl !== null)
	        data["disabledImageUrl"] = disabledImageUrl;
	    
	    var expandedImageUrl = this._properties.getValue("expandedImageUrl", null)
	    if(expandedImageUrl !== null)
	        data["expandedImageUrl"] = expandedImageUrl;
	        
	    if(this.get_hoveredImageUrl() !== null)
	        data["hoveredImageUrl"] = this.get_hoveredImageUrl();
	    
	    var selectedImageUrl = this._properties.getValue("selectedImageUrl", null)
	    if(selectedImageUrl !== null)
	        data["selectedImageUrl"] = selectedImageUrl;
	    
	    if(this.get_imageUrl() !== null)
	        data["imageUrl"] = this.get_imageUrl();

        if(this.get_navigateUrl() !== null)
	        data["navigateUrl"] = this.get_navigateUrl();
	    
	    data["text"] = this.get_text();
	    
  		if (this.get_attributes().get_count() > 0)
		{
			data["attributes"] = this.get_attributes()._data;
		}
		
		delete data.items;
				
		return data;
	},	
	
	_createItemCollection : function ()
	{
		var items = new Telerik.Web.UI.RadTreeNodeCollection(this);
		Telerik.Web.UI.RadTreeView._createNodesFromJson(this, items);
		
		return items;
	},
	
	_hasChildren : function ()
	{
	    return (this.get_nodes().get_count() > 0);
	},

    get_nextVisibleNode : function ()
    {
        if(this.get_nodes().get_count() > 0 && this.get_expanded())
        {
            return this.get_nodes().getNode(0);
        }
        
        var nextSibling = this.get_nextNode();
        if(nextSibling) return nextSibling;
        
	    var parent = this.get_parent();
	    while (parent && !Telerik.Web.UI.RadTreeView.isInstanceOfType(parent))
	    {
	        var nextParentSibling = parent.get_nextNode();
		    if (nextParentSibling)
			    return nextParentSibling;
		    
		    parent = parent.get_parent();
	    }
	    
	    return null;
    },

    get_prevVisibleNode : function ()
    {
	    var prevSibling = this.get_previousNode();
    	
	    if (prevSibling)
	    {
		    if (prevSibling.get_nodes().get_count() > 0 && prevSibling.get_expanded())
		    {
		        return prevSibling.get_lastVisibleChild();
		    }
    		
		    return this.get_previousNode();
	    }
	    
	    var parent = this.get_parent();
	    if (parent && !Telerik.Web.UI.RadTreeView.isInstanceOfType(parent))
	    {
		    return parent;
	    }
    	
	    return null;
    },
    
    get_lastVisibleChild : function ()
    {                
        var lastNode = this.get_lastChild();
        
        while(lastNode._hasChildren() && lastNode.get_expanded())
        {
            lastNode = lastNode.get_lastChild();
        }
        
        return lastNode;        
    },
    
    _getNextSelectableNode : function ()
    {
        var nextVisibleNode = this.get_nextVisibleNode();
        
        while (nextVisibleNode && !nextVisibleNode.get_enabled())
        {
            nextVisibleNode = nextVisibleNode.get_nextVisibleNode();
        }
        
        return nextVisibleNode;
    },

    _getPrevSelectableNode : function ()
    {
        var prevVisibleNode = this.get_prevVisibleNode();
        
        while (prevVisibleNode && !prevVisibleNode.get_enabled())
        {
            prevVisibleNode = prevVisibleNode.get_prevVisibleNode();
        }
        
        return prevVisibleNode;
    },
    
    get_lastChild : function ()
    {
        if(this._hasChildren())
        {
            return this.get_nodes().getNode(this.get_nodes().get_count() - 1);
        }
        
        return null;
    },
	
	get_nodeData : function ()
	{
		return this.get_itemData();
	},
	
	get_selected : function ()
	{
		return this._properties.getValue("selected", false) == true;
	},
	
	set_selected : function (value)
	{
	    if (!this.get_isEnabled()) return;
	    
	    if(this.get_selected() == value) return;
	
		this._properties.setValue("selected", value);
		
		var treeView = this.get_treeView();
		if (!treeView)
			return;
					
		if (value)
		{
			if(!treeView.get_multipleSelect())
			{
				treeView._clearSelectedNodes();
			}
			
			if(!this._editing)
			{
			    this.get_treeView()._endEdit(false);
			}
		
			this._select(treeView);			
		}
		else
		{
			this._unselect(treeView);
		}
		
		this._updateImageUrl();
	},
	
	_loadFromDictionary : function (data)
	{
		Telerik.Web.UI.RadTreeNode.callBaseMethod(this, '_loadFromDictionary', [data]);
		
		if (typeof(data.ExpandMode) != "undefined")
		{
			this.set_expandMode(data.ExpandMode);
		}
		
		if (typeof(data.NavigateUrl) != "undefined" && data.NavigateUrl)
		{
			this.set_navigateUrl(data.NavigateUrl);
		}
		
		if (typeof(data.PostBack) != "undefined" && !data.PostBack)
		{
			this.set_postBack(data.PostBack);
		}		
			
		if (typeof(data.CssClass) != "undefined" && data.CssClass)
		{
			this.set_cssClass(data.CssClass);
		}
		
		if (typeof(data.DisabledCssClass) != "undefined" && data.DisabledCssClass)
		{
			this.set_disabledCssClass(data.DisabledCssClass);
		}
		
		if (typeof(data.SelectedCssClass) != "undefined" && data.SelectedCssClass)
		{
			this.set_selectedCssClass(data.SelectedCssClass);
		}
		
		if (typeof(data.HoveredCssClass) != "undefined" && data.HoveredCssClass)
		{
			this.set_hoveredCssClass(data.HoveredCssClass);
		}
		
		if (typeof(data.ImageUrl) != "undefined" && data.ImageUrl)
		{
			this.set_imageUrl(data.ImageUrl);
		}
		
		if (typeof(data.HoveredImageUrl) != "undefined" && data.HoveredImageUrl)
		{
			this.set_hoveredImageUrl(data.HoveredImageUrl);
		}
		
		if (typeof(data.DisabledImageUrl) != "undefined" && data.DisabledImageUrl)
		{
			this.set_disabledImageUrl(data.DisabledImageUrl);
		}
		
		if (typeof(data.ExpandedImageUrl) != "undefined" && data.ExpandedImageUrl)
		{
			this.set_expandedImageUrl(data.ExpandedImageUrl);
		}

		if (typeof(data.ContextMenuID) != "undefined" && data.ContextMenuID !== null)
		{
			this.set_contextMenuID(data.ContextMenuID);
		}
	},
	
	_startEdit : function ()
	{
	    var treeView = this._getControl();
	
	    if(treeView)
	    {
		    treeView._editing = true;
	        treeView._editNode = this;	
	    }
	
	    this._editing = true;
		this._originalText = this.get_text();
		
		var innerElement = this.get_textElement();
		this._originalTextHtml = innerElement.innerHTML;
		innerElement.innerHTML = "";		
			
		var inputElement = document.createElement("input");	
		inputElement.setAttribute("type","text");
		inputElement.setAttribute("size", this._originalText.length + 3);	
		inputElement.setAttribute("value", Telerik.Web.UI.RadTreeView._htmlDecode(this._originalText));
		
		this._inputElement = inputElement;
		
		this._addClassToContentElement("rtEdit");
		innerElement.appendChild(inputElement);
		
		var nodeInstance = this;
		inputElement.onblur = function() { nodeInstance._endEdit(false); };
		inputElement.onchange = function()	{ nodeInstance._endEdit(false); };

		inputElement.focus();
		
		this._cancelInputEvents(inputElement);		
		this._selectInputText(inputElement, this._originalText.length);
	},
	
	_endEdit : function (cancel)
	{
	    this._editing = false;
	    var inputElement = this.get_inputElement();
	    var inputParent = inputElement.parentNode;
	    
	    inputParent.removeChild(inputElement);

	    if(!cancel)
	    {
	        var newText = Telerik.Web.UI.RadTreeView._htmlEncode(inputElement.value);
	        var escapedOriginalText = Telerik.Web.UI.RadTreeView._regExEscape(this._originalText);
	        escapedOriginalText = Telerik.Web.UI.RadTreeView._htmlEncode(escapedOriginalText);
            var regEx = new RegExp(escapedOriginalText, "g");
	        var updatedHtml = this._originalTextHtml.replace(regEx, newText);
	        inputParent.innerHTML = updatedHtml; 
	        
	        var shouldPostback = this._originalText != inputElement.value;
	        
	        if( !this.get_treeView()._editNodeText(this, newText, shouldPostback) )
	        {
	            inputParent.innerHTML = this._originalTextHtml;
	        }
	    }
	    else
	    {
	        inputParent.innerHTML = this._originalTextHtml;
	    }
	    
	    this._clearEdit();
	},
	
	_clearEdit : function ()
	{
	    this._removeClassFromContentElement("rtEdit");
	    this.get_treeView()._clearEdit();
	    this._originalText = null;
	    this._originalTextHtml = null;
		this._inputElement.onblur = null;
		this._inputElement.onchange = null;
	    this._inputElement = null;
	},
	
	_selectInputText : function (inputElement, textLength)
	{
		var startIndex = 0;
		var endIndex = textLength;
		if (inputElement.createTextRange)
		{
			var textRange = inputElement.createTextRange();
			textRange.moveStart("character", startIndex);
			textRange.moveEnd("character", endIndex);
			textRange.select();
		}
		else
		{
			inputElement.setSelectionRange(startIndex, endIndex);
		}	    
	},
	
	_cancelInputEvents : function (inputElement)
	{
	    inputElement.onselectstart = inputElement.onmousedown = inputElement.onmouseup = inputElement.onclick = function(e)
		{
			if (!e) e = window.event;
			if (e.stopPropagation)
			{
				e.stopPropagation();
			}
			else
			{
				e.cancelBubble = true;
			}		    
		};
	},
	
	_select : function (treeView)
	{
		treeView._registerSelectedNode(this);
		this._addClassToContentElement("rtSelected");
		this._addClassToContentElement(this.get_selectedCssClass());
	},
	
	_unselect : function (treeView)
	{
		treeView._unregisterSelectedNode(this);
		this._removeClassFromContentElement("rtSelected");
		this._removeClassFromContentElement(this.get_selectedCssClass());
	},
	
	_addClassToContentElement : function (className)
	{
		if (!className) return;
		var contentElement = this.get_contentElement();
		if (contentElement)
			Sys.UI.DomElement.addCssClass(contentElement, className);
	},
	
	_removeClassFromContentElement : function (className)
	{
		if (!className) return;
		var contentElement = this.get_contentElement();
		if (contentElement)
			Sys.UI.DomElement.removeCssClass(contentElement, className);
	},
	
	_addClassToTextElement : function (className)
	{
		if (!className) return;
		var textElement = this.get_textElement();
		if (textElement)
			Sys.UI.DomElement.addCssClass(textElement, className);
	},
	
	_removeClassFromTextElement : function (className)
	{
		if (!className) return;
		var textElement = this.get_textElement();
		if (textElement)
			Sys.UI.DomElement.removeCssClass(textElement, className);
	},	
	
	_displayChildren : function (show)
	{    
		var nodeList = this.get_childListElement();
		if (!nodeList) return;

		if (this._animation)
		{
			this._animation.stop();
		}
		
		nodeList.style.height = "auto";
		nodeList.style.overflow = "hidden";

		var treeView = this.get_treeView();
		if (show)
		{
			// Hide the node list.
			nodeList.style.visibility = "hidden";
			nodeList.style.position = "absolute";
			nodeList.style.display = "";

			// Record its height and set it to 1px to avoid flicker.
			// The initial height should be 1px instead of 0px to prevent a flicker in IE6 Quirks Mode
			var height = nodeList.offsetHeight;
			nodeList.style.height = "1px";
			nodeList.style.position = "static";
			
			this._expanding = true;
			var expandAnimation = treeView.get_expandAnimation();
			if (expandAnimation.get_type() != Telerik.Web.UI.AnimationType.None)
			{
			    // Again, the initial height is set to 1px instead of 0px to prevent a flicker in IE6 Quirks Mode
				this._playAnimation(treeView.get_expandAnimation(), 1, height);
			}
			else
			{			    
			    this._playAnimation(treeView.get_expandAnimation(), height, height);
			}
		}
		else
		{
			this._expanding = false;
			var collapseAnimation = treeView.get_collapseAnimation();
			if (collapseAnimation.get_type() != Telerik.Web.UI.AnimationType.None)
			{
				this._playAnimation(treeView.get_collapseAnimation(), nodeList.offsetHeight, 1);
			}
			else
			{
				this._animationEnded();
			}
		}
	},

	_playAnimation: function(animationSettings, startHeight, finalHeight)
	{
		var duration = animationSettings.get_duration();
		var points = Telerik.Web.UI.AnimationFunctions.CalculateAnimationPoints(animationSettings, startHeight, finalHeight, Telerik.Web.UI.RadTreeNode._fps);
		var animatedElement = this.get_childListElement();
		
		for (var i = 0; i < points.length; i++)
		{
			points[i] = Math.max(0, parseInt(points[i])) + "px";
		}

		// Show the animatedElement after the calculations have been done.		
		animatedElement.style.visibility = "";
		
		if (this._animation)
		{
			this._animation.set_duration(duration / 1000);
			this._animation.set_values(points);
		}
		else
		{
			this._animation = new $TWA.DiscreteAnimation(animatedElement, duration / 1000, Telerik.Web.UI.RadTreeNode._fps, "style", "height", points);
			this._animation.add_ended(this._animationEndedDelegate);
		}
				
		this._animation.play();
	},
	
	_disposeAnimation : function ()
	{
		if (this._animation) 
		{
			this._animation.dispose();
			this._animation = null;
		}
	},
	
	_animationEnded : function ()
	{
		var nodeList = this.get_childListElement();
		if (!nodeList) return;
		
		if (this._expanding)
		{
			nodeList.style.overflow = "visible";
		}
		else
		{
			nodeList.style.display = "none";
		}
		
		nodeList.style.height = "auto";
		nodeList.style.cssText = nodeList.style.cssText;
	},
	
	_collapseSiblings : function()
	{
		var siblings = this.get_parent().get_nodes();
		for (var i = 0; i < siblings.get_count(); i++)
		{
			if (siblings.getNode(i) != this)
			{
				siblings.getNode(i).set_expanded(false);
			}
		}
	},
	
	set_expanded : function (value)
	{
	    if (!this.get_isEnabled())
			return;
			
	    if(this.get_expanded() == value) return;
	
		this._properties.setValue("expanded", value);
		
		if (!this.get_element()) return;

		var treeView = this.get_treeView();		
		
		if (value)
		{
		    treeView._registerExpandedNode(this);
			if (treeView.get_singleExpandPath())
			{
				this._collapseSiblings();
			}
			
		    if (this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.ServerSide)
		    {
				var command = {commandName:"Expand", index: this._getHierarchicalIndex()};
				treeView._postback(command);
			}
			
			
			if (this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.ServerSideCallBack)
			{
				treeView._doLoadOnDemand(this);
				
				return;
			}
			
			if (this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.WebService)
			{
				treeView._loadChildrenFromWebService(this);
				
				return;
			}
						
			this._ensureChildControls();
		}
		else
		{
            treeView._registerCollapsedNode(this);
            
		    if (this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.ServerSide)
		    {
			    var command = {commandName:"Collapse", index: this._getHierarchicalIndex()};
			    treeView._postback(command);
		    }            
		}
		
		if (this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.ClientSide)
		{
			this._displayChildren(value);
			this._updateToggle();
			this._updateImageUrl();
		}
	},
	
	set_visible : function (value)
	{	    	
	    if (this.get_visible() == value) return;
	    
	    Telerik.Web.UI.RadTreeNode.callBaseMethod(this, 'set_visible', [value]);
	    
	    if (value)
	    {
	        this.get_element().style.display = "";
	    }
	    else
	    {
	        this.get_element().style.display = "none";
	    }
	    
	    this._ensureSiblingsAppearance();
	    
	    var parent = this.get_parent();
        if (parent != this.get_treeView())
            parent._ensureToggleElementAppearance();
	},
	
	get_treeView : function()
	{
		return this._getControl();
	},
	
	_updateToggle : function ()
	{
		var toggleElement = this.get_toggleElement();
		
		if (!toggleElement)
			return;						
			
		if (this.get_expanded())
		{
			this._replaceCssClass(toggleElement, "rtPlus", "rtMinus");
		}
		else
		{
			this._replaceCssClass(toggleElement, "rtMinus", "rtPlus");
		}
	},
	
	_removeToggle : function ()
	{
		var toggleElement = this.get_toggleElement();
		
		if (!toggleElement)
			return;
		
		var parentElement = toggleElement.parentNode;
		parentElement.removeChild(toggleElement);
		this._toggleElement = null;
	},	
	
	_replaceCssClass : function (element, oldClass, newClass)
	{
		element.className = element.className.replace(oldClass, newClass);
	},
	
	get_expanded : function ()
	{
		return this._properties.getValue("expanded", false) == true;
	},
	
	get_checked : function ()
	{
		return this._properties.getValue("checked", false) == true;
	},

	_setChecked : function (treeView, value)
	{
		if (!this.get_isEnabled())
			return;
		if (!this.get_checkable())
			return;	
			
		if (this.get_checked() == value)
		    return;
		
		this._properties.setValue("checked", value);
		
		if (!treeView) return;
		
		if (value)
			treeView._registerCheckedNode(this);
		else
			treeView._unregisterCheckedNode(this);
	},
	
	set_checked : function (value, e)
	{
        var treeView = this.get_treeView();
        this._setChecked(treeView, value);
        var checkBoxElement = this.get_checkBoxElement();
        
        //Do not update "checked" if the user clicked the checkbox. Required for RadFormDecorator support.
        if (checkBoxElement && !e)
		{
			checkBoxElement.checked = value;
			if ($telerik.isSafari) checkBoxElement.safarichecked = value;
		}
		
        if (!treeView) return;
        
        if (treeView._checkChildNodes)
        {
			var nodes = this.get_nodes();
			for (var i = 0, length = nodes.get_count(); i < length; i++)
				nodes.getNode(i).set_checked(value);
        }
                
		if (checkBoxElement)
		{
	        if (treeView._threeState)
	        {
				checkBoxElement.className = value ? "rtChecked" : "rtUnchecked";
				this._updateParentCheckState(treeView);
			}
        }
	},
	
	get_nodes : function ()
	{
		return this._getChildren();
	},
	
	get_text : function (text)
	{
	    var text = Telerik.Web.UI.RadTreeNode.callBaseMethod(this, 'get_text');
	    return Telerik.Web.UI.RadTreeView._htmlDecode(text); 
	},
	
	set_text : function (text)
	{
	    if(!text) text = "";
	    if(this.get_element())
	    {	    
	        var textElement = this.get_textElement();
	        if(this._text)
	        {	            
	            var escapedOriginalText = Telerik.Web.UI.RadTreeView._regExEscape(this.get_text());
	            escapedOriginalText = Telerik.Web.UI.RadTreeView._htmlEncode(escapedOriginalText);
	            var regEx = new RegExp(escapedOriginalText, "g");
	            var encodedText = Telerik.Web.UI.RadTreeView._htmlEncode(text);
	            textElement.innerHTML = textElement.innerHTML.replace(regEx, encodedText);
	        }
	        else
	        {
	            textElement.innerHTML = text;
	        }
	    }
	    this._text = text;
	    this._properties.setValue("text", text, true);	    
	},
			
	get_allowEdit : function ()
	{
	    return this._properties.getValue("allowEdit", true) == true;
	},
	
	set_allowEdit : function (value)
	{
	    this._properties.setValue("allowEdit", value);
	},
	
	get_allowDrag : function ()
	{
	    return this._properties.getValue("allowDrag", true) == true;
	},
	
	set_allowDrag : function (value)
	{
	    this._properties.setValue("allowDrag", value);
	},
	
	get_allowDrop : function ()
	{
	    return this._properties.getValue("allowDrop", true) == true;
	},
	
	set_allowDrop : function (value)
	{
	    this._properties.setValue("allowDrop", value);
	},
	
	_dispose: function ()
	{
	    Telerik.Web.UI.RadTreeNode.callBaseMethod(this, '_dispose');
	    
    	this._nodeListElement = null;
	    this._inputElement = null;
	    this._contentElement = null;
	    this._toggleElement = null;
	    this._textElement = null;
	    this._checkBoxElement = null;
	    this._loadingStatusElement = null;
	    this._imageElement = null;
	    this._linkElement = null;
	    
	    this._disposeAnimation();
	},
	
	_createChildListElement : function()
	{
		var childListElement = document.createElement("ul");
		
		childListElement.className = "rtUL";
		this.get_element().appendChild(childListElement);
		
		if (!this.get_expanded())
		{
		    childListElement.style.display = "none";
		}		
		
		return childListElement;
	},
	
	_renderChildren : function (html)
	{
		html[html.length] = "<ul class='rtUL'";
			
		if (!this.get_expanded())
		{
			html[html.length] = "style='display:none'>";
		}
		else
		{
			html[html.length] = ">";
		}
		var nodes = this.get_nodes();
		for (var i = 0, length = nodes.get_count(); i < length; i++)
		{
			nodes.getNode(i)._render(html);
		}
		html[html.length] = "</ul>";
	},
	
	_isDescendantOf : function(node)
	{
	    var parentNode = this.get_parent();
	    while(parentNode != this._getControl())
	    {
	        if(parentNode == node) return true;
	        
	        parentNode = parentNode.get_parent();
	    }
	    
	    return false;
	},
	
	_isFirstVisibleNode : function ()
	{
	    if(this.get_isFirst() && this.get_visible()) return true;
	    
		var previousSibling = this.get_previousSibling();
		while(previousSibling)
		{
		    if(previousSibling.get_visible()) return false;
		    
		    previousSibling = previousSibling.get_previousSibling();
		}
		
		return true;
	},
	
	_isLastVisibleNode : function ()
	{
	    if(this.get_isLast() && this.get_visible()) return true;
	    
		var nextSibling = this.get_nextSibling();
		while(nextSibling)
		{
		    if(nextSibling.get_visible()) return false;
		    
		    nextSibling = nextSibling.get_nextSibling();
		}
		
		return true;	    
	},	
	
	_isFirstRootNode : function ()
	{
		return this._isFirstVisibleNode() && this.get_parent() == this.get_treeView();
	},
	
	_renderBeginTag : function (html)
	{
		html[html.length] = "<li class='rtLI";
		
		if (this._isLastVisibleNode() && !this._isFirstRootNode())
		{
			html[html.length] = " rtLast";
		}
		else if (this._isFirstRootNode())
		{
			html[html.length] = " rtFirst";
		}
		html[html.length] = "'>";
	},
	
	_hasChildren : function ()
	{
		return this.get_nodes().get_count() > 0;
	},
	
	_renderWrap : function (html)
	{
		html[html.length] = "<div class='rt";
		
		if (this._isLastVisibleNode() && !this._isFirstRootNode())
		{
			html[html.length] = "Bot";
		}
		else if (this._isFirstVisibleNode())
		{
			html[html.length] = "Top";
		}
		else
		{
			html[html.length] = "Mid";
		}
		
		if (this.get_selected())
		{
			html[html.length] = " rtSelected";
		}
		
		html[html.length] = "'><span class='rtSp'></span>";
		if (this._hasChildren() || 
		    this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.WebService ||
		    this.get_expandMode() == Telerik.Web.UI.TreeNodeExpandMode.ServerSideCallBack)
		{
			this._renderToggleElement(html);
		}
		var treeView = this.get_treeView();		
		var checkBox = treeView._checkBoxes && this.get_checkable();
		if (checkBox)
		{
			if (treeView._threeState)
			{
				html[html.length] = "<span class='";
				html[html.length] = this._getCssClassForCheckState(this.get_checkState());
				html[html.length] = "'></span>";
			}
			else
			{
				html[html.length] = "<input type='checkbox' class='rtChk'";
				if (this.get_checked())
				{
					html[html.length] = "checked='checked'";
				}
				html[html.length] = " />"
			}
		}
		
		var imageUrl = this._getImageUrlToApply();
		if (imageUrl)
		{
			html[html.length]= "<img class='rtImg' alt='' src='";
			html[html.length] = imageUrl;
			html[html.length] = "' />";
		}
		
		var cssClass = this.get_cssClass();
		
		if (this.get_navigateUrl())
		{
			html[html.length] = "<a class='rtIn";						
			if(cssClass)
			    html[html.length] = " " + cssClass;
			html[html.length] = "' href='";
			html[html.length] = this.get_navigateUrl();
			html[html.length] = "'";
			
			if (this.get_target())
			{
				html[html.length] = " target='";
				html[html.length] = this.get_target();
				html[html.length] = "'";
			}
			
			html[html.length] = ">";
			html[html.length] = this.get_text();
			html[html.length] = "</a></div>";
		}
		else
		{
			html[html.length] = "<span class='rtIn";
			if(cssClass)
			    html[html.length] = " " + cssClass;			
			html[html.length] = "'>";
			html[html.length] = this.get_text();
			html[html.length] = "</span></div>";
		}
	},
	
	_renderToggleElement : function (html)
	{
		html[html.length] = "<span class='";
		if (this.get_expanded())
		{
			html[html.length] = "rtMinus'></span>";
		}
		else
		{
			html[html.length] = "rtPlus'></span>"
		}
	},
	
	_ensureAppearance : function ()
	{
		//if the node is not rendered yet - do nothing.
		if (!this.get_element())
			return;
			
		if (this._isFirstRootNode())
		{
			this._ensureFirstRootNodeAppearance();
		}
		else if (this._isLastVisibleNode())
		{
			this._ensureLastNodeAppearance();
		}
		else if (this._isFirstVisibleNode())
		{
			this._ensureFirstNodeAppearance();
		}
		else
		{
			this._ensureMiddleNodeAppearance();
		}
		
		if (this.get_selected())
		{
			this._addClassToContentElement("rtSelected");
		}
	},
	
	_render : function (html)
	{
		this._renderBeginTag(html);
		this._renderWrap(html);
		
		if (this._hasChildren() > 0)
		{
			this._renderChildren(html);
		}
		
		html[html.length] = "</li>";
			
        this._ensureSiblingsAppearance();
		
		var parent = this.get_parent();
		if (parent != this.get_treeView())
			parent._ensureParentNodeAppearance();
	},
	
	_ensureToggleElementAppearance : function ()
	{
	    var toggleElement = this.get_toggleElement();
	    if(!toggleElement) return;
	
	    var hasVisibleItems = false;
        for (var i = 0; i < this.get_nodes().get_count(); i++)
	    {
            if(this.get_nodes().getNode(i).get_visible())
                hasVisibleItems = true;
	    }	    	    	    	    
	    
	    if (hasVisibleItems)
	    {
	        toggleElement.style.display = "";
	    }
	    else
	    {
	        toggleElement.style.display = "none";
	    }
	},
	
	_ensureSiblingsAppearance : function ()
	{
        var nextSibling = this.get_nextSibling();
		if (nextSibling)
		{
			nextSibling._ensureAppearance();
		}
		
		var previousSibling = this.get_previousSibling();
		if (previousSibling)
		{
			previousSibling._ensureAppearance();
		}
	},
	
	_ensureParentNodeAppearance : function ()
	{
		if (!this.get_element())
			return;
		if (this.get_toggleElement())
		{
		    this._ensureToggleElementAppearance();		
			return;
		}
		this._createToggleElement();
	},
	
	_createToggleElement : function ()
	{
		var toggleElement = document.createElement("span");
		toggleElement.className = this.get_expanded() ? "rtMinus" : "rtPlus";
		this.get_contentElement().insertBefore(toggleElement, this.get_contentElement().firstChild.nextSibling);
	},
	
	_ensureFirstNodeAppearance : function ()
    {
		this._setCssClass(this.get_element(), "rtLI");
		this._setCssClass(this.get_contentElement(), "rtTop");
    },
	
	_ensureLastNodeAppearance : function ()
	{
		this._setCssClass(this.get_element(), "rtLI rtLast");
		this._setCssClass(this.get_contentElement(), "rtBot");
	},
	
	_ensureMiddleNodeAppearance : function ()
	{
		this._setCssClass(this.get_element(), "rtLI");
		this._setCssClass(this.get_contentElement(), "rtMid");
	},
	
	_ensureFirstRootNodeAppearance : function ()
	{
		var elementClassName = "rtLI rtFirst";
		if (this.get_parent().get_nodes().get_count() < 2)
		{
			elementClassName = "rtLI rtFirst rtLast";
		}
		this._setCssClass(this.get_element(), elementClassName);
		this._setCssClass(this.get_contentElement(), "rtTop");
	},
	
	_cacheDomProperties : function ()
	{
	    this.get_disabledImageUrl();
	    this.get_expandedImageUrl();
	    this.get_hoveredImageUrl();
	    this.get_selectedImageUrl();
	    this.get_imageUrl();
	    this.get_text();
	    this.get_navigateUrl();
	    this.get_target();
	    
	    for(var i = 0; i < this.get_nodes().get_count(); i++)
	    {
	        this.get_nodes().getNode(i)._cacheDomProperties();
	    }
	},
	
	_removeFromDom : function (parent)
	{
	    this._cacheDomProperties();
	
		parent.get_childListElement().removeChild(this.get_element());
		
		var firstSibling = parent.get_nodes().getNode(0);
		if (firstSibling)
		{
			firstSibling._ensureAppearance();
		}
		
		var lastSibling = parent.get_nodes().getNode(parent.get_nodes().get_count() - 1);
		if (lastSibling)
		{
			lastSibling._ensureAppearance();
		}
	},
	
	_getNodeData : function()
	{
		return	{
			Text: this.get_text(),
			Value: this.get_value(),
			ExpandMode: this.get_expandMode(),
			NavigateUrl: this.get_navigateUrl(),
			PostBack: this.get_postBack(),
			DisabledCssClass: this.get_disabledCssClass(),
			SelectedCssClass: this.get_selectedCssClass(),
			HoveredCssClass: this.get_hoveredCssClass(),
			ImageUrl: this.get_imageUrl(),
			HoveredImageUrl: this.get_hoveredImageUrl(),
			DisabledImageUrl: this.get_disabledImageUrl(),
			ExpandedImageUrl: this.get_expandedImageUrl(),
			ContextMenuID: this.get_contextMenuID()
		};
	}
}

Telerik.Web.UI.RadTreeNode.registerClass('Telerik.Web.UI.RadTreeNode', Telerik.Web.UI.ControlItem);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadTreeNodeCollection = function (parent)
{
	Telerik.Web.UI.RadTreeNodeCollection.initializeBase(this, [parent]);
}

Telerik.Web.UI.RadTreeNodeCollection.prototype = 
{
	getNode : function(index)
	{
		return this.getItem(index);
	}
}

Telerik.Web.UI.RadTreeNodeCollection.registerClass("Telerik.Web.UI.RadTreeNodeCollection", Telerik.Web.UI.ControlItemCollection);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.TreeNodeExpandMode = function (){}
Telerik.Web.UI.TreeNodeExpandMode.prototype = 
{
	ClientSide : 0,
	ServerSide : 1,
	ServerSideCallBack : 2,
	WebService : 3
}

Telerik.Web.UI.TreeNodeExpandMode.registerEnum("Telerik.Web.UI.TreeNodeExpandMode");

Telerik.Web.UI.TreeNodeCheckState = function (){}
Telerik.Web.UI.TreeNodeCheckState.prototype = 
{
	Unchecked : 0,
	Checked : 1,
	Indeterminate : 2
}
Telerik.Web.UI.TreeNodeCheckState.registerEnum("Telerik.Web.UI.TreeNodeCheckState");

Telerik.Web.UI.TreeViewLoadingStatusPosition = function (){}
Telerik.Web.UI.TreeViewLoadingStatusPosition.prototype = 
{
	BeforeNodeText : 0,
	AfterNodeText : 1,
	BelowNodeText : 2,
	None : 3
}

Telerik.Web.UI.TreeViewLoadingStatusPosition.registerEnum("Telerik.Web.UI.TreeViewLoadingStatusPosition");

Telerik.Web.UI.RadTreeView = function (element)
{
	Telerik.Web.UI.RadTreeView.initializeBase(this, [element]);
	
	this._childTypeName = "Telerik.Web.UI.RadTreeNode";
	
	this._loadingMessage = "Loading ...";
	this._loadingStatusPosition = Telerik.Web.UI.TreeViewLoadingStatusPosition.BeforeNodeText;
	this._nodeData = null;
	this._nodeListElement = null;
	this._postBackReference = null;
	this._uniqueId = null;
	this._multipleSelect = false;
	this._initialDragMousePos = null;
	this._hoveredNode = null;
    this._editing = false;
    this._editNode = null;
	this._dragging = false;
	this._checkBoxes = false;
	this._checkChildNodes = false;
	this._threeState = false;
	this._draggingClue = null;
	this._initialDragNode = null;
	this._dropClue = null;
	this._enableDragAndDropBetweenNodes = false;
	this._enableDragAndDrop = false;
	this._selectedIndexes = [];
	this._contextMenuIDs = [];
	this._contextMenus = null;
	this._checkedIndexes = [];
	this._expandedIndexes = [];
	this._collapsedIndexes = [];
	this._expandedNodesJson = "[]";
	this._collapsedNodesJson = "[]"
	this._selectedNodesJson = "[]";
	this._checkedNodesJson = "[]";
	this._logEntriesJson = "[]";
	this._scrollPosition = 0;
	this._allowNodeEditing = false;
	this._postBackOnCheck = false;
	this._postBackOnClick = false;
	this._postBackOnExpand = false;
	this._postBackOnEdit = false;
	this._postBackOnContextMenuItemClick = false;
	this._postBackOnCollapse = false;
	this._isRtl = false;
	this._singleExpandPath = false;
	this._clientState = {
		expandedNodes:[],
		collapsedNodes:[],
		checkedNodes:[],
		logEntries:[],
		selectedNodes:[]
	};
	this._onDocumentMouseMoveDelegate = null;
	this._onDocumentMouseUpDelegate = null;
	this._onSelectStartDelegate = null;
	this._contextMenuNode = null;
	this._skin = null;
	this._expandAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._collapseAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings({});
	this._persistLoadOnDemandNodes = true;
	this._webServiceLoader = null;
	this._initializeComplete = false;
	this._mouseMoveAttached = false;
	
	// Constants
	this._numpadPlusKeyCode = 107;
	this._numpadMinusKeyCode = 109;
	this._leftArrowKeyCode = 37;
	this._rightArrowKeyCode = 39;
	this._downArrowKeyCode = 40;
	this._upArrowKeyCode = 38;
	this._enterKeyCode = 13;
	this._spaceKeyCode = 32;
	this._f2KeyCode = 113;
	this._escapeKeyCode = 27;
	this._shiftKeyCode = 16;
}

Telerik.Web.UI.RadTreeView._createNodesFromJson = function (parent, nodes)
{
	var nodeData = parent.get_nodeData();

	if (!nodeData) return;

	var childElements = $telerik.getChildrenByTagName(parent.get_childListElement(), "li");
	
	for (var i = 0; i < nodeData.length; i++)
	{
		var node = new Telerik.Web.UI.RadTreeNode();
		nodes.add(node);
		node._initialize(nodeData[i], childElements[i]);
	}
}

Telerik.Web.UI.RadTreeView.prototype =
{
	initialize : function ()
	{
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, 'initialize');
		
		this._clientState.selectedNodes = this._selectedIndexes;
		this._selectedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.selectedNodes);

		this._clientState.checkedNodes = this._checkedIndexes;
		
		this._checkedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.checkedNodes);
		
		this._clientState.expandedNodes = this._expandedIndexes;
		this._expandedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.expandedNodes);
		
		this._clientState.collapsedNodes = this._collapsedIndexes;
		this._collapsedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.collapsedNodes);

		this.updateClientState();
				
		this._eventMap.addHandlerForClassName("dblclick", "rtIn", this._doubleClick);
		this._eventMap.addHandlerForClassName("click", "rtPlus", this._toggle);
		this._eventMap.addHandlerForClassName("click", "rtChk", this._check);
		this._eventMap.addHandlerForClassName("click", "rtChecked", this._check);
		this._eventMap.addHandlerForClassName("click", "rtUnchecked", this._check);
		this._eventMap.addHandlerForClassName("click", "rtIndeterminate", this._check);
		
		//RadFormDecorator
		this._eventMap.addHandlerForClassName("click", "radfdCheckboxUnchecked", this._check);
		this._eventMap.addHandlerForClassName("click", "radfdCheckboxChecked", this._check);
		
		this._eventMap.addHandlerForClassName("click", "rtMinus", this._toggle);
		this._eventMap.addHandlerForClassName("click", "rtIn", this._click);
		this._eventMap.addHandlerForClassName("click", "rtImg", this._click);
		this._eventMap.addHandlerForClassName("keydown", "RadTreeView", this._onKeyDown);
		this._eventMap.addHandlerForClassName("mouseover", "RadTreeView", this._treeMouseOver);
		this._eventMap.addHandlerForClassName("mouseover", "rtIn", this._mouseOver);
		this._eventMap.addHandlerForClassName("mouseover", "rtPlus", this._expandOnHover);
		this._eventMap.addHandlerForClassName("mouseover", "rtImg", this._expandOnHover);
		this._eventMap.addHandlerForClassName("mouseout", "rtIn", this._mouseOut);
		this._eventMap.addHandlerForClassName("mouseout", "rtLI", this._nodeMouseOut);
		this._eventMap.addHandlerForClassName("mousedown", "rtIn", this._mouseDown);
		this._eventMap.addHandlerForClassName("mousedown", "rtImg", this._mouseDown);
		this._eventMap.addHandlerForClassName("selectstart", "rtIn", this._cancelEvent);
		this._eventMap.addHandlerForClassName("dragstart", "rtImg", this._cancelEvent);
		this._eventMap.addHandlerForClassName("dragstart", "rtIn", this._cancelEvent);
		this._eventMap.addHandlerForClassName("scroll", "RadTreeView", this._updateScrollPosition);
		
		if (!$telerik.isOpera)
		{
			this._eventMap.addHandlerForClassName("contextmenu", "rtIn", this._contextMenu);
			this._eventMap.addHandlerForClassName("contextmenu", "rtImg", this._contextMenu);
		}
		else
		{
			this._eventMap.addHandlerForClassName("mousedown", "rtImg", this._contextMenu);
		}
		
        this._onDocumentMouseMoveDelegate = Function.createDelegate(this, this._onDocumentMouseMove);		
		this._onDocumentMouseUpDelegate = Function.createDelegate(this, this._onDocumentMouseUp);
		this._onDocumentMouseOutDelegate = Function.createDelegate(this, this._onDocumentMouseOut);
		this._onDocumentKeyDownDelegate = Function.createDelegate(this, this._onDocumentKeyDown);
		this._onSelectStartDelegate = Function.createDelegate(this, this._cancelEvent);
		this._contextMenuItemClickingHandler = Function.createDelegate(this, this._contextMenuItemClickingHandler);
		this._contextMenuShownHandler = Function.createDelegate(this, this._contextMenuShownHandler);
		this._applicationLoadHandler = Function.createDelegate(this, this._applicationLoadHandler);
		
		Sys.Application.add_load(this._applicationLoadHandler);
		    
		$addHandler(document.documentElement, "keydown", this._onDocumentKeyDownDelegate);
		
		this._isRtl = Telerik.Web.UI.RadTreeView._isRtl(this.get_element());
		
		if(this._isRtl)
		{
		    Telerik.Web.UI.RadTreeView._initializeRtl(this.get_element());
		    this._setRtlSkin();
		}
		
		this._initializeComplete = true;
		this.raiseEvent("load");
	},
	
	_attachMouseMoveHandler : function ()
	{
        // There is a bug in ASP.NET AJAX in IE6, the workaround is to attach the handler directly
		if($telerik.isIE)
		{
		    document.attachEvent("onmousemove",this._onDocumentMouseMoveDelegate);
		}
		else
		{
		    $addHandler(document, "mousemove", this._onDocumentMouseMoveDelegate);
		}
		this._mouseMoveAttached = true;
	},

	_setRtlSkin : function ()
	{
        if (this._skin && this.get_element().className.indexOf("RadTreeView_rtl") < 0)
	    {
		    this.get_element().className = String.format("{0} RadTreeView_rtl RadTreeView_{1}_rtl", 
                this.get_element().className, this._skin);
	    }	
	},

	_applicationLoadHandler : function()
	{
		this._addContextMenuHandlers();
		Sys.Application.remove_load(this._applicationLoadHandler);
	},

	_contextMenuItemClickingHandler : function(sender, args)
	{
		if (this._contextMenuNode == null)
		{
			return;
		}

		var menuItem = args.get_item();
		var node = this._contextMenuNode;
		
		if (this._raiseContextMenuItemClicking(node, menuItem))
		{
			args.set_cancel(true);
			return;
		}

		var eventArgs = new Telerik.Web.UI.RadTreeViewContextMenuItemEventArgs(node, menuItem);
		this.raiseEvent("contextMenuItemClicked", eventArgs);

		menuItem.get_menu().hide();

		if (this._postBackOnContextMenuItemClick && menuItem.get_postBack())
		{
			var command =
			{
				commandName: "ContextMenuItemClick",
				index: node._getHierarchicalIndex(),
				contextMenuID : menuItem.get_menu().get_id(),
				menuItemIndex: menuItem._getHierarchicalIndex()
			};
			args.set_cancel(true);
			this._postback(command);
		}
	},
	
	_contextMenuShownHandler : function(sender, args)
	{
		var node = this._contextMenuNode;
		var eventArgs = new Telerik.Web.UI.RadTreeViewContextMenuEventArgs(node, sender);
		this.raiseEvent("contextMenuShown", eventArgs);		
	},
	
	_resolveContextMenuID : function(contextMenuID)
	{
		return String.format("{0}_{1}", this.get_id(), contextMenuID);
	},

	_addContextMenuHandlers : function()
	{
		var contextMenus = this.get_contextMenus();
		for (var i=0; i<contextMenus.length; i++)
		{
			var contextMenu = contextMenus[i];
			if (contextMenu)
			{
				contextMenu.add_itemClicking(this._contextMenuItemClickingHandler);
				contextMenu.add_shown(this._contextMenuShownHandler);
			}
		}
	},
	
	_removeContextMenuHandlers : function()
	{
		var contextMenus = this.get_contextMenus();
		for (var i=0; i<contextMenus.length; i++)
		{
			var contextMenu = contextMenus[i];
			if (contextMenu)
			{
				contextMenu.remove_shown(this._contextMenuShownHandler);
				contextMenu.remove_itemClicking(this._contextMenuItemClickingHandler);
			}
		}
	},
	
	findNodeByText : function (text)
	{
		return this._findItemByText(text);
	},
	
	findNodeByValue : function (value)
	{
		return this._findItemByValue(value);
	},
	
	findNodeByUrl: function(value)
	{
		return this._findItemByUrl(value);
	},
	findNodeByAbsoluteUrl: function(value)
	{
		return this._findItemByAbsoluteUrl(value);
	},
	
	findNodeByAttribute : function (attributeName, attributeValue)
	{
		return this._findItemByAttribute(attributeName, attributeValue);
	},

	unselectAllNodes : function ()
	{
		this._clearSelectedNodes();
	},

	showNodeContextMenu : function(node, domEvent)
	{
	    var contextMenu = node.get_contextMenu();

		var eventArgs = new Telerik.Web.UI.RadTreeViewContextMenuCancelEventArgs(node, contextMenu, domEvent);
		this.raiseEvent("contextMenuShowing", eventArgs);

		if (eventArgs.get_cancel())
			return;
	
		this._contextMenuNode = node;
		node._showContextMenu(domEvent);
	},

	get_allNodes : function()
	{
		return this._getAllItems();
	},
	
	set_enabled : function (value)
	{
		if (this.get_enabled() == value)
			return;
			
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, "set_enabled", [value]);
		
		if (!this.get_isInitialized())
			return;
		
		this.get_element().disabled = !value;
		
		var disabledCssClass = String.format("RadTreeView_{0}_disabled", this._skin);
		this.toggleCssClass(disabledCssClass);
		
		var checkBoxes = this.get_element().getElementsByTagName("input");
		for (var i = 0, length = checkBoxes.length; i < length; i++)
		{
			var checkBox = checkBoxes[i];
			if (checkBox.className != "rtChk") continue;
			checkBox.disabled = !value;
		}
	},
	
	get_loadingStatusPosition : function()
	{
		return this._loadingStatusPosition;
	},
	
	set_loadingStatusPosition : function(value)
	{
		this._loadingStatusPosition = value;
	},
	
	get_loadingMessage : function()
	{
		return this._loadingMessage;
	},
	
	set_loadingMessage : function(value)
	{
		this._loadingMessage = value;
	},
	
	get_childListElement : function()
	{
		if (!this._nodeListElement)
			this._nodeListElement = $telerik.getFirstChildByTagName(this.get_element(), "ul", 0);
		return this._nodeListElement;
	},
	
	get_expandAnimation: function()
	{
		/// <exclude/>
		
		return this._expandAnimation;
	},
	
	set_expandAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._expandAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	get_collapseAnimation: function()
	{
		/// <exclude/>
		
		return this._collapseAnimation;
	},
	
	set_collapseAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._collapseAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	_postback : function (command)
	{
		if (!this._postBackReference)
			return;

		var postbackFunction = this._postBackReference.replace("arguments", 
				Sys.Serialization.JavaScriptSerializer.serialize(command));

		eval(postbackFunction);
	},

	_registerExpandedNode : function (node)
	{
		var index = node._getHierarchicalIndex();
		
		if (Array.indexOf(this._clientState.collapsedNodes, index) > -1)
		{
			Array.remove(this._clientState.collapsedNodes, index);
		}

		Array.add(this._clientState.expandedNodes, index);
		
		this._updateToggleState();		
	},
	
	_registerCollapsedNode : function (node)
	{
		var index = node._getHierarchicalIndex();
		
		if (Array.indexOf(this._clientState.expandedNodes, index) > -1)
		{
			Array.remove(this._clientState.expandedNodes, index);
		}

		Array.add(this._clientState.collapsedNodes, index);
		
		this._updateToggleState();
	},
	
	_updateToggleState : function()
	{
		this._expandedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.expandedNodes);
						
		this._collapsedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.collapsedNodes);
						
		this.updateClientState();
	},
	
	_updateSelectedState : function()
	{
		this._selectedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.selectedNodes);
		this.updateClientState();
	},
	
	_updateCheckedState : function ()
	{
		this._checkedNodesJson = 
			Sys.Serialization.JavaScriptSerializer.serialize(this._clientState.checkedNodes);
		this.updateClientState();
	},
	
	commitChanges : function()
	{
		this._logEntriesJson = this._log.serialize();
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, "commitChanges");
	},
	
	saveClientState : function()
	{
		return "{\"expandedNodes\":" + this._expandedNodesJson + 
		        ",\"collapsedNodes\":" + this._collapsedNodesJson + 
				",\"logEntries\":" + this._logEntriesJson + 
				",\"selectedNodes\":" + this._selectedNodesJson +
				",\"checkedNodes\":" + this._checkedNodesJson + 
				",\"scrollPosition\":" + this._scrollPosition + "}";
	},
	
	_updateScrollPosition : function()
	{
		this._scrollPosition = this.get_element().scrollTop;
		this.updateClientState();
	},
	
	_unregisterSelectedNode : function(node)
	{
	    Array.remove(this._clientState.selectedNodes, node._getHierarchicalIndex());

		this._updateSelectedState();
	},
	
	_unregisterCheckedNode : function(node)
	{
	    Array.remove(this._clientState.checkedNodes, node._getHierarchicalIndex());	    
		
		this._updateCheckedState();
	},
	
	_unregisterNodeFromClientState : function(node)
	{
	    Array.remove(this._clientState.collapsedNodes, node._getHierarchicalIndex());
	    Array.remove(this._clientState.expandedNodes, node._getHierarchicalIndex());
	    Array.remove(this._clientState.selectedNodes, node._getHierarchicalIndex());
	    Array.remove(this._clientState.checkedNodes, node._getHierarchicalIndex());	    
	},
	
	_unregisterNodeChildrenFromClientState : function(node)
	{
	    for(var i = 0; i < node.get_nodes().get_count(); i++)
	    {
	        this._unregisterNodeHierarchyFromClientState(node.get_nodes().getNode(i));
	    }
	},	
	
	_unregisterNodeHierarchyFromClientState : function(node)
	{
	    this._unregisterNodeFromClientState(node);
	    this._unregisterNodeChildrenFromClientState(node);
	},	
	
	_clearSelectedNodes : function()
	{
		var selectedNodes = this.get_selectedNodes();
		
		for(var i = 0; i < selectedNodes.length; i++)
		{
			selectedNodes[i].set_selected(false);
		}
		
		this._clientState.selectedNodes = new Array();
		this._updateSelectedState();
	},
	
	get_selectedNode : function ()
	{
		var lastNodeIndex = this._clientState.selectedNodes.length - 1;
		
		if(lastNodeIndex >= 0)
		{
			var index = this._clientState.selectedNodes[lastNodeIndex];
			if (index)
			{
				return this._findItemByHierarchicalIndex(index);
			}
		}
		
		return null;				
	},
	
	get_selectedNodes : function ()
	{
		var selectedNodes = [];
		for (var i = 0; i < this._clientState.selectedNodes.length; i++)
		{
			var selectedNode = this._findItemByHierarchicalIndex(this._clientState.selectedNodes[i]);
			Array.add(selectedNodes, selectedNode);
		}
		return selectedNodes;
	},
	
	get_checkedNodes : function ()
	{
		var checkedNodes = [];
		for (var i = 0; i < this._clientState.checkedNodes.length; i++)
		{
			var selectedNode = this._findItemByHierarchicalIndex(this._clientState.checkedNodes[i]);
			Array.add(checkedNodes, selectedNode);
		}
		return checkedNodes;
	},
	
	_getExpandedNodes : function ()
	{	
		var expandedNodes = [];
		for (var i = 0; i < this._clientState.expandedNodes.length; i++)
		{
			var expandedNode = this._findItemByHierarchicalIndex(this._clientState.expandedNodes[i]);
			Array.add(expandedNodes, expandedNode);
		}
		return expandedNodes;
	},
		
	_getCollapsedNodes : function ()
	{	
		var collapsedNodes = [];
		for (var i = 0; i < this._clientState.collapsedNodes.length; i++)
		{
			var collapsedNode = this._findItemByHierarchicalIndex(this._clientState.collapsedNodes[i]);
			Array.add(collapsedNodes, collapsedNode);
		}
		return collapsedNodes;
	},

	_backupClientState : function ()
	{
	    this._backupCollapsedNodes = this._getCollapsedNodes();
		this._backupExpandedNodes = this._getExpandedNodes();
		this._backupSelectedNodes = this.get_selectedNodes();
		this._backupCheckedNodes = this.get_checkedNodes();
	},
	
	_restoreClientState : function ()
	{
		this._clientState.selectedNodes = [];
		
		for (var i = 0; i < this._backupSelectedNodes.length; i++)
		{
			Array.add(this._clientState.selectedNodes, 
				this._backupSelectedNodes[i]._getHierarchicalIndex());
		}
		
		this._clientState.collapsedNodes = [];
		
		for (var i = 0; i < this._backupCollapsedNodes.length; i++)
		{
			Array.add(this._clientState.collapsedNodes, 
				this._backupCollapsedNodes[i]._getHierarchicalIndex());
		}
		
		this._clientState.expandedNodes = [];
		
		for (var i = 0; i < this._backupExpandedNodes.length; i++)
		{
			Array.add(this._clientState.expandedNodes, 
				this._backupExpandedNodes[i]._getHierarchicalIndex());
		}
		
		this._clientState.checkedNodes = [];
		
		for (var i = 0; i < this._backupCheckedNodes.length; i++)
		{
			Array.add(this._clientState.checkedNodes, 
				this._backupCheckedNodes[i]._getHierarchicalIndex());
		}
		
		this._updateToggleState();
		this._updateSelectedState();
		this._updateCheckedState();
	},
	
	_registerSelectedNode : function(node)
	{
		Array.add(this._clientState.selectedNodes, node._getHierarchicalIndex());
		
		this._updateSelectedState();
	},
	
	_registerCheckedNode : function (node)
	{
		Array.add(this._clientState.checkedNodes, node._getHierarchicalIndex());
		
		this._updateCheckedState();
	},
	
	_getMousePosition : function (e)
	{
		var scrollOffset = $telerik.getScrollOffset(document.body, true);
				
		var mouseX = e.clientX;
		var mouseY = e.clientY;
		
		mouseX += scrollOffset.x;
		mouseY += scrollOffset.y;
		
		return { x: mouseX, y: mouseY };
	},
	
	_extractNodeFromDomElement : function (element)
	{
		return this._extractItemFromDomElement(element);
	},
	
	_doubleClick : function(e)
	{	    
		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		this._raiseEvent("nodeDoubleClick", node, e);		
		
		if(this.get_allowNodeEditing() && node.get_allowEdit()) return;
		
		this._toggle(e);
	},
	
	_hideContextMenus : function()
	{
		if (this.get_contextMenuIDs().length > 0)
		{
			Telerik.Web.UI.RadContextMenu.hideAll();
		}
	},
	
    _expandOnHover : function (e)
    {                   
        if(Telerik.Web.UI.RadTreeView._draggingTreeView)
        {                    
            var node = this._extractNodeFromDomElement(e.eventMapTarget);
            
            this._hoveredNode = node;
            
            window.setTimeout(function () { if(node._getControl() && node == node._getControl()._hoveredNode) { node.set_expanded(true); } }, 1000);
        }
        return true;
    },
	
	_toggle : function (e)
	{
		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		
		if (!node.get_isEnabled())
			return;

		this._hideContextMenus();
		e.stopPropagation();

		var expanded = node.get_expanded();
		
		if (expanded == false)
		{
			if (this._raiseCancelEvent("nodeExpanding", node, e))
				return;
		}
		else 
		{
			if (this._raiseCancelEvent("nodeCollapsing", node, e))
				return;
		}
		
		node.toggle();
		
		if (expanded == false)
		{
			this._raiseEvent("nodeExpanded", node, e);
		}
		else
		{
			this._raiseEvent("nodeCollapsed", node, e);
		}		
	},
	
	_check : function (e)
	{
		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		
		if (!node.get_isEnabled())
			return;
		
		this._hideContextMenus();	
		e.stopPropagation();
			
		if (this._raiseCancelEvent("nodeChecking", node, e))
		{
		    // Revert checkbox to previous state
		    node.get_checkBoxElement().checked = !node.get_checkBoxElement().checked;
			return;
		}
			
		if (this._threeState && node.get_checkState() == Telerik.Web.UI.TreeNodeCheckState.Indeterminate)
			node.set_checked(true, e);
		else
			node.set_checked(!node.get_checked(), e);
			
		this._raiseEvent("nodeChecked", node, e);
		
		if (this._postBackOnCheck)
		{
			var command = {commandName: "Check", index: node._getHierarchicalIndex()};
		    this._postback(command);
		}
	},
	
	_mouseDown : function (e)
	{	    
	    // Opera doesn't have 'contextmenu' event so show the context menu on right-click mousedown
		if ($telerik.isOpera && e.button == 2)
		{
			this._contextMenu(e);
			return;
		}				
		
		// Drag only on left-click mousedown
		if (e.button != 0)
		{
			return;
		}
		
		if(!this.get_enableDragAndDrop()) return;

		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		
		if(!node) return;
		if(!node.get_isEnabled() || !node.get_allowDrag()) return;
		
		this._initialDragMousePos = this._getMousePosition(e);
		this._initialDragNode = node;
		
		this._attachMouseMoveHandler();
		$addHandler(document, "mouseup", this._onDocumentMouseUpDelegate);
		$addHandler(document, "mouseout", this._onDocumentMouseOutDelegate);
		
		e.preventDefault();
	},
	
	_createDragClueAt : function (node, posX, posY)
	{
		this._draggingClue = document.createElement("div");
		
		this._draggingClue.className = this.get_element().className;
		
		this._draggingClue.style.position = "absolute";
		//To override width and height set via CssClass
		this._draggingClue.style.width = "auto";
		this._draggingClue.style.height = "auto";
		
		this._draggingClue.style.overflow = "visible";						
		this._draggingClue.style.top = posY + "px";
		this._draggingClue.style.zIndex = 1;				
		
		if(this._isRtl)
		{
		    var treeWidth = this.get_element().scrollWidth;
		    this._draggingClue.dir = "rtl";
		    this._draggingClue.style.width = treeWidth + "px";
		    this._draggingClue.style.left = (posX - treeWidth) + "px";
		}
		else
		{
		    this._draggingClue.style.left = posX + "px";
		}
		
		this._draggingClueList = node._createChildListElement();
		
		this._draggingClueList.style.display = "";
		
		this._draggingClue.appendChild(this._draggingClueList);
	
	    var selectedNodes = this.get_selectedNodes();
	        
	    for (var i = 0; i < selectedNodes.length; i++)
	    {
	        var currentNode = selectedNodes[i];
		    var clonedElement = $telerik.getElementByClassName(currentNode.get_element(), "rtIn").cloneNode(true);
		    clonedElement.style.display = "block";
		    
		    
	        var childListElement = $telerik.getElementByClassName(clonedElement, "rtUL");
	        		        
	        if(childListElement)
	            clonedElement.removeChild(childListElement);
		    
		    this._draggingClueList.appendChild(clonedElement);
	    }
		
		document.body.appendChild(this._draggingClue);
	},
	
	get_draggingClueElement : function ()
	{
	    return this._draggingClue;
	},
	
	_contextMenu : function(e)
	{
	    // Opera doesn't have 'contextmenu' event so show the context menu on right-click mousedown
		if ($telerik.isOpera && e.button != 2)
		{
			return;
		}
		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		if (!node) return;
		if (!node.get_isEnabled()) return;

		this.showNodeContextMenu(node, e);
	},
	
	_cancelEvent : function(e)
	{
	    e.preventDefault();
		return false;
	},
	
	_shouldStartDrag : function(mousePos)
	{
	    if(!this._initialDragNode || !this._initialDragMousePos) return false;
	    
	    if(Math.abs(this._initialDragMousePos.x - mousePos.x) > 4 ||
	        Math.abs(this._initialDragMousePos.y - mousePos.y) > 4)
	        return true;
	},
	
	_selectFirstNode : function()
	{
	    var firstNode = this.get_nodes().getNode(0);
	    
	    if(!firstNode) return;
	    
	    firstNode.set_selected(true);
	    this._scrollToNode(firstNode);
	},
	
	_onDocumentKeyDown : function (e)
	{
        if(e.keyCode == this._escapeKeyCode && this._dragging)
        {
            this._clearDrag();
        }
	},
	
	_onKeyDown : function (e)
	{
	    if(this._editing)
	    {
	        this._onEditKeyDown(e);
	        return;
	    }
	    
        var node = this.get_selectedNode();
        if(!node)
        {
            if(e.keyCode == this._upArrowKeyCode || e.keyCode == this._downArrowKeyCode ||
                e.keyCode == this._enterKeyCode || e.keyCode == this._spaceKeyCode)
            {
                this._selectFirstNode();
                e.preventDefault();
            }	            	            
            return;
        }
        
        if(this._raiseCancelEvent("keyPressing", node, e)) return;
        
	    if(e.keyCode == this._numpadPlusKeyCode ||
	        e.keyCode == this._numpadMinusKeyCode ||
	        e.keyCode == this._leftArrowKeyCode ||
	        e.keyCode == this._rightArrowKeyCode)
	    {
		    node.toggle();
	    }
	    
		if(e.keyCode == this._downArrowKeyCode)
	    {		    
	        var nextSelectableNode = node._getNextSelectableNode();		        		        
	        
	        if(!nextSelectableNode) return;
	    
		    e.preventDefault();
		    
            if(!this.get_multipleSelect() || (!e.ctrlKey && !e.shiftKey))
            {
                this._clearSelectedNodes();
            }

		    nextSelectableNode.set_selected(true);
		    this._scrollToNode(nextSelectableNode);
	    }

	    if(e.keyCode == this._upArrowKeyCode)
	    {
	        var prevSelectableNode = node._getPrevSelectableNode();
	        
	        if(!prevSelectableNode) return;
	        
	        e.preventDefault();
	        
            if(!this.get_multipleSelect() || (!e.ctrlKey && !e.shiftKey))
            {
                this._clearSelectedNodes();
            }		        
	    
		    prevSelectableNode.set_selected(true);
		    this._scrollToNode(prevSelectableNode);
	    }		    
	    
	    if(e.keyCode == this._f2KeyCode)
	    {
	        if(this.get_allowNodeEditing() && node.get_selected() && node.get_allowEdit())
	        {
	            this._startEdit(node);
	        }
	    }
	    
	    if(e.keyCode == this._spaceKeyCode)
	    {
	        node.set_checked(!node.get_checked());
	    }
	    
	    if(e.keyCode == this._enterKeyCode)
	    {
	        if (this._raiseCancelEvent("nodeClicking", node, e))
		        return true;
    		
	       	this._raiseEvent("nodeClicked", node, e);
	       	
	       	this._postClickCommand(node);		       			

			e.preventDefault();
		    return true;
	    }		    
	},
	
	_postClickCommand : function (node)
	{
        if (node.get_enabled() && node.get_postBack() && this._postBackOnClick && !node._editing)
        {
	        var command = {commandName: "Click", index: node._getHierarchicalIndex()};
            this._postback(command);
        }	    
	},
	
    _scrollToNode : function (node)
    {	    
        var nodeElement = node.get_contentElement();
        var treeViewElement = this.get_element();
        
        var nodeOffsetTop = this._getTotalOffsetTop(nodeElement);
        var treeOffsetTop = this._getTotalOffsetTop(treeViewElement);
        var relativeOffsetTop = nodeOffsetTop - treeOffsetTop;

        if(relativeOffsetTop < treeViewElement.scrollTop)
        {
		    treeViewElement.scrollTop = relativeOffsetTop;
	    }

	    var height = nodeElement.offsetHeight;
    	
	    if(relativeOffsetTop + height > (treeViewElement.clientHeight + treeViewElement.scrollTop))
	    {
		    treeViewElement.scrollTop += ((relativeOffsetTop + height) - (treeViewElement.clientHeight + treeViewElement.scrollTop));
	    }
    },
    
    _getTotalOffsetTop : function (element)
    {
        var offsetTop = element.offsetTop;
        
        var parent = element.offsetParent;
        
        while(parent)
        {
            offsetTop += parent.offsetTop;
            parent = parent.offsetParent;
        }

	    return offsetTop;        
    },
	
	_onEditKeyDown : function (e)
	{
	    if(e.keyCode == this._escapeKeyCode)
	    {
	        this._endEdit(true);
	    }
	    
	    if(e.keyCode == this._enterKeyCode)
	    {
	        this._endEdit(false);
	    }
	    
	    e.stopPropagation();
	    return false;
	},
	
	_onDocumentMouseMove : function (e)
	{	    
	    if(e.srcElement) e.target = e.srcElement;
	    
	    var mousePos = this._getMousePosition(e);
	    
        if(!this._dragging && this._shouldStartDrag(mousePos) && !this._raiseCancelEvent("nodeDragStart", this._initialDragNode, e))
        {
            this._startDrag(e, mousePos);
	    }

	    if(!this._dragging) return;

        var eventArgs = new Telerik.Web.UI.RadTreeNodeDraggingEventArgs(this._initialDragNode, e);
        this.raiseEvent("nodeDragging", eventArgs);
	    if(!eventArgs.get_cancel())
	    {
            this._positionDropClue(e);
        }
	    
	    this._mousePos = mousePos;
	    this._adjustScroll();			
		this._draggingClue.style.top = mousePos.y + 4 + "px";
		
		if(!this._isRtl)
		{
		    this._draggingClue.style.left = mousePos.x + 4 + "px";
		}
		else
		{
		    this._draggingClue.style.left = (mousePos.x - 4 - this._draggingClue.scrollWidth) + "px";
		}
	},
	
	_onDocumentMouseOut : function (e)
	{
	    if(!this._dragging) return;
	
	    var relatedTarget;
	    if(e.rawEvent.relatedTarget)
	        relatedTarget = e.rawEvent.relatedTarget;
	    else
	        relatedTarget = e.rawEvent.toElement;
	    
	    if(!relatedTarget)
	    {
	        this._clearDrag();
	    }
	},
	
	_startDrag : function (e, mousePos)
	{
        if(this._initialDragNode.get_selected() == false)
        {
            if(!this.get_multipleSelect() || (!e.ctrlKey && !e.shiftKey))
            {
                this._clearSelectedNodes();
            }
    		
            this._initialDragNode.set_selected(true);
        }
	
        this._createDragClueAt(this._initialDragNode, mousePos.x, mousePos.y);
        
        this._createDropClue();
        
        $addHandler(document, "selectstart", this._onSelectStartDelegate);        
		
        this._dragging = true;
        this._draggingPosition = "over";
        Telerik.Web.UI.RadTreeView._draggingTreeView = this;		        
		
		e.returnValue = false;
	},
	
	_createDropClue : function ()
	{
	    this._dropClue = document.createElement("div");
	    
	    document.body.appendChild(this._dropClue);
	    
        this._dropClue.style.position = "absolute";
        this._dropClue.style.height = "5px";
	},
	
	_positionDropClue : function (e)
	{
	    // Don't do anything if hovering over the drop clue
	    if(this._dropClue == e.target) return;
	
        var node = this._extractNodeFromDomElement(e.target);                        
	    
	    // Hide drop clue if mouse is outside a tree
        if(!node)
        {
            this._dropClue.style.visibility = "hidden";
            return;
        }                
        
        var hoveredTree = node._getControl();	    	
        if(!hoveredTree.get_enableDragAndDropBetweenNodes()) return;        
        
        // Hide drop clue if over a node
        if($telerik.isDescendantOrSelf(node.get_textElement(), e.target))
        {   
            this._dropClue.style.visibility = "hidden";
            this._draggingPosition = "over";
            return;            
        }            
        else
        {
            this._dropClue.style.visibility = "visible";
        }
        
        // Save the TreeNode that the Clue is attached to
        // This is needed in case browser events hit the Clue instead of the Node
        this._dropClue.treeNode = node;
        
        // Set drop clue width
        var nodeElement = node.get_element();	    	        
        this._dropClue.style.width = nodeElement.offsetWidth + "px";
        
        // Set drop clue left coordinate
        var nodeContentElement = node.get_contentElement();
        var elementPos = $telerik.getLocation(nodeContentElement);
        this._dropClue.style.left = elementPos.x + "px";                
        	    	    
	    var mousePos = this._getMousePosition(e);	    	    
	    
        if(mousePos.y < (elementPos.y + (nodeContentElement.offsetHeight / 2)))
        {		                
            this._dropClue.style.top = elementPos.y + "px";
            this._dropClue.className = String.format("rtDropAbove_{0}",this._skin);
            this._draggingPosition = "above";
        }
        else
        {
            this._dropClue.style.top = (elementPos.y + nodeContentElement.offsetHeight - 5) + "px";
            this._dropClue.className = String.format("rtDropBelow_{0}",this._skin);	            
            this._draggingPosition = "below";
        }
	},	
	
	_adjustScroll : function ()
    {    	
        if(!Telerik.Web.UI.RadTreeView._draggingTreeView) return;        

        var treeViewToScroll = Telerik.Web.UI.RadTreeView._lastHoveredTreeView;
        
        if(!treeViewToScroll)
            treeViewToScroll = this;
        
	    var treeElement = treeViewToScroll.get_element();
	    	    
	    if(!treeElement) return;

	    var topY, bottomY;
	    var treeView = treeViewToScroll;
		
	    topY = $telerik.getLocation(treeElement).y;
	    bottomY = topY + treeElement.offsetHeight;
	    
	    var scrollAtTop = treeElement.scrollTop <= 0;
	    var scrollAtBottom = treeElement.scrollTop >= (treeElement.scrollHeight - treeElement.offsetHeight + 16);
	    var mouseDistanceToTop = Telerik.Web.UI.RadTreeView._draggingTreeView._mousePos.y - topY;
	    var mouseDistanceToBottom = bottomY - Telerik.Web.UI.RadTreeView._draggingTreeView._mousePos.y;
		
	    if (mouseDistanceToTop < 50 && !scrollAtTop)
	    {
	        var scrollSpeed = (10 - (mouseDistanceToTop / 5));
		    treeElement.scrollTop = treeElement.scrollTop - scrollSpeed;	
		    window.setTimeout( function() { treeView._adjustScroll(); }, 100);		
	    }	
	    else if (mouseDistanceToBottom < 50 && !scrollAtBottom)
	    {
	        var scrollSpeed = (10 - (mouseDistanceToBottom / 5));
		    treeElement.scrollTop = treeElement.scrollTop + scrollSpeed;
		    window.setTimeout( function() { treeView._adjustScroll(); }, 100);		
	    }
	    
	    this._scrollPosition = treeElement.scrollTop;
    },
	
	_onDocumentMouseUp : function (e)
	{
		if(!this._dragging)
		{
		    this._initialDragMousePos = null;
		    this._initialDragNode = null;
		    return;
		}
		
	    var sourceNodes = this.get_selectedNodes();
	    
	    var destinationNode = null;
	    if(e.target == this._dropClue)
	    {
	        // If the event has hit the DropClue we take the node it is attached to
	        destinationNode = this._dropClue.treeNode;
	    }
	    else
	    {
	        destinationNode = this._extractNodeFromDomElement(e.target);
	    }
	    
	    if (destinationNode)
	    {
			if(destinationNode._isDescendantOf(this._initialDragNode) || this._initialDragNode == destinationNode)
			{
				this._clearDrag();
				return;
			}
	    }
	    
	    var htmlElement = e.target;
	    var eventArgs = new Telerik.Web.UI.RadTreeNodeDroppingEventArgs(sourceNodes, destinationNode, htmlElement, this._draggingPosition, e);
	    this.raiseEvent("nodeDropping", eventArgs);
	    if(!eventArgs.get_cancel())
	    {		    
		    var command = {};
		    command.sourceNodesIndices = [];
		    
		    for(var i = 0; i < sourceNodes.length; i++)
		    {
		        Array.add(command.sourceNodesIndices, sourceNodes[i]._getHierarchicalIndex());
		    }
		    
		    htmlElement = eventArgs.get_htmlElement();		    
									    
		    if(destinationNode && (destinationNode.get_allowDrop() || this._draggingPosition != "over") && destinationNode.get_isEnabled())
		    {
		        command.destIndex = destinationNode._getHierarchicalIndex();
		    
		        if(destinationNode._getControl() == this)
		        {			    
		            command.commandName = "NodeDrop";
			    }
			    else
			    {
			        command.commandName = "NodeDropOnTree";
			        command.treeId = destinationNode._getControl()._uniqueId;
			    }
			    
			    command.dropPosition = this._draggingPosition;
		    } 		    
		    else if(htmlElement.id && htmlElement.id != "")
		    {
		        command.commandName = "NodeDropOnHtmlElement";
		        command.htmlElementId = htmlElement.id;
		    }
		    
		    if(command.commandName)
		    {   				
	            var eventArgs = new Telerik.Web.UI.RadTreeNodeDroppedEventArgs(sourceNodes);
	            this.raiseEvent("nodeDropped", eventArgs);
		        this._postback(command);
		    }
		}
		this._clearDrag();
	},		
	
	_clearDrag : function ()
	{
		if (!this._dragging) 
		    return;
		
		if(this._dropClue)
		{
		    document.body.removeChild(this._dropClue);
		    this._dropClue = null;
		}
	    
	    if (this._draggingClue)
	    {
		    document.body.removeChild(this._draggingClue);
		    this._draggingClue = null;
		}
		
		this._dragging = false;
		Telerik.Web.UI.RadTreeView._draggingTreeView = null;
		
		this._initialDragMousePos = null;
		this._initialDragNode = null;
		
		this._removeMouseMoveHandler();									
		$removeHandler(document, "mouseup", this._onDocumentMouseUpDelegate);
		$removeHandler(document, "selectstart", this._onSelectStartDelegate);
		$removeHandler(document, "mouseout", this._onDocumentMouseOutDelegate);		
	},
	
	_treeMouseOver : function (e)
	{
	    Telerik.Web.UI.RadTreeView._lastHoveredTreeView = this;
	},
	
	_mouseOver : function (e)
	{
		var node = this._extractNodeFromDomElement(e.eventMapTarget);
		if (this._highlightedNode)
		{
			this._highlightedNode._unhighlight();
		}
		node._highlight();
		
		if(node.get_expandMode() != Telerik.Web.UI.TreeNodeExpandMode.ServerSide)
		    this._expandOnHover(e);
		
		if (Telerik.Web.UI.RadTreeView._draggingTreeView && !node.get_allowDrop())
		{
		    node.get_textElement().style.cursor = "not-allowed";
		}
											
		this._highlightedNode = node;
		this._raiseEvent("mouseOver", node, e);
	},
	
	_mouseOut : function (e)
	{
	    
		if (!this._highlightedNode)
			return;
			
		var relatedTarget = e.eventMapRelatedTarget;
		
		if (!relatedTarget)
			return;

		if ($telerik.isDescendant(this._highlightedNode.get_textElement(), 
			relatedTarget))
		{
			return;
		}
		
		var node = this._highlightedNode;
		this._highlightedNode._unhighlight();		
		
		if (Telerik.Web.UI.RadTreeView._draggingTreeView)
		{
		    node.get_textElement().style.cursor = "default";
		}						
				
		this._highlightedNode = null;
		this._raiseEvent("mouseOut", node, e);
	},
	
	_editNodeText : function (node, text, shouldPostback)
	{
		var eventArgs = new Telerik.Web.UI.RadTreeNodeEditingEventArgs(node, text);
	    this.raiseEvent("nodeEditing", eventArgs);

	    if(eventArgs.get_cancel())
	    {
	        return false;
        }

	    node._text = text;
	    node._properties.setValue("text", text, true);	
	    
	    this._raiseEvent("nodeEdited", node, null);
	    
	    if(this._postBackOnEdit && shouldPostback)
	    {	    	    	    
	        var command = {};
	        command.commandName = "NodeEdit";
	        command.index = node._getHierarchicalIndex();
	        text = text.replace(/'/g,"&squote");
	        command.nodeEditText = encodeURIComponent(text);
	    
	        this._postback(command);
	    }
	    
	    return true;
	},
	
	_startEdit : function (node)
	{
	    node._startEdit();
	},
	
	_clearEdit : function ()
	{
	    this._editing = false;
	    this._editNode = null;
	},
	
	_endEdit : function (cancel)
	{
	    if(this._editing)
	    {
	        this._editNode._endEdit(cancel);
	    }
	},
	
	_nodeMouseOut : function (e)
	{
	    var node = this._extractNodeFromDomElement(e.eventMapTarget);
   		this._hoveredNode = null;
	},
	
	_click : function (e)
	{
		var node = this._extractNodeFromDomElement(e.eventMapTarget);		
		
		if (this._raiseCancelEvent("nodeClicking", node, e))
		{
		    e.preventDefault();
			return;
		}
		
		if (!node.get_isEnabled())
		{
			this._raiseEvent("nodeClicked", node, e);
			e.preventDefault();
			return;
		}
		
		this._hideContextMenus();				
			
		if(this.get_multipleSelect() && (e.ctrlKey || e.shiftKey))
		{
		    node.set_selected(!node.get_selected());
		    return;
		}
		else
		{
			if(this.get_allowNodeEditing() && node.get_selected() && node.get_allowEdit())
			{
				this._clearSelectedNodes();
				node.set_selected(true);
				this._startEdit(node);
				e.stopPropagation();
			}
			else
			{
				this._clearSelectedNodes();
				node.set_selected(true);
			}
		}

		this._raiseEvent("nodeClicked", node, e);

        this._postClickCommand(node);

		return;
	},
	
	_raiseEvent : function (eventName, node, domEvent)
	{
        var eventArgs = new Telerik.Web.UI.RadTreeNodeEventArgs(node, domEvent);
		this.raiseEvent(eventName, eventArgs);
	},
	
	_raiseCancelEvent : function (eventName, node, domEvent)
	{
        var eventArgs = new Telerik.Web.UI.RadTreeNodeCancelEventArgs(node, domEvent);		
		this.raiseEvent(eventName, eventArgs);
		return eventArgs.get_cancel();
	},
	
	add_mouseOver : function (eventHandler)
	{
		this.get_events().addHandler("mouseOver", eventHandler);
	},
	
	remove_mouseOver : function (eventHandler)
	{
		this.get_events().removeHandler("mouseOver", eventHandler);
	},

	add_mouseOut : function (eventHandler)
	{
		this.get_events().addHandler("mouseOut", eventHandler);
	},
	
	remove_mouseOut : function (eventHandler)
	{
		this.get_events().removeHandler("mouseOut", eventHandler);
	},

	add_nodePopulating : function(handler)
	{
		this.get_events().addHandler("nodePopulating", handler);
	},
	
	remove_nodePopulating : function(handler)
	{
		this.get_events().removeHandler("nodePopulating", handler);
	},
	
	add_nodePopulated: function(handler)
	{
		this.get_events().addHandler("nodePopulated", handler);
	},
	
	remove_nodePopulated: function(handler)
	{
		this.get_events().removeHandler("nodePopulated", handler);
	},
	
	add_nodePopulationFailed: function(handler)
	{
		this.get_events().addHandler("nodePopulationFailed", handler);
	},
	
	remove_nodePopulationFailed: function(handler)
	{
		this.get_events().removeHandler("nodePopulationFailed", handler);
	},
	
	add_nodeChecked : function (eventHandler)
	{
		this.get_events().addHandler("nodeChecked", eventHandler);
	},
	
	remove_nodeChecked : function (eventHandler)
	{
		this.get_events().removeHandler("nodeChecked", eventHandler);
	},
	
	add_nodeChecking : function (eventHandler)
	{
		this.get_events().addHandler("nodeChecking", eventHandler);
	},
	
	remove_nodeChecking : function (eventHandler)
	{
		this.get_events().removeHandler("nodeChecking", eventHandler);
	},
	
	add_nodeClicking : function (eventHandler)
	{
		this.get_events().addHandler("nodeClicking", eventHandler);
	},
	
	remove_nodeClicking : function (eventHandler)
	{
		this.get_events().removeHandler("nodeClicking", eventHandler);
	},

	add_nodeDragStart : function (eventHandler)
	{
		this.get_events().addHandler("nodeDragStart", eventHandler);
	},
	
	remove_nodeDragStart : function (eventHandler)
	{
		this.get_events().removeHandler("nodeDragStart", eventHandler);
	},
	
	add_nodeDragging : function (eventHandler)
	{
		this.get_events().addHandler("nodeDragging", eventHandler);
	},
	
	remove_nodeDragging : function (eventHandler)
	{
		this.get_events().removeHandler("nodeDragging", eventHandler);
	},	

	add_nodeExpanding : function (eventHandler)
	{
		this.get_events().addHandler("nodeExpanding", eventHandler);
	},
	
	remove_nodeExpanding : function (eventHandler)
	{
		this.get_events().removeHandler("nodeExpanding", eventHandler);
	},
	
	add_nodeCollapsing : function (eventHandler)
	{
		this.get_events().addHandler("nodeCollapsing", eventHandler);
	},
	
	remove_nodeCollapsing : function (eventHandler)
	{
		this.get_events().removeHandler("nodeCollapsing", eventHandler);
	},
	
	add_nodeClicked : function (eventHandler)
	{
		this.get_events().addHandler("nodeClicked", eventHandler);
	},
	
	remove_nodeClicked : function (eventHandler)
	{
		this.get_events().removeHandler("nodeClicked", eventHandler);
	},	

	add_nodeDoubleClick : function (eventHandler)
	{
		this.get_events().addHandler("nodeDoubleClick", eventHandler);
	},
	
	remove_nodeDoubleClick : function (eventHandler)
	{
		this.get_events().removeHandler("nodeDoubleClick", eventHandler);
	},
	
	add_nodeExpanded : function (eventHandler)
	{
		this.get_events().addHandler("nodeExpanded", eventHandler);
	},
	
	remove_nodeExpanded : function (eventHandler)
	{
		this.get_events().removeHandler("nodeExpanded", eventHandler);
	},
	
	add_nodeCollapsed : function (eventHandler)
	{
		this.get_events().addHandler("nodeCollapsed", eventHandler);
	},
	
	remove_nodeCollapsed : function (eventHandler)
	{
		this.get_events().removeHandler("nodeCollapsed", eventHandler);
	},
	
	add_nodeDropping : function (eventHandler)
	{
	    this.get_events().addHandler("nodeDropping", eventHandler);	    
	},
	
	remove_nodeDropping : function (eventHandler)
	{
	    this.get_events().removeHandler("nodeDropping", eventHandler);
	},

	add_nodeDropped : function (eventHandler)
	{
	    this.get_events().addHandler("nodeDropped", eventHandler);	    
	},
	
	remove_nodeDropped : function (eventHandler)
	{
	    this.get_events().removeHandler("nodeDropped", eventHandler);
	},

	add_contextMenuItemClicking : function (eventHandler)
	{
		this.get_events().addHandler("contextMenuItemClicking", eventHandler);
	},
	
	remove_contextMenuItemClicking : function (eventHandler)
	{
		this.get_events().removeHandler("contextMenuItemClicking", eventHandler);
	},

	_raiseContextMenuItemClicking : function (node, menuItem)
	{
		var eventArgs = new Telerik.Web.UI.RadTreeViewContextMenuItemCancelEventArgs(node, menuItem);
		this.raiseEvent("contextMenuItemClicking", eventArgs);
		return eventArgs.get_cancel();
	},

	add_contextMenuItemClicked : function (eventHandler)
	{
		this.get_events().addHandler("contextMenuItemClicked", eventHandler);
	},
	
	remove_contextMenuItemClicked : function (eventHandler)
	{
		this.get_events().removeHandler("contextMenuItemClicked", eventHandler);
	},

	add_contextMenuShowing : function (eventHandler)
	{
		this.get_events().addHandler("contextMenuShowing", eventHandler);
	},
	
	remove_contextMenuShowing : function (eventHandler)
	{
		this.get_events().removeHandler("contextMenuShowing", eventHandler);
	},

	add_contextMenuShown : function (eventHandler)
	{
		this.get_events().addHandler("contextMenuShown", eventHandler);
	},
	
	remove_contextMenuShown : function (eventHandler)
	{
		this.get_events().removeHandler("contextMenuShown", eventHandler);
	},

	add_nodeEditing : function (eventHandler)
	{
	    this.get_events().addHandler("nodeEditing", eventHandler);
	},

	remove_nodeEditing : function (eventHandler)
	{
	    this.get_events().removeHandler("nodeEditing", eventHandler);
	},

	add_nodeEdited : function (eventHandler)
	{
	    this.get_events().addHandler("nodeEdited", eventHandler);
	},

	remove_nodeEdited : function (eventHandler)
	{
	    this.get_events().removeHandler("nodeEdited", eventHandler);
	},
	
	add_keyPressing : function (eventHandler)
	{
		this.get_events().addHandler("keyPressing", eventHandler);
	},
	
	remove_keyPressing : function (eventHandler)
	{
		this.get_events().removeHandler("keyPressing", eventHandler);
	},
	
	add_load : function (eventHandler)
	{
		this.get_events().addHandler("load", eventHandler);
	},
	
	remove_load : function (eventHandler)
	{
		this.get_events().removeHandler("load", eventHandler);
	},
	
	add_nodeDataBound : function (eventHandler)
	{
		this.get_events().addHandler("nodeDataBound", eventHandler);
	},
	
	remove_nodeDataBound : function (eventHandler)
	{
		this.get_events().removeHandler("nodeDataBound", eventHandler);
	},
	
	dispose : function ()
	{
		this._removeContextMenuHandlers();
		
		this._removeMouseMoveHandler();
					
	    $removeHandler(document.documentElement, "keydown", this._onDocumentKeyDownDelegate);
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, 'dispose');
	},
	
	_removeMouseMoveHandler : function ()
	{
	    if(!this._mouseMoveAttached) return;
	    
	    if($telerik.isIE)
		{
		    document.detachEvent("onmousemove",this._onDocumentMouseMoveDelegate);
		}
		else
		{
            $removeHandler(document, "mousemove", this._onDocumentMouseMoveDelegate);
		}
		this._mouseMoveAttached = false;
	},

	_ensureChildControls : function ()
	{
		if (this._initializeComplete)
		{
			Telerik.Web.UI.RadTreeView.callBaseMethod(this, "_ensureChildControls");
		}
	},	

	_createChildControls : function ()
	{
		this._children = new Telerik.Web.UI.RadTreeNodeCollection(this);
		Telerik.Web.UI.RadTreeView._createNodesFromJson(this, this._children);
	},

	get_nodes : function ()
	{
		return this._getChildren();
	},

	get_nodeData : function ()
	{
		return this._nodeData;
	},

	set_nodeData : function (value)
	{
		this._nodeData = value;
	},
	
	get_multipleSelect : function()
	{
		return this._multipleSelect;
	},
	
	set_multipleSelect : function(value)
	{
		this._multipleSelect = value;
	},
	
	get_singleExpandPath : function()
	{
		return this._singleExpandPath;
	},
	
	set_singleExpandPath : function(value)
	{
		this._singleExpandPath = value;
	},
	
	get_selectedIndexes : function()
	{
		return this._selectedIndexes;
	},
	
	set_selectedIndexes : function(value)
	{
		this._selectedIndexes = value;
	},
	
	get_expandedIndexes : function()
	{
		return this._expandedIndexes;
	},
	
	set_expandedIndexes : function(value)
	{
		this._expandedIndexes = value;
	},
	
	get_collapsedIndexes : function()
	{
		return this._collapsedIndexes;
	},
	
	set_collapsedIndexes : function(value)
	{
		this._collapsedIndexes = value;
	},
	
	get_contextMenuIDs : function()
	{
		/// <exclude/>
		return this._contextMenuIDs;
	},

	set_contextMenuIDs : function(contextMenuIDs)
	{
		/// <exclude/>
		this._contextMenuIDs = contextMenuIDs;
		this._contextMenus = null;
	},

	get_contextMenus : function()
	{
		if (!this._contextMenus)
		{
			this._contextMenus = [];
			var contextMenuIDs = this.get_contextMenuIDs();
			for (var i=0; i<contextMenuIDs.length; i++)
			{
				Array.add(this._contextMenus, $find(this._resolveContextMenuID(contextMenuIDs[i])));
			}
		}
		return this._contextMenus;
	},

	get_allowNodeEditing : function ()
	{
	    return this._allowNodeEditing;
	},
	
	set_allowNodeEditing : function (value)
	{
	    this._allowNodeEditing = value;
	},
	
	get_enableDragAndDrop : function ()
	{
	    return this._enableDragAndDrop;
	},
	
	set_enableDragAndDrop : function (value)
	{
	    this._enableDragAndDrop = value;
	},
	
	get_enableDragAndDropBetweenNodes : function ()
	{
	    return this._enableDragAndDropBetweenNodes;
	},
	
	set_enableDragAndDropBetweenNodes : function (value)
	{
	    this._enableDragAndDropBetweenNodes = value;
	},
	
	get_checkedIndexes : function ()
	{
		return this._checkedIndexes;
	},
	
	set_checkedIndexes : function(value)
	{
		this._checkedIndexes = value;
	},
	
	get_webServiceSettings: function()
	{
		/// <exclude/>
		
		return this._webServiceSettings;
	},
	
	set_webServiceSettings: function(value)
	{
		/// <exclude/>
		
		var deserializedWebServiceSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings(deserializedWebServiceSettings);
	},
	
	get_persistLoadOnDemandNodes : function ()
	{
		return this._persistLoadOnDemandNodes;
	},
	
	set_persistLoadOnDemandNodes : function (value)
	{
		this._persistLoadOnDemandNodes = value;
	},
	
	_childRemoved : function (node, parent)
    {
		this._restoreClientState();
		
		if (this._threeState)
			parent._refreshCheckState(this);
					
		node._removeFromDom(parent);
		
		if (parent.get_nodes().get_count() < 1)
		{			
			if (parent != this)
			{
		        parent.get_element().removeChild(parent.get_childListElement());
		        parent._nodeListElement = null;
						
				parent.get_contentElement().removeChild(parent.get_toggleElement());
				parent._toggleElement = null;
			}
		}
		
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, "_childRemoved", [node, parent]);
    },
    
    _childRemoving : function (node)
    {
        this._unregisterNodeHierarchyFromClientState(node);
    
		node.set_selected(false);
		node._setChecked(this, false);
			
		this._backupClientState();
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, "_childRemoving", [node]);
    },
    
    _childInserting : function (index, node, parent)
    {
		if (!parent._childControlsCreated) return;
		
		this._backupClientState();
    },
    
    _childInserted : function(index, node, parent)
    {
		if (!parent._childControlsCreated) return;
		
		this._restoreClientState();
		
		if (this._threeState)
			node._updateParentCheckState(this);
			
		Telerik.Web.UI.RadTreeView.callBaseMethod(this, "_childInserted", [index, node, parent]);
    },
    
    _childrenCleared : function(parent)
    {
        this._unregisterNodeChildrenFromClientState(parent);
        Telerik.Web.UI.RadTreeView.callBaseMethod(this, "_childrenCleared", [parent]);                
    },
          
    /*------- Load On Demand --------*/
    
    _doLoadOnDemand : function (node)
	{
		var nodePopulatingArgs = new Telerik.Web.UI.RadTreeNodePopulatingEventArgs(node, null);
		this.raiseEvent("nodePopulating", nodePopulatingArgs);
		
		if (nodePopulatingArgs.get_cancel())
		{
			node._properties.setValue("expanded", false);
			return;
		}
		
		var command = String.format("{{commandName:\"LOD\",index:\"{0}\",data:{1},clientState:{2}}}",
		node._getHierarchicalIndex(), 
		Sys.Serialization.JavaScriptSerializer.serialize(node._getData()),
		this.saveClientState()
		);
		
		if (this.get_loadingStatusPosition() != Telerik.Web.UI.TreeViewLoadingStatusPosition.None)
		{
			node.showLoadingStatus(this.get_loadingMessage(), this.get_loadingStatusPosition());
		}
		
		var onCallback = Function.createDelegate(this, this._onCallbackResponse);
		var onError = Function.createDelegate(this, this._onCallbackError);
		WebForm_DoCallback(this._uniqueId, 
			command, onCallback, node, onError, true);
	},
	
	_onCallbackError : function (error, node)
	{
		var errorMessage = this._extractErrorMessage(error);

		this._onLoadOnDemandFailed(errorMessage, node);
	},
	
	_onCallbackResponse : function (response, node)
	{
		if (this.get_loadingStatusPosition() != Telerik.Web.UI.TreeViewLoadingStatusPosition.None)
		{
			node.hideLoadingStatus();
		}
		
		var responseComponents = response.split("_$$_");
		node._itemData = eval(responseComponents[0]);
		
		node._childControlsCreated = false;
		
		var childListElement = node.get_childListElement();
		if (!childListElement)
		{
			childListElement = node._createChildListElement();
			childListElement.style.display = "none";
			node.get_element().appendChild(childListElement);
		}

		childListElement.innerHTML = responseComponents[1];
		node._updateToggle();
		node._updateImageUrl();
		
		var persistNodes = this.get_persistLoadOnDemandNodes();
		if (persistNodes)
			this.trackChanges();
		
		node.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);		
		
		var children = node._getAllItems();
		for (var i = 0; i < children.length; i++)					
		{
		    if(children[i].get_checked())
		        this._registerCheckedNode(children[i]);
		        
		    if(children[i].get_selected())
		        this._registerSelectedNode(children[i]);
		        	    
			if (persistNodes)
				this._log.logInsert(children[i]);
		}
		
		if (this._threeState)
			node._refreshCheckState();
			
		if (persistNodes)
			this.commitChanges();

		var nodePopulatedArgs = new Telerik.Web.UI.RadTreeNodePopulatedEventArgs(node);
		this.raiseEvent("nodePopulated", nodePopulatedArgs);
			
		if(node.get_nodes().get_count() > 0)
		    node._displayChildren(true);
		else
		    node._removeToggle();		    
	},
	
	// Web Service LOD	
	_initializeWebServiceLoader : function()
	{
		this._webServiceLoader = new Telerik.Web.UI.WebServiceLoader(this.get_webServiceSettings());
		this._webServiceLoader.add_loadingStarted(Function.createDelegate(this, this._onNodeLoadingStarted));
		this._webServiceLoader.add_loadingSuccess(Function.createDelegate(this, this._onNodeLoadingSuccess));
		this._webServiceLoader.add_loadingError(Function.createDelegate(this, this._onNodeLoadingError));
	},
	
	_loadChildrenFromWebService : function (node)
	{
		if (!this._webServiceLoader)
			this._initializeWebServiceLoader();
		
		var userContext = { };
		var nodePopulatingArgs = new Telerik.Web.UI.RadTreeNodePopulatingEventArgs(node, userContext);
		this.raiseEvent("nodePopulating", nodePopulatingArgs);
		
		if (nodePopulatingArgs.get_cancel())
		{
			node._properties.setValue("expanded", false);
			return;
		}
				
		var params = { node: node._getNodeData(), context: userContext };
		this._webServiceLoader.loadData(params, node);
	},

	_onNodeLoadingStarted : function(sender, eventArgs)
	{
		var node = eventArgs.get_context();

		if (this.get_loadingStatusPosition() != Telerik.Web.UI.TreeViewLoadingStatusPosition.None)
		{
			node.showLoadingStatus(this.get_loadingMessage(), this.get_loadingStatusPosition());
		}
	},
	
	_onNodeLoadingSuccess : function(sender, eventArgs)
	{
		var result = eventArgs.get_data();
		var node = eventArgs.get_context();
		var persistNodes = this.get_persistLoadOnDemandNodes();
		
		if (this.get_loadingStatusPosition() != Telerik.Web.UI.TreeViewLoadingStatusPosition.None)
		{
			node.hideLoadingStatus();
		}

		node._updateToggle();
		
		if (persistNodes)
		{
			this.trackChanges();
		}
		
		var childNodes = node.get_nodes();
		for (i = 0; i < result.length; i++)
		{
			var nodeData = result[i];
			var dynamicNode = new Telerik.Web.UI.RadTreeNode();
			dynamicNode._loadFromDictionary(nodeData);
			childNodes.add(dynamicNode);
			var nodeDataBoundEventArgs = new Telerik.Web.UI.RadTreeNodeDataBoundEventArgs(dynamicNode, nodeData);
			this.raiseEvent("nodeDataBound", nodeDataBoundEventArgs);
		}		
		
		node.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);				
		
		if (persistNodes)
		{
			this.commitChanges();
		}
		
		if(node.get_nodes().get_count() > 0)
		{
		    // Milushev: Fixes expand animation 'jumping'
		    node.set_expanded(false);
		    node.set_expanded(true);
		}
		else
		{
		    node._removeToggle();
		}

		var nodePopulatedArgs = new Telerik.Web.UI.RadTreeNodePopulatedEventArgs(node);
		this.raiseEvent("nodePopulated", nodePopulatedArgs);
	},

	_onNodeLoadingError : function (sender, eventArgs)
	{
		var errorMessage = eventArgs.get_message();
		var node = eventArgs.get_context();
				
		this._onLoadOnDemandFailed(errorMessage, node);
	},
	
	_onLoadOnDemandFailed : function(errorMessage, node)
	{
		// Restore the expanded state, so the LOD operation can be retried.
		node._properties.setValue("expanded", false);

		if (this.get_loadingStatusPosition() != Telerik.Web.UI.TreeViewLoadingStatusPosition.None)
		{
			node.hideLoadingStatus();
		}

		var nodePopulationFailedArgs = new Telerik.Web.UI.RadTreeNodePopulationFailedEventArgs(node, errorMessage);
		this.raiseEvent("nodePopulationFailed", nodePopulationFailedArgs);
		
		if (nodePopulationFailedArgs.get_cancel())
		{
			return;
		}	

		alert(errorMessage);
	},
	
	_clearLog : function ()
	{
	    this._log.initialize();
        this._logEntriesJson = "[]";
        this.updateClientState();
	}
}

Telerik.Web.UI.RadTreeView._htmlDecode = function(text)
{
    var escapedSymbols = {'&lt;':'<', '&gt;':'>', '&amp;':'&', '&quot;':'"'};

    for(var symbol in escapedSymbols)
    text = text.replace(new RegExp(symbol, 'g'), escapedSymbols[symbol]);

    return text;
}

Telerik.Web.UI.RadTreeView._htmlEncode = function(text)
{
    var escapedSymbols = {'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;'};

    for(var symbol in escapedSymbols)
    text = text.replace(new RegExp(symbol, 'g'), escapedSymbols[symbol]);

    return text;
}

Telerik.Web.UI.RadTreeView._regExEscape = function(text)
{
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

Telerik.Web.UI.RadTreeView._preInitialize = function(elementId, scrollPosition)
{
    var element = $get(elementId);
    
    element.scrollTop = scrollPosition;
    
    if(Telerik.Web.UI.RadTreeView._isRtl(element))
    {
        Telerik.Web.UI.RadTreeView._initializeRtl(element);
    }
}

Telerik.Web.UI.RadTreeView._isRtl = function(element)
{
    while (element)
    {
        if (element.dir && element.dir.toLowerCase() == "rtl")
        {
            return true;
        }
        element = element.parentNode;
    }
    return false;
}

Telerik.Web.UI.RadTreeView._initializeRtl = function (treeElement)
{
    treeElement.style.styleFloat = "right";
    treeElement.style.cssFloat = "right";        
}

Telerik.Web.UI.RadTreeView._clearLog = function(treeId)
{
    var treeView = $find(treeId);
    if(treeView)
        treeView._clearLog();
}

Telerik.Web.UI.RadTreeView._draggingTreeView = null;
Telerik.Web.UI.RadTreeView._lastHoveredTreeView = null;

Telerik.Web.UI.RadTreeView.registerClass('Telerik.Web.UI.RadTreeView', Telerik.Web.UI.ControlItemContainer);;
/* END Telerik.Web.UI.TreeView.RadTreeViewScripts.js */
/* START Telerik.Web.UI.Grid.RadGridScripts.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridColumn = function(element) 
{
    Telerik.Web.UI.GridColumn.initializeBase(this, [element]);
    
    this._owner = {};
    this._data = {};
    this._resizeTolerance = 5;
    this._onMouseUpDelegate = null;
    this._columnResizer = null;
};

Telerik.Web.UI.GridColumn.prototype = 
{
    initialize : function() 
    {   
        Telerik.Web.UI.GridColumn.callBaseMethod(this, 'initialize');

        this._onMouseDownDelegate = Function.createDelegate(this, this._onMouseDownHandler);
        $addHandler(this.get_element(), "mousedown", this._onMouseDownDelegate);
        
        this.get_element().UniqueName = this.get_uniqueName();

        this._onLocalMouseMoveDelegate = Function.createDelegate(this, this._onLocalMouseMoveHandler);
        $addHandler(this.get_element(), "mousemove", this._onLocalMouseMoveDelegate);
        
        $addHandlers(this.get_element(), {click:Function.createDelegate(this, this._onClick)});
        $addHandlers(this.get_element(), {dblclick:Function.createDelegate(this, this._onDblClick)});
        $addHandlers(this.get_element(), {mouseover:Function.createDelegate(this, this._onMouseOver)});
        $addHandlers(this.get_element(), {mouseout:Function.createDelegate(this, this._onMouseOut)});
        $addHandlers(this.get_element(), {contextmenu:Function.createDelegate(this, this._onContextMenu)});
    },

    dispose : function() 
    {
        if (this._columnResizer)
            this._columnResizer.dispose();
        
        this._owner._owner.raise_columnDestroying(Sys.EventArgs.Empty);        
        $clearHandlers(this.get_element());
        
        this._element.control = null;
        this._element = null;

        Telerik.Web.UI.GridColumn.callBaseMethod(this, 'dispose');
    },

    get_owner : function()
    {
        return this._owner;
    },

    _onMouseDownHandler : function(e)
    {
        if (!this._onMouseUpDelegate)
        {
            this._onMouseUpDelegate = Function.createDelegate(this, this._onMouseUpHandler);
           // $addHandler(document, "mouseup", this._onMouseUpDelegate);    
           $telerik.addExternalHandler(document, "mouseup", this._onMouseUpDelegate);
        }
        
        if(this._owner._owner.ClientSettings.AllowDragToGroup || this._owner._owner.ClientSettings.AllowColumnsReorder)
        {
            this._onMouseMoveDelegate = Function.createDelegate(this, this._onMouseMoveHandler);
            //$addHandler(document, "mousemove", this._onMouseMoveDelegate);
            $telerik.addExternalHandler(document, "mousemove", this._onMouseMoveDelegate);
            
            if(this._canDragDrop && 
                ((this._data.Reorderable && this._owner._owner.ClientSettings.AllowColumnsReorder) || 
                (this._data.Groupable && this._owner._owner.ClientSettings.AllowDragToGroup)))
            {
                Telerik.Web.UI.Grid.CreateDragDrop(e, this, true);
            }
        }

//        if(this._owner._owner.ClientSettings.Resizing && 
//            this._owner._owner.ClientSettings.Resizing.AllowColumnResize)
//        {
//            if(this._canResize && this.get_resizable())
//            {
//                this._isResize = true;
//                Telerik.Web.UI.Grid.CreateColumnResizers(this, e);
//            }
//         }

        //this.AttachDomEvent(document, "mouseup", "OnMouseUp");
        
	    if (this._canResize && (e.button == 0))
	    {
	        var positionX = Telerik.Web.UI.Grid.GetEventPosX(e);
	        var startX = Telerik.Web.UI.Grid.FindPosX(this.get_element());
	        var endX = startX + this.get_element().offsetWidth;

            
	        if ((positionX >= endX - this._resizeTolerance) && 
		        (positionX <= endX + this._resizeTolerance))
	        {
		        this._columnResizer = new Telerik.Web.UI.GridColumnResizer(this, this._owner._owner.ClientSettings.Resizing.EnableRealTimeResize);
		        this._columnResizer._position(e);
	        }

		    Telerik.Web.UI.Grid.ClearDocumentEvents();
	    }
    },
    
    _onMouseUpHandler : function(e)
    {        
        if (this._onMouseUpDelegate)
        {
            //$removeHandler(document, "mouseup", this._onMouseUpDelegate);
            $telerik.removeExternalHandler(document, "mouseup", this._onMouseUpDelegate);
            this._onMouseUpDelegate = null;
        }
            
        if (this._onMouseMoveDelegate)
        {
            //$removeHandler(document, "mousemove", this._onMouseMoveDelegate);
            $telerik.removeExternalHandler(document, "mouseup", this._onMouseUpDelegate);
            this._onMouseMoveDelegate = null;
        }

        if(!Telerik.Web.UI.Grid)
            return;

	    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	    if (currentElement != null && this._canDragDrop && !this._isResize)
	    {
            var postBackFunction = this._owner._owner.ClientSettings.PostBackFunction;
		    postBackFunction = postBackFunction.replace("{0}", this._owner._owner.UniqueID);

		    if (this._owner._owner.ClientSettings.AllowDragToGroup 
		        && this._owner._owner._groupPanel
		        && Telerik.Web.UI.Grid.IsChildOf(currentElement, this._owner._owner._groupPanel.get_element()))
		    {
		        if(this._data.Groupable)
		        {
		            this._owner.groupColumn(this.get_element().UniqueName);
		        }
            }
            
            if(this._owner._owner.ClientSettings.AllowColumnsReorder &&
                Telerik.Web.UI.Grid.IsChildOf(currentElement, this.get_element().parentNode) &&
                currentElement != this.get_element() 
                )
            {
//                while(currentElement.parentNode != this.get_element().parentNode && 
//			            Telerik.Web.UI.Grid.IsChildOf(currentElement.parentNode, this.get_element().parentNode))
//		        {
//                    currentElement = currentElement.parentNode;
//		        }
//			        
                if (typeof(currentElement.UniqueName) != "undefined"
                    && this._canDropOnThisColumn(currentElement.UniqueName) && this.get_reorderable()){
                    
                        if(!this._owner._owner.ClientSettings.ReorderColumnsOnClient)
                        {
                            var column1 = this._owner.getColumnByUniqueName(this.get_element().UniqueName);
                            var column2 = this._owner.getColumnByUniqueName(currentElement.UniqueName);
                            var args = new Sys.CancelEventArgs();
                            args.get_gridSourceColumn = function ()
	                        {
		                        return column1;
	                        }
	                        args.get_gridTargetColumn = function ()
	                        {
		                        return column2;
	                        }
                            this._owner._owner.raise_columnSwapping(args);
                            if (args.get_cancel())
		                        return false;
                        
		                    postBackFunction = postBackFunction.replace("{1}", "ReorderColumns," + this._owner._data.UniqueID + "," + this.get_element().UniqueName + "," + currentElement.UniqueName);
			                eval(postBackFunction);
                        }
                        else
                        {
                            if(this._owner._owner.ClientSettings.ColumnsReorderMethod == 1)
                            {
                                this._owner.reorderColumns(this.get_element().UniqueName, currentElement.UniqueName);
                            }
                            else
                            {
                                this._owner.swapColumns(this.get_element().UniqueName, currentElement.UniqueName);
                            }
                        }
                }
            }
        }

        Telerik.Web.UI.Grid.DestroyDragDrop();

//        if(this._isResize)
//        {
//            Telerik.Web.UI.Grid.DestroyColumnResizers();
//            this._isResize = false;
//        }

        Telerik.Web.UI.Grid.RestoreDocumentEvents();
    },
    
    _onMouseMoveHandler : function(e)
    {
        if(this._canDragDrop)
        {
            Telerik.Web.UI.Grid.MoveDragDrop(e, this, true);
        }

//        if(this._isResize)
//        {
//            Telerik.Web.UI.Grid.MoveColumnResizers(this, e);
//        }
	},

    _onLocalMouseMoveHandler : function(e)
    {
        if(!Telerik.Web.UI.Grid)
            return;

        this._canDragDrop = true;
        this._canResize = false;
        
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
        var th = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "th");
        var x = Telerik.Web.UI.Grid.FindPosX(currentElement);        
        
        if((this._owner._owner.ClientSettings.AllowDragToGroup || 
            this._owner._owner.ClientSettings.AllowColumnsReorder) 
            && (this.get_reorderable() || this._data.Groupable))
        {            
            this.get_element().title = this._owner._owner.ClientSettings.ClientMessages.DragToGroupOrReorder;
            this.get_element().style.cursor = "move";
        }
        
        if(this._owner._owner.ClientSettings.Resizing.AllowColumnResize &&
            this.get_resizable() && Telerik.Web.UI.Grid.GetEventPosX(e) >= (x + th.offsetWidth - 5))
        {
            //this.get_element().style.cursor = "e-resize";
            this._canDragDrop = false;
            //this._canResize = true;
        }

	    if (this._owner._owner.ClientSettings 
	        && this._owner._owner.ClientSettings.Resizing.AllowColumnResize 
	        && this.get_resizable() 
	        && this.get_element().tagName.toLowerCase() == "th")
	    {
		    var positionX = Telerik.Web.UI.Grid.GetEventPosX(e);
		    var startX = Telerik.Web.UI.Grid.FindPosX(this.get_element());
		    var endX = startX + this.get_element().offsetWidth;
    		
		    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
    		
		    if(this._owner._owner.GridDataDiv && !this._owner._owner.GridHeaderDiv && !window.netscape)
		    {
		        var bodyMargin = 0;
			    if (document.body.currentStyle && document.body.currentStyle.margin
			     && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
	            {
		            bodyMargin = parseInt(document.body.currentStyle.marginLeft);
	            }

		        this._resizeTolerance = 10;
		    }

		    if ((positionX >= endX - this._resizeTolerance) && 
			    (positionX <= endX + this._resizeTolerance) && !this._owner._owner.MoveHeaderDiv)
		    {
			    this.get_element().style.cursor = "e-resize";
    			
			    this.get_element().title = this._owner._owner.ClientSettings.ClientMessages.DragToResize;

			    this._canResize = true;
			    currentElement.style.cursor = "e-resize";
			    this._owner._owner._isResize = true;
		    }
		    else
		    {		        
			    this.get_element().style.cursor = "";
			    this.get_element().title = "";
			    this._canResize = false;

			    currentElement.style.cursor = "";
			    this._owner._owner._isResize = false;
		    }
	    }

	},
	
	_canDropOnThisColumn : function(uniqueName)
	{
	    if (typeof(this._owner._columns) == "undefined")
	    {
	        this._owner._columns = {};

            for(var i = 0; i < this._owner._data._columnsData.length; i++)
	        {
	            this._owner._columns[this._owner._data._columnsData[i].UniqueName] = this._owner._data._columnsData[i];
	        }
	    }
	   return this._owner._columns[uniqueName].Reorderable;
	},
	
	_onContextMenu : function(e)
    {
        this._owner._owner.raise_columnContextMenu(new Telerik.Web.UI.GridColumnEventArgs(this, e));  
        if(this._owner._owner.get_events().getHandler("columnContextMenu"))
        {
            if (e.preventDefault)
            {
                e.preventDefault();
            }
            else
            {
                e.returnValue = false;
                return false;
            }    
        }  
    },

    _onClick : function(e)
    {
        this._owner._owner.raise_columnClick(new Telerik.Web.UI.GridColumnEventArgs(this, e));
    },

    _onDblClick : function(e)
    {
        this._owner._owner.raise_columnDblClick(new Telerik.Web.UI.GridColumnEventArgs(this, e));
    },
    
    _onMouseOver : function(e)
    {
        this._owner._owner.raise_columnMouseOver(new Telerik.Web.UI.GridColumnEventArgs(this, e));

        if(this._owner._owner.Skin != "")
        {
            Sys.UI.DomElement.addCssClass(this.get_element(),"GridHeaderOver_" + this._owner._owner.Skin);
        }
    },
    
    _onMouseOut : function(e)
    {
        this._owner._owner.raise_columnMouseOut(new Telerik.Web.UI.GridColumnEventArgs(this, e));

        if(this._owner._owner.Skin != "")
        {
            Sys.UI.DomElement.removeCssClass(this.get_element(),"GridHeaderOver_" + this._owner._owner.Skin);
        }
    },
    
    get_resizable : function() 
    {
        return this._data.Resizable;
    },
    
    set_resizable : function(value) 
    {
        if (this._data.Resizable != value) 
        {
            this._data.Resizable = value;
        }
    },
    
    get_reorderable : function() 
    {
        return this._data.Reorderable;
    },
    
    set_reorderable : function(value) 
    {
        if (this._data.Reorderable != value) 
        {
            this._data.Reorderable = value;
        }
    },
    
    get_uniqueName : function() 
    {
        return this._data.UniqueName;
    }
};

Telerik.Web.UI.GridColumn.registerClass('Telerik.Web.UI.GridColumn', Sys.UI.Control);

Telerik.Web.UI.GridColumnEventArgs = function(gridColumn, domEvent)
{
	Telerik.Web.UI.GridColumnEventArgs.initializeBase(this);
	this._gridColumn = gridColumn;
	this._domEvent = domEvent;
};

Telerik.Web.UI.GridColumnEventArgs.prototype = 
{
	get_gridColumn : function ()
	{
		return this._gridColumn;
	},

	get_domEvent : function ()
	{
		return this._domEvent;
	}
};

Telerik.Web.UI.GridColumnEventArgs.registerClass("Telerik.Web.UI.GridColumnEventArgs", Sys.EventArgs);

Telerik.Web.UI.GridColumnCancelEventArgs = function(gridColumn, domEvent) 
{
	Telerik.Web.UI.GridColumnCancelEventArgs.initializeBase(this);
	this._gridColumn = gridColumn;
	this._domEvent = domEvent;
};

Telerik.Web.UI.GridColumnCancelEventArgs.prototype = 
{
	get_gridColumn : function ()
	{
		return this._gridColumn;
	},
	
	get_domEvent : function ()
	{
		return this._domEvent;
	}
};

Telerik.Web.UI.GridColumnCancelEventArgs.registerClass("Telerik.Web.UI.GridColumnCancelEventArgs", Sys.CancelEventArgs);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridColumnResizer = function(owner, isRealTimeResize)
{
    Telerik.Web.UI.GridColumnResizer.initializeBase(this);    
    
    this._isRealTimeResize = isRealTimeResize;
    
    this._column = owner;
	this._isRealTimeResize = isRealTimeResize;
	
	this._currentWidth = null;

	this._leftResizer = document.createElement("span");
	this._leftResizer.style.backgroundColor = "navy";
	this._leftResizer.style.width = "1" + "px";
	this._leftResizer.style.position = "absolute";
	this._leftResizer.style.cursor = "e-resize";

	this._rightResizer = document.createElement("span");
	this._rightResizer.style.backgroundColor = "navy";
	this._rightResizer.style.width = "1" + "px";
	this._rightResizer.style.position = "absolute";
	this._rightResizer.style.cursor = "e-resize";

	this._resizerToolTip = document.createElement("span");
	this._resizerToolTip.style.position = "absolute";

    if (this._column._owner._owner.Skin != "")
    {
		this._resizerToolTip.className = String.format("GridToolTip_{0}", this._column._owner._owner.Skin);
    }
    if (!this._column._owner._owner._embeddedSkin || this._column._owner._owner.Skin == "")
    {
		this._resizerToolTip.style.backgroundColor = "#F5F5DC";
		this._resizerToolTip.style.border = "1px solid";
		this._resizerToolTip.style.font = "icon";
		this._resizerToolTip.style.padding = "2px";
    }
    
	this._resizerToolTip.innerHTML = "Width: <b>" + this._column.get_element().offsetWidth + "</b> <em>pixels</em>";

	document.body.appendChild(this._leftResizer);
	document.body.appendChild(this._rightResizer);
	document.body.appendChild(this._resizerToolTip);
	
	this.CanDestroy = true;

    this._onMouseUpDelegate = Function.createDelegate(this, this._onMouseUpHandler);
    //$addHandler(document, "mouseup", this._onMouseUpDelegate);
    $telerik.addExternalHandler(document, "mouseup", this._onMouseUpDelegate);
    
    this._onMouseMoveDelegate = Function.createDelegate(this, this._onMouseMoveHandler);
    $addHandler(this._column._owner._owner.get_element(), "mousemove", this._onMouseMoveDelegate);
}

Telerik.Web.UI.GridColumnResizer.prototype = 
{
    dispose : function() 
    {
	    try
	    {
		    this._destroy();
	    }
	    catch (error)
	    {
	    }
    	
        if (this._onMouseUpDelegate)
            $telerik.removeExternalHandler(document, "mouseup", this._onMouseUpDelegate);
            //    $removeHandler(document, "mouseup", this._onMouseUpDelegate);
            
        if (this._onMouseMoveDelegate)
            $removeHandler(this._column._owner._owner.get_element(), "mousemove", this._onMouseMoveDelegate);
    	
	    this._leftResizer = null;
	    this._rightResizer = null;
	    this._resizerToolTip = null;    
    },
    
    _position : function(e)
    {
	    this._leftResizer.style.top = Telerik.Web.UI.Grid.FindPosY(this._column.get_element()) - 
									    Telerik.Web.UI.Grid.FindScrollPosY(this._column.get_element()) + 
									    document.documentElement.scrollTop + 
									    document.body.scrollTop + "px";

	    this._leftResizer.style.left = Telerik.Web.UI.Grid.FindPosX(this._column.get_element()) - 
									    Telerik.Web.UI.Grid.FindScrollPosX(this._column.get_element()) + 
									    document.documentElement.scrollLeft + 
									    document.body.scrollLeft + "px";

		if ($telerik.isIE || $telerik.isSafari2)
		{
			if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
			{
			 this._leftResizer.style.left = parseInt(this._leftResizer.style.left) - parseInt(document.body.currentStyle.marginLeft);
			}
			else if (document.defaultView && document.defaultView.getComputedStyle && 
				document.defaultView.getComputedStyle(document.body, "").marginLeft.indexOf("px") != -1 && !window.opera)
			{
				this._leftResizer.style.left = parseInt(this._leftResizer.style.left) - parseInt(document.defaultView.getComputedStyle(document.body, "").marginLeft);
			}
	        
			if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
			{
				this._leftResizer.style.top = parseInt(this._leftResizer.style.top) - parseInt(document.body.currentStyle.marginTop);
			}
			else if (document.defaultView && document.defaultView.getComputedStyle && 
				document.defaultView.getComputedStyle(document.body, "").marginTop.indexOf("px") != -1 && !window.opera)
			{
				this._leftResizer.style.top = parseInt(this._leftResizer.style.top) - parseInt(document.defaultView.getComputedStyle(document.body, "").marginTop);
			}
		}
        
	    this._rightResizer.style.top = this._leftResizer.style.top;
	    this._rightResizer.style.left = parseInt(this._leftResizer.style.left) +	this._column.get_element().offsetWidth + "px";

	    this._resizerToolTip.style.top = parseInt(this._rightResizer.style.top) - this._resizerToolTip.offsetHeight - 2 + "px";

	    this._resizerToolTip.style.left = parseInt(this._rightResizer.style.left) - 5 + "px";

	    if (parseInt(this._leftResizer.style.left) < Telerik.Web.UI.Grid.FindPosX(this._column._owner.get_element()))
	    {
		    this._leftResizer.style.display = "none";
	    }
    	
	    if(!this._column._owner._owner.ClientSettings.Scrolling.AllowScroll)
	    {
	        this._leftResizer.style.height = this._column._owner.get_element().tBodies[0].offsetHeight + this._column._owner.get_element().tHead.offsetHeight + "px";
	    }
	    else
	    {
	        if(this._column._owner._owner.ClientSettings.Scrolling.UseStaticHeaders)
	        {
	            this._leftResizer.style.height = this._column._owner._owner._gridDataDiv.clientHeight + this._column._owner.get_element().tHead.offsetHeight + "px";
	        }
	        else
	        {
	            this._leftResizer.style.height = this._column._owner._owner._gridDataDiv.clientHeight + "px";
	        }
	    }

        this._rightResizer.style.height = this._leftResizer.style.height;    
    },

    _onMouseUpHandler : function(e)
    {
	    this._destroy(e);
    },

    _onMouseMoveHandler : function(e)
    {
	    this._move(e);
    },

    _destroy : function(e)
    {
	    if (this.CanDestroy)
	    {
	        if (this._onMouseUpDelegate)
	        {
	            //$removeHandler(document, "mouseup", this._onMouseUpDelegate);
	            $telerik.removeExternalHandler(document, "mouseup", this._onMouseUpDelegate);
	            this._onMouseUpDelegate = null;
            }
	            
            if (this._onMouseMoveDelegate)
            {
                $removeHandler(this._column._owner._owner.get_element(), "mousemove", this._onMouseMoveDelegate);
                this._onMouseMoveDelegate = null;
            }
    		
		    if (this._currentWidth != null)
		    {
			    if (this._currentWidth > 0)
			    {
				    this._column._owner.resizeColumn(this._column.get_element().cellIndex, this._currentWidth);
				    this._currentWidth = null;
			    }
		    }

		    document.body.removeChild(this._leftResizer);
		    document.body.removeChild(this._rightResizer);
		    document.body.removeChild(this._resizerToolTip);
    	
		    this.CanDestroy = false;
	    }
    },


    _move : function(e)
    {
	    this._leftResizer.style.left = Telerik.Web.UI.Grid.FindPosX(this._column.get_element()) - 
									    Telerik.Web.UI.Grid.FindScrollPosX(this._column.get_element()) + 
									    document.documentElement.scrollLeft + 
									    document.body.scrollLeft + "px";
									    
		if ($telerik.isIE || $telerik.isSafari2)
		{
			if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
			{
			 this._leftResizer.style.left = parseInt(this._leftResizer.style.left) - parseInt(document.body.currentStyle.marginLeft);
			}
			else if (document.defaultView && document.defaultView.getComputedStyle && 
				document.defaultView.getComputedStyle(document.body, "").marginLeft.indexOf("px") != -1 && !window.opera)
			{
				this._leftResizer.style.left = parseInt(this._leftResizer.style.left) - parseInt(document.defaultView.getComputedStyle(document.body, "").marginLeft);
			}
		}
    									
	    this._rightResizer.style.left = parseInt(this._leftResizer.style.left) + (Telerik.Web.UI.Grid.GetEventPosX(e) - Telerik.Web.UI.Grid.FindPosX(this._column.get_element()))+ "px";

	    this._resizerToolTip.style.left = parseInt(this._rightResizer.style.left) - 5 + "px";

	    var width = parseInt(this._rightResizer.style.left) - parseInt(this._leftResizer.style.left);
    	
	    var deltaWidth = this._column.get_element().scrollWidth - width;
    	
	    this._resizerToolTip.innerHTML = "Width: <b>" + width + "</b> <em>pixels</em>";

	    if (!Telerik.Web.UI.Grid.FireEvent(this._column._owner, "OnColumnResizing", [this._column.Index, width]))
		    return;

	    if (width <= 0)
	    {
		    this._rightResizer.style.left = this._rightResizer.style.left;
		    this._destroy(e);
		    return;
	    }

	    this._currentWidth = width;

	    if (this._isRealTimeResize)
	    {
	        var columnIndex = (navigator.userAgent.indexOf("Safari") != -1)? Telerik.Web.UI.Grid.GetRealCellIndex(this._column._owner, this._column.get_element()) : this._column.get_element().cellIndex;

            this._column._owner.resizeColumn(columnIndex, width);
	    }
	    else
	    {
		    this._currentWidth = width;
		    return;
	    }

	    if (Telerik.Web.UI.Grid.FindPosX(this._leftResizer) != Telerik.Web.UI.Grid.FindPosX(this._column.get_element()))
	    {
		    this._leftResizer.style.left =  Telerik.Web.UI.Grid.FindPosX(this._column.get_element()) + "px";
	    }

	    if (Telerik.Web.UI.Grid.FindPosX(this._rightResizer) != (Telerik.Web.UI.Grid.FindPosX(this._column.get_element()) + this._column.get_element().offsetWidth))
	    {
		    this._rightResizer.style.left =  Telerik.Web.UI.Grid.FindPosX(this._column.get_element()) + this._column.get_element().offsetWidth + "px";
	    }

	    if (Telerik.Web.UI.Grid.FindPosY(this._leftResizer) != Telerik.Web.UI.Grid.FindPosY(this._column.get_element()))
	    {
		    this._leftResizer.style.top =  Telerik.Web.UI.Grid.FindPosY(this._column.get_element()) + "px";
		    this._rightResizer.style.top =  Telerik.Web.UI.Grid.FindPosY(this._column.get_element()) + "px";
	    }

	    if( this._column._owner._owner._gridDataDiv)
	    {
		     this._leftResizer.style.left = parseInt(this._leftResizer.style.left.replace("px","")) - this._column._owner._owner._gridDataDiv.scrollLeft + "px";
		     this._rightResizer.style.left = parseInt(this._leftResizer.style.left.replace("px","")) + this._column.get_element().offsetWidth + "px";
		     this._resizerToolTip.style.left = parseInt(this._rightResizer.style.left) - 5 + "px";
	    }
    	
        if(!this._column._owner._owner.ClientSettings.Scrolling.AllowScroll)
	    {
	        this._leftResizer.style.height = this._column._owner.get_element().tBodies[0].offsetHeight + this._column._owner.get_element().tHead.offsetHeight + "px";
	    }
	    else
	    {
	        if(this._column._owner._owner.ClientSettings.Scrolling.UseStaticHeaders)
	        {
	            this._leftResizer.style.height = this._column._owner._owner._gridDataDiv.clientHeight + this._column._owner.get_element().tHead.offsetHeight + "px";
	        }
	        else
	        {
	            this._leftResizer.style.height = this._column._owner._owner._gridDataDiv.clientHeight + "px";
	        }
	    }

        this._rightResizer.style.height = this._leftResizer.style.height;    
    }
};

Telerik.Web.UI.GridColumnResizer.registerClass("Telerik.Web.UI.GridColumnResizer", null, Sys.IDisposable);;Type.registerNamespace("Telerik.Web.UI");
Type.registerNamespace("Telerik.Web.UI.Grid");

Telerik.Web.UI.Grid._uniqueIDToClientID = function(uniqueID)
{
    return uniqueID.replace(/[$:]/g, '_');
};

Telerik.Web.UI.Grid.getTableHeaderRow = function(table)
{
    var headerRow = null;
    if (table.tHead)
	{
		for(var i = 0; i < table.tHead.rows.length;i++)
		{
			if (table.tHead.rows[i] != null)
			{
				if (table.tHead.rows[i].cells[0] != null)
				{
					if (table.tHead.rows[i].cells[0].tagName != null)
					{
						if (table.tHead.rows[i].cells[0].tagName.toLowerCase() == "th")
						{
							headerRow = table.tHead.rows[i];
							break;
						}
					}
				}
			}
		}
	}

    return headerRow;
};

Telerik.Web.UI.Grid.GetRealCellIndex = function (tableView, cell)
{
    for(var i = 0; i < tableView.get_columns().length; i++)
    {
        if(tableView.get_columns()[i].get_element() == cell)
        {
            return i;
        }
    }
};

Telerik.Web.UI.Grid.CopyAttributes = function(target, source)
{
    for(var i = 0; i < source.attributes.length; i++)
	{
		try
		{
			if (source.attributes[i].name.toLowerCase() == "id")
				continue;
				
			if (source.attributes[i].value != null && source.attributes[i].value != "null" && 
			    source.attributes[i].value != "")
			{
				target.setAttribute(source.attributes[i].name, source.attributes[i].value);
			}
		}
		catch(e)
		{
			continue;
		}
	}
};

Telerik.Web.UI.Grid.PositionDragElement = function(element, mouseEvent)
{    
    element.style.top =  mouseEvent.clientY + 
							document.documentElement.scrollTop + 
							document.body.scrollTop + 1 + "px";

	element.style.left = mouseEvent.clientX + 
							document.documentElement.scrollLeft + 
							document.body.scrollLeft + 1 + "px";
							
	if($telerik.isOpera || ($telerik.isSafari && !$telerik.isSafari3))
	{
	    element.style.top = parseInt(element.style.top) - document.body.scrollTop + "px";
	}
};

Telerik.Web.UI.Grid.ClearDocumentEvents = function()
{
    if (document.onmousedown != this.mouseDownHandler)
	{
		this.documentOnMouseDown = document.onmousedown;
	}

	if (document.onselectstart != this.selectStartHandler)
	{
		this.documentOnSelectStart = document.onselectstart;
	}

	if (document.ondragstart != this.dragStartHandler)
	{
		this.documentOnDragStart = document.ondragstart;
	}

	this.mouseDownHandler = function(e){return false;};
	this.selectStartHandler = function(){return false;};
	this.dragStartHandler = function(){return false;};

	document.onmousedown = this.mouseDownHandler;
	document.onselectstart = this.selectStartHandler;
	document.ondragstart = this.dragStartHandler;
};

Telerik.Web.UI.Grid.RestoreDocumentEvents = function()
{
	if ((typeof(this.documentOnMouseDown) == "function") &&
		(document.onmousedown != this.mouseDownHandler))
	{
		document.onmousedown = this.documentOnMouseDown;
	}
	else
	{
		document.onmousedown = "";
	}
	
	if ((typeof(this.documentOnSelectStart) == "function") &&
		(document.onselectstart != this.selectStartHandler))
	{
		document.onselectstart = this.documentOnSelectStart;
	}
	else
	{
		document.onselectstart = "";
	}
	
	if ((typeof(this.documentOnDragStart) == "function") &&
		(document.ondragstart != this.dragStartHandler))
	{
		document.ondragstart = this.documentOnDragStart;
	}
	else
	{
		document.ondragstart = "";
	}
};

Telerik.Web.UI.Grid.IsChildOf = function (node, parentNode)
{
	while (node.parentNode)
	{
		if (node.parentNode == parentNode)
		{
			return true;
		}
		node = node.parentNode;
	}
	return false;
};

Telerik.Web.UI.Grid.GetCurrentElement = function (e)
{
	if (!e)
		var e = window.event;

	var currentElement;

	if (e.srcElement)
	{
		currentElement = e.srcElement;
	}
	else
	{
		currentElement = e.target;
	}

	return currentElement;
};

Telerik.Web.UI.Grid.CreateReorderIndicators = function (currentElement, skin, imagesPath, adjustScrollPos, gridID)
{
	if ((this.ReorderIndicator1 == null) && (this.ReorderIndicator2 == null))
	{
		this.ReorderIndicator1 = document.createElement("span"); 
		this.ReorderIndicator2 = document.createElement("span"); 

		if (imagesPath != "")
		{
		    var topImg = new Image();
		    topImg.src = imagesPath + "MoveDown.gif";
		    var bottomImg = new Image();
		    bottomImg.src = imagesPath + "MoveUp.gif";
		    
			this.ReorderIndicator1.innerHTML = "<img src=\"" + imagesPath + "MoveDown.gif\" alt=\"reorder indicator\" />";
			this.ReorderIndicator2.innerHTML = "<img src=\"" + imagesPath + "MoveUp.gif\" alt=\"reorder indicator\" />";
		    this.ReorderIndicator1.className = "TopReorderImage_" + skin;
		    this.ReorderIndicator2.className = "BottomReorderImage_" + skin;
		}
        else if (skin == "")
        {
		    this.ReorderIndicator1.innerHTML = "&darr;";
		    this.ReorderIndicator2.innerHTML = "&uarr;"; 
		}
		else
		{
		    this.ReorderIndicator1.className = "TopReorderIndicator_" + skin;
		    this.ReorderIndicator2.className = "BottomReorderIndicator_" + skin;
		    this.ReorderIndicator1.style.width = this.ReorderIndicator1.style.height = 
		    this.ReorderIndicator2.style.width = this.ReorderIndicator2.style.height = "10px"; 
		}
		
		this.ReorderIndicator1.style.backgroundColor = "transparent";
		this.ReorderIndicator1.style.color = "darkblue";
		this.ReorderIndicator1.style.fontSize = "1px";

		this.ReorderIndicator2.style.backgroundColor = this.ReorderIndicator1.style.backgroundColor;
		this.ReorderIndicator2.style.color = this.ReorderIndicator1.style.color;
		this.ReorderIndicator2.style.fontSize = this.ReorderIndicator1.style.fontSize;

		var gridControl = $find(gridID);
		var dataDivScrollPosX = 0;
		var dataDivScrollPosY = 0;
		if (adjustScrollPos && currentElement.nodeName == "TH" && gridControl && gridControl.GridDataDiv)
		{
			var dataDivScrollPosX = gridControl.GridDataDiv.scrollLeft;
			if (!gridControl.ClientSettings.Scrolling.UseStaticHeaders)
			{
				var dataDivScrollPosY = gridControl.GridDataDiv.scrollTop;
			}
		}
		this.ReorderIndicator1.style.top = Telerik.Web.UI.Grid.FindPosY(currentElement) - dataDivScrollPosY - this.ReorderIndicator1.offsetHeight + "px";
		this.ReorderIndicator1.style.left = Telerik.Web.UI.Grid.FindPosX(currentElement) - dataDivScrollPosX + "px";

		this.ReorderIndicator2.style.top = Telerik.Web.UI.Grid.FindPosY(currentElement) - dataDivScrollPosY + currentElement.offsetHeight + "px";
		this.ReorderIndicator2.style.left = this.ReorderIndicator1.style.left;

		this.ReorderIndicator1.style.visibility = "hidden";
		this.ReorderIndicator1.style.display = "none";
		this.ReorderIndicator1.style.position = "absolute";

		this.ReorderIndicator2.style.visibility = this.ReorderIndicator1.style.visibility;
		this.ReorderIndicator2.style.display = this.ReorderIndicator1.style.display;
		this.ReorderIndicator2.style.position = this.ReorderIndicator1.style.position;

		document.body.appendChild(this.ReorderIndicator1);
		document.body.appendChild(this.ReorderIndicator2);
		
		if (imagesPath != "")
		{
		    this.ReorderIndicator1.style.marginLeft = - parseInt(topImg.width / 2) + "px";
		    this.ReorderIndicator2.style.marginLeft = - parseInt(bottomImg.width / 2) + "px";
			topImg = null;
			bottomImg = null;
		}
	}
};

Telerik.Web.UI.Grid.DestroyReorderIndicators = function()
{
	if ((this.ReorderIndicator1 != null) && (this.ReorderIndicator2 != null))
	{
		document.body.removeChild(this.ReorderIndicator1);
		document.body.removeChild(this.ReorderIndicator2);

		this.ReorderIndicator1 = null; 
		this.ReorderIndicator2 = null; 
	}
};

Telerik.Web.UI.Grid.MoveReorderIndicators = function (e, currentElement, adjustScrollPos, gridID)
{
	if ((this.ReorderIndicator1 != null) && (this.ReorderIndicator2 != null))
	{
		this.ReorderIndicator1.style.visibility = "visible";
		this.ReorderIndicator1.style.display = "";

		this.ReorderIndicator2.style.visibility = "visible";
		this.ReorderIndicator2.style.display = "";
		
		var gridControl = $find(gridID);
		var dataDivScrollPosX = 0;
		var dataDivScrollPosY = 0;
		if (adjustScrollPos && currentElement.nodeName == "TH" && gridControl && gridControl.GridDataDiv)
		{
			var dataDivScrollPosX = gridControl.GridDataDiv.scrollLeft;
			if (!gridControl.ClientSettings.Scrolling.UseStaticHeaders)
			{
				var dataDivScrollPosY = gridControl.GridDataDiv.scrollTop;
			}
		}
		this.ReorderIndicator1.style.top = Telerik.Web.UI.Grid.FindPosY(currentElement) - dataDivScrollPosY - this.ReorderIndicator1.offsetHeight + "px";
		this.ReorderIndicator1.style.left = Telerik.Web.UI.Grid.FindPosX(currentElement) - dataDivScrollPosX + "px";

		this.ReorderIndicator2.style.top = Telerik.Web.UI.Grid.FindPosY(currentElement) - dataDivScrollPosY + currentElement.offsetHeight + "px";
		this.ReorderIndicator2.style.left = this.ReorderIndicator1.style.left;
	}	
};

Telerik.Web.UI.Grid.getVisibleCols = function(cols)
{
    var count = 0;
    for (var i = 0, l = cols.length; i < l; i++)
	{
	    if(cols[i].style.display == "none")
	        continue;
	    count++;
    }
    return count;
};

Telerik.Web.UI.Grid.hideShowCells = function(table, index, display, cols)
{
     var totalVisibleCols = Telerik.Web.UI.Grid.getVisibleCols(cols);

     for (var i = 0, l = table.rows.length; i < l; i++)
	 {
	    if(table.rows[i].cells.length != totalVisibleCols)
	    {
	        if(table.rows[i].cells.length == 1)
	        {
	            table.rows[i].cells[0].colSpan = totalVisibleCols;
	        }
	        else
	        {
	            for (var j = 0; j < table.rows[i].cells.length; j++)
	            {
	                if(table.rows[i].cells[j].colSpan > 1 && j >= index)
	                {
	                    if(!display)
	                    {
	                        table.rows[i].cells[j].colSpan = table.rows[i].cells[j].colSpan - 1;
	                    }
	                    else
	                    {
	                        table.rows[i].cells[j].colSpan = table.rows[i].cells[j].colSpan + 1;
	                    }
	                    break;
	                }
	            }
	        }
	    }
	    
	    var cell = table.rows[i].cells[index];
	    var defaultColSpan = (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && navigator.userAgent.indexOf("Mac") != -1)? 0 : 1;
	    
	    if(!display)
	    {
		    if(cell != null && cell.colSpan == defaultColSpan && cell.style.display != "none")
		    {
                cell.style.display = "none";
                if(navigator.userAgent.toLowerCase().indexOf("msie") != -1 && navigator.userAgent.toLowerCase().indexOf("6.0") != -1)
                {
                     Telerik.Web.UI.Grid._hideShowSelect(cell, display);
                }
		    }
		}
		else
		{
            if(cell != null && cell.colSpan == defaultColSpan && cell.style.display == "none")
		    {
                cell.style.display = (window.netscape)? "table-cell" : "";
		    }
            
            if(navigator.userAgent.toLowerCase().indexOf("msie") != -1 && navigator.userAgent.toLowerCase().indexOf("6.0") != -1)
            {
                 Telerik.Web.UI.Grid._hideShowSelect(cell, display);
            }
    
		}
	}
};

Telerik.Web.UI.Grid._hideShowSelect = function(node, display)
{
    if(!node)
        return;

    var selectElements = node.getElementsByTagName("select");

    for(var i = 0; i < selectElements.length; i++)
    {
        selectElements[i].style.display = (display)? "" : "none";
    }
}

Telerik.Web.UI.Grid.FindPosX = function (node)
{
	var x = 0;
	try
	{
		var leftBordersWidth = 0;
		if (node.offsetParent)
		{
			while (node.offsetParent)
			{
				x += node.offsetLeft
				
				if(node.currentStyle && node.currentStyle.borderLeftWidth.indexOf("px") != -1 
				    && !window.opera)
				{
				    leftBordersWidth += parseInt(node.currentStyle.borderLeftWidth);
				}
				
				node = node.offsetParent;
			}
		}
		else if (node.x)
			x += node.x;

		if (
			(navigator.userAgent.indexOf("Gecko") == -1 || navigator.userAgent.indexOf("WebKit/4") != -1) &&
			(
				(document.compatMode == "BackCompat" && !$telerik.isIE) ||
				(document.compatMode != "BackCompat" && $telerik.isIE) ||
				navigator.userAgent.indexOf("WebKit/4") != -1
			)
		)
        {
	        if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
	        {
		     x = parseInt(x) + parseInt(document.body.currentStyle.marginLeft);
	        }

	        if (document.defaultView && document.defaultView.getComputedStyle && 
                document.defaultView.getComputedStyle(document.body, "").marginLeft.indexOf("px") != -1 && !window.opera)
            {
	            x = parseInt(x) + parseInt(document.defaultView.getComputedStyle(document.body, "").marginLeft);
            }
	    }

		return x + leftBordersWidth;
		
	}
	catch(error)
	{
		return x;
	}
};

Telerik.Web.UI.Grid.FindPosY = function (node)
{
	var y = 0;
	try {
		var topBordersWidth = 0;
		if (node.offsetParent)
		{
			while (node.offsetParent)
			{
				y += node.offsetTop
				
					if(node.currentStyle && node.currentStyle.borderTopWidth.indexOf("px") != -1 && !window.opera)
					{
						topBordersWidth += parseInt(node.currentStyle.borderTopWidth);
					}
				node = node.offsetParent;
			}
		}
		else if (node.y)
			y += node.y;
			
		if (
			(navigator.userAgent.indexOf("Gecko") == -1 || navigator.userAgent.indexOf("WebKit/4") != -1) &&
			(
				(document.compatMode == "BackCompat" && !$telerik.isIE) ||
				(document.compatMode != "BackCompat" && $telerik.isIE) ||
				navigator.userAgent.indexOf("WebKit/4") != -1
			)
		)
		{
			if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
			{
				y = parseInt(y) + parseInt(document.body.currentStyle.marginTop);
			}
	        
			if (document.defaultView && document.defaultView.getComputedStyle && 
				document.defaultView.getComputedStyle(document.body, "").marginTop.indexOf("px") != -1 && !window.opera)
			{
				y = parseInt(y) + parseInt(document.defaultView.getComputedStyle(document.body, "").marginTop);
			}

		}
	        
		return y + topBordersWidth;
	}
	catch(error)
	{
		return y;
	}
};

Telerik.Web.UI.Grid.CreateDragDrop = function(e, column, adjustScrollPos)
{
    Telerik.Web.UI.Grid.CreateReorderIndicators(column.get_element(), column._owner._owner.Skin, column._owner._owner._imagesPath, adjustScrollPos, column._owner._owner.get_id());

    this._moveHeaderDiv = document.createElement("div");

    var table = document.createElement("table");

    if (this._moveHeaderDiv.mergeAttributes)
    {
	    this._moveHeaderDiv.mergeAttributes(column._owner._owner.get_element());
    }
    else
    {
	    Telerik.Web.UI.Grid.CopyAttributes(this._moveHeaderDiv, column.get_element());
    }

    if (table.mergeAttributes)
    {
	    table.mergeAttributes(column._owner.get_element());
    }
    else
    {
	    Telerik.Web.UI.Grid.CopyAttributes(table, column._owner.get_element());
    }

    table.style.margin = "0px";
    table.style.height = column.get_element().offsetHeight + "px";
    table.style.width = column.get_element().offsetWidth + "px";

    table.style.border = "0px";
    table.style.borderCollapse = "collapse";
    table.style.padding = "0px";

    var tHead = document.createElement("thead");
    var tr = document.createElement("tr");

    table.appendChild(tHead);
    tHead.appendChild(tr);
    tr.appendChild(column.get_element().cloneNode(true));
    this._moveHeaderDiv.appendChild(table);
    
    if(window.netscape)
    {
        this._moveHeaderDiv.className += " " + column._owner._owner.get_element().className;
    }

    document.body.appendChild(this._moveHeaderDiv);

    this._moveHeaderDiv.style.height = table.style.height;
    this._moveHeaderDiv.style.width = table.style.width;

    this._moveHeaderDiv.style.position = "absolute";

    this._moveHeaderDiv.style.cursor = "move";

    this._moveHeaderDiv.style.display = "none";
    
    this._moveHeaderDiv.UniqueName = column.get_element().UniqueName;

    Telerik.Web.UI.Grid.ClearDocumentEvents();
};

Telerik.Web.UI.Grid.MoveDragDrop = function(e, column, adjustScrollPos)
{    
    if (this._moveHeaderDiv != null)
    {
	    if (typeof(this._moveHeaderDiv.style.filter) != "undefined")
	    {
	        this._moveHeaderDiv.style.filter = "alpha(opacity=25);";
	    }
	    else if(typeof(this._moveHeaderDiv.style.MozOpacity) != "undefined")
	    {
		    this._moveHeaderDiv.style.MozOpacity = 1/4;
	    }
	    else if(typeof(this._moveHeaderDiv.style.opacity) != "undefined")
	    {
		    this._moveHeaderDiv.style.opacity = 1/4;
	    }
	
	    this._moveHeaderDiv.style.visibility = "";
	    this._moveHeaderDiv.style.display = "";

	    Telerik.Web.UI.Grid.PositionDragElement(this._moveHeaderDiv, e);

	    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	    if (currentElement != null)
	    {
		    if (Telerik.Web.UI.Grid.IsChildOf(currentElement, column._owner.get_element()) ||
		            (column._owner._owner.ClientSettings.AllowDragToGroup && column._owner._owner._groupPanel &&
		                Telerik.Web.UI.Grid.IsChildOf(currentElement, column._owner._owner._groupPanel.get_element())))
		    {
			    //var item = this._owner._isItem(currentElement);
			    if (
			        (currentElement != column.get_element()) &&
				    //(item != null) &&
				        (
				        (currentElement.parentNode == column.get_element().parentNode)
				        )
				    )
			    {			        
//			        while(currentElement.parentNode != column.get_element().parentNode && 
//			            Telerik.Web.UI.Grid.IsChildOf(currentElement.parentNode, column.get_element().parentNode))
//			        {
//                        currentElement = currentElement.parentNode;
//			        }
			        if(!column._hierarchicalIndex)
			        {
			            var column = column._owner.getColumnByUniqueName(currentElement.UniqueName);
			            if(column._data.Reorderable && column._owner._owner.ClientSettings.AllowColumnsReorder)
			            {
			                currentElement.title = column._owner._owner.ClientSettings.ClientMessages.DropHereToReorder;
				            Telerik.Web.UI.Grid.MoveReorderIndicators(e, currentElement, adjustScrollPos, column._owner._owner.get_id());
				        }
				    }
				    else
				    {	
				        if(currentElement.parentNode.cells && 
				            currentElement != currentElement.parentNode.cells[currentElement.parentNode.cells.length-1])
				        {
				            currentElement.title = column._owner._owner.ClientSettings.ClientMessages.DropHereToReorder;
				            Telerik.Web.UI.Grid.MoveReorderIndicators(e, currentElement, adjustScrollPos, column._owner._owner.get_id());
				        }
				    }
			    }
			    else if(column._owner._owner.ClientSettings.AllowDragToGroup && column._owner._owner._groupPanel &&
		        Telerik.Web.UI.Grid.IsChildOf(currentElement, column._owner._owner._groupPanel.get_element()))
		        {		            
		            Telerik.Web.UI.Grid.MoveReorderIndicators(e, column._owner._owner._groupPanel.get_element(), adjustScrollPos, column._owner._owner.get_id());
		        }
			    else
			    {			        
				    Telerik.Web.UI.Grid.ReorderIndicator1.style.visibility = "hidden";
				    Telerik.Web.UI.Grid.ReorderIndicator1.style.display = "none";
				    Telerik.Web.UI.Grid.ReorderIndicator1.style.position = "absolute";

				    Telerik.Web.UI.Grid.ReorderIndicator2.style.visibility = Telerik.Web.UI.Grid.ReorderIndicator1.style.visibility;
				    Telerik.Web.UI.Grid.ReorderIndicator2.style.display = Telerik.Web.UI.Grid.ReorderIndicator1.style.display;
				    Telerik.Web.UI.Grid.ReorderIndicator2.style.position = Telerik.Web.UI.Grid.ReorderIndicator1.style.position;
			    }
			    
			    var ownerGrid = column._owner._owner;                           
                if (ownerGrid && ownerGrid.ClientSettings.Scrolling.AllowScroll && ownerGrid._gridDataDiv)
                {  
                    Telerik.Web.UI.Grid.AutoScrollHorizontally(ownerGrid,currentElement);
                }

		    }
	    }

    }
};
  
Telerik.Web.UI.Grid.AutoScrollHorizontally = function(ownerGrid,currentElement)
{
    if (!ownerGrid || !this || ownerGrid.ClientSettings.Scrolling.FrozenColumnsCount > 0)
        return;
       
    var leftX, rightX;               
    var gridElement = ownerGrid._gridDataDiv;
   
    if(!gridElement || !this._moveHeaderDiv)
        return;           
   
    var dragElementLocation = $telerik.getLocation(this._moveHeaderDiv);  
   
    leftX = $telerik.getLocation(gridElement).x;
    rightX = leftX + gridElement.offsetWidth;         
    var scrollToLeft = gridElement.scrollLeft <= 0;
    var scrollToRight = gridElement.scrollLeft >= (gridElement.scrollWidth - gridElement.offsetWidth + 16);
   
    var mouseDistanceToLeft = dragElementLocation.x - leftX;
    var mouseDistanceToRight = rightX - dragElementLocation.x;       
  
    if (mouseDistanceToLeft < (50 + Telerik.Web.UI.Grid.GetScrollBarWidth()) && !scrollToLeft)
    {          
        var scrollSpeed = (10 - (mouseDistanceToLeft / 5));
        gridElement.scrollLeft = gridElement.scrollLeft - scrollSpeed;   
        window.setTimeout( function() { Telerik.Web.UI.Grid.AutoScrollHorizontally(ownerGrid,currentElement); }, 100);   
        Telerik.Web.UI.Grid.HideReorderIndicators();
    }
    else if (mouseDistanceToRight < (50 + Telerik.Web.UI.Grid.GetScrollBarWidth()) && !scrollToRight)
    {          
        var scrollSpeed = (10 - (mouseDistanceToRight / 5));       
        gridElement.scrollLeft = gridElement.scrollLeft + scrollSpeed;
        window.setTimeout( function() { Telerik.Web.UI.Grid.AutoScrollHorizontally(ownerGrid,currentElement); }, 100);   
        Telerik.Web.UI.Grid.HideReorderIndicators();
    }       
}; 

Telerik.Web.UI.Grid.HideReorderIndicators = function()
{
    if(!Telerik.Web.UI.Grid.ReorderIndicator1 || !Telerik.Web.UI.Grid.ReorderIndicator2)
        return;
       
    Telerik.Web.UI.Grid.ReorderIndicator1.style.visibility = "hidden";
    Telerik.Web.UI.Grid.ReorderIndicator1.style.display = "none";
    Telerik.Web.UI.Grid.ReorderIndicator1.style.position = "absolute";

    Telerik.Web.UI.Grid.ReorderIndicator2.style.visibility = Telerik.Web.UI.Grid.ReorderIndicator1.style.visibility;
    Telerik.Web.UI.Grid.ReorderIndicator2.style.display = Telerik.Web.UI.Grid.ReorderIndicator1.style.display;
    Telerik.Web.UI.Grid.ReorderIndicator2.style.position = Telerik.Web.UI.Grid.ReorderIndicator1.style.position;
};

Telerik.Web.UI.Grid.DestroyDragDrop = function()
{
    if (this._moveHeaderDiv != null)
    {
	    var parentNode = this._moveHeaderDiv.parentNode;
	    parentNode.removeChild(this._moveHeaderDiv);
	    this._moveHeaderDiv = null;
	    Telerik.Web.UI.Grid.RestoreDocumentEvents();
    }

    Telerik.Web.UI.Grid.DestroyReorderIndicators();
};


Telerik.Web.UI.Grid.GetFirstParentByTagName = function (node, tagName)
{
	while (node && node.parentNode)
	{
		if (node.tagName.toLowerCase() == tagName.toLowerCase())
		{
			return node;
		}
		node = node.parentNode;
	}
	return null;
};

Telerik.Web.UI.Grid.CreateColumnResizers = function(column, e)
{
    Telerik.Web.UI.Grid.ClearDocumentEvents();

	this.LeftResizer = document.createElement("span");
	this.LeftResizer.style.backgroundColor = "navy";
	this.LeftResizer.style.width = "1" + "px";
	this.LeftResizer.style.position = "absolute";
	this.LeftResizer.style.cursor = "e-resize";

	this.RightResizer = document.createElement("span");
	this.RightResizer.style.backgroundColor = "navy";
	this.RightResizer.style.width = "1" + "px";
	this.RightResizer.style.position = "absolute";
	this.RightResizer.style.cursor = "e-resize";

	this.ResizerToolTip = document.createElement("span");
	this.ResizerToolTip.style.backgroundColor = "#F5F5DC";
	this.ResizerToolTip.style.border = "1px solid";
	this.ResizerToolTip.style.position = "absolute";
	this.ResizerToolTip.style.font = "icon";
	this.ResizerToolTip.style.padding = "2";
	this.ResizerToolTip.innerHTML = "Width: <b>" + column.get_element().offsetWidth + "</b> <em>pixels</em>";
	
	
	this.LeftResizer.style.display = 
	    this.ResizerToolTip.style.display = this.ResizerToolTip.style.display = "none";

	document.body.appendChild(this.LeftResizer);
	document.body.appendChild(this.RightResizer);
	document.body.appendChild(this.ResizerToolTip);

	Telerik.Web.UI.Grid.MoveColumnResizers(column, e);
};

Telerik.Web.UI.Grid.DestroyColumnResizers = function()
{
    Telerik.Web.UI.Grid.RestoreDocumentEvents();

    if(this.LeftResizer && this.LeftResizer.parentNode)
    {
	    document.body.removeChild(this.LeftResizer);
	    this.LeftResizer = null;
	}

    if(this.RightResizer && this.RightResizer.parentNode)
    {
        document.body.removeChild(this.RightResizer);
        this.RightResizer = null;
    }

    if(this.ResizerToolTip && this.ResizerToolTip.parentNode)
    {
        document.body.removeChild(this.ResizerToolTip);
        this.ResizerToolTip = null
    }
};

Telerik.Web.UI.Grid.MoveColumnResizers = function(column, e)
{
    if(!this.LeftResizer || !this.RightResizer || !this.RightResizer)
        return;

    this.LeftResizer.style.display = 
        this.RightResizer.style.display = this.ResizerToolTip.style.display = "";

	this.LeftResizer.style.top = Telerik.Web.UI.Grid.FindPosY(column.get_element()) - 
									Telerik.Web.UI.Grid.FindScrollPosY(column.get_element()) + 
									document.documentElement.scrollTop + 
									document.body.scrollTop + "px";

	this.LeftResizer.style.left = Telerik.Web.UI.Grid.FindPosX(column.get_element()) - 
									Telerik.Web.UI.Grid.FindScrollPosX(column.get_element()) + 
									document.documentElement.scrollLeft + 
									document.body.scrollLeft + "px";

    
	this.RightResizer.style.top = this.LeftResizer.style.top;
	//this.RightResizer.style.left = parseInt(this.LeftResizer.style.left) +	column.get_element().offsetWidth + "px";
	this.RightResizer.style.left = Telerik.Web.UI.Grid.GetEventPosX(e) - 5 + "px";
	
	this.ResizerToolTip.style.top = parseInt(this.RightResizer.style.top) - 20 + "px";

	this.ResizerToolTip.style.left = parseInt(this.RightResizer.style.left) - 5 + "px";

	if (parseInt(this.LeftResizer.style.left) < Telerik.Web.UI.Grid.FindPosX(column._owner.get_element()))
	{
		this.LeftResizer.style.display = "none";
	}
	
	if(!column._owner._owner.ClientSettings.Scrolling.AllowScroll)
	{
	    this.LeftResizer.style.height = column._owner.get_element().tBodies[0].offsetHeight 
	        + column._owner.get_element().tHead.offsetHeight + "px";
	}
	else
	{
	    var dataDiv =  $get(column._owner._owner.ClientID + "_GridData");
	    if(column._owner._owner.ClientSettings.Scrolling.UseStaticHeaders)
	    {
	        this.LeftResizer.style.height = dataDiv.clientHeight
	            + column._owner.get_element().tHead.offsetHeight + "px";
	    }
	    else
	    {
	        this.LeftResizer.style.height = dataDiv.clientHeight + "px";
	    }
	}

    this.RightResizer.style.height = this.LeftResizer.style.height;

    var delta = parseInt(this.RightResizer.style.left) - parseInt(this.LeftResizer.style.left);
	this.ResizerToolTip.innerHTML = "Width: <b>" + delta + "</b> <em>pixels</em>";


	if(column._owner._owner.ClientSettings.Resizing.EnableRealTimeResize)
	{
	    if(delta > 0)
	    {
            column.get_element().style.width = delta + "px";
	        this.RightResizer.style.left = parseInt(this.LeftResizer.style.left) +	column.get_element().offsetWidth + "px";
        }
	}

    if(parseInt(this.RightResizer.style.left) <= parseInt(this.LeftResizer.style.left) - 1)
    {
        Telerik.Web.UI.Grid.DestroyColumnResizers();
    }
    
};

Telerik.Web.UI.Grid.FindScrollPosX = function(node)
{
	var x = 0;
	while (node.parentNode)
	{
		if (typeof(node.parentNode.scrollLeft) == "number")
		{
			x += node.parentNode.scrollLeft;
		}
		node = node.parentNode;
	}
	    if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
	    {
		    x = parseInt(x) - parseInt(document.body.currentStyle.marginLeft);
	    }
	return x;
};

Telerik.Web.UI.Grid.FindScrollPosY = function(node)
{
	var y = 0;

	while (node.parentNode)
	{
		if (typeof(node.parentNode.scrollTop) == "number")
		{
			y += node.parentNode.scrollTop;
		}
		node = node.parentNode;
	}
	    if (document.body.currentStyle && document.body.currentStyle.margin.indexOf("px") != -1 && !window.opera)
	    {
		    y = parseInt(y) - parseInt(document.body.currentStyle.marginTop);
	    }
	return y;
};

Telerik.Web.UI.Grid.GetEventPosX = function(e)
{
	var x = e.clientX;

	var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	while (currentElement.parentNode)
	{
		if (typeof(currentElement.parentNode.scrollLeft) == "number")
		{
			x += currentElement.parentNode.scrollLeft;
		}
		currentElement = currentElement.parentNode;
	}
	
	if(Telerik.Web.UI.Grid.IsRightToLeft(document.body))
	{
	    x = x - Telerik.Web.UI.Grid.getScrollBarHeight();
	}
	
	return x;
};

Telerik.Web.UI.Grid.GetEventPosY = function (e)
{
	var y = e.clientY;

	var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	while (currentElement.parentNode)
	{
		if (typeof(currentElement.parentNode.scrollTop) == "number")
		{
			y += currentElement.parentNode.scrollTop;
		}
		currentElement = currentElement.parentNode;
	}

	return y;
};

Telerik.Web.UI.Grid.getScrollBarHeight = function()
{
	try
	{
	    if(typeof(this.scrollbarHeight) == "undefined")
	    {
            var offsetHeight, clientHeight = 0;

            var div1 = document.createElement('div');
            div1.style.position = 'absolute';
            div1.style.top = '-1000px';
            div1.style.left = '-1000px';
            div1.style.width = '100px';
            div1.style.height = '100px';
            div1.style.overflow = 'auto';

            var div2 = document.createElement('div');
            div2.style.width = '1000px';
            div2.style.height = '1000px';

            div1.appendChild(div2);
            document.body.appendChild(div1);

            offsetHeight = div1.offsetHeight;

            clientHeight = div1.clientHeight;

            document.body.removeChild(document.body.lastChild);

            this.scrollbarHeight = offsetHeight - clientHeight;
            
            if(this.scrollbarHeight <= 0 || clientHeight == 0)
            {
                this.scrollbarHeight = 16;
            }
            
            div2.outerHTML=null;
            div1.outerHTML=null;
            div1=null;
            div2=null;
	    }
		return this.scrollbarHeight;
	}
	catch(error)
	{
		return false;
	}
};

Telerik.Web.UI.Grid.GetScrollBarWidth = function()
{
	try
	{
	    if(typeof(this.scrollbarWidth) == "undefined")
	    {
            var offsetWidth, clientWidth = 0;

            var div1 = document.createElement('div');
            div1.style.position = 'absolute';
            div1.style.top = '-1000px';
            div1.style.left = '-1000px';
            div1.style.width = '100px';
            div1.style.overflow = 'auto';

            var div2 = document.createElement('div');
            div2.style.width = '1000px';

            div1.appendChild(div2);
            document.body.appendChild(div1);

            offsetWidth = div1.offsetWidth;

            clientWidth = div1.clientWidth;

            document.body.removeChild(document.body.lastChild);

            this.scrollbarWidth = offsetWidth - clientWidth;
            
            if(this.scrollbarWidth <= 0 || clientWidth == 0)
            {
                this.scrollbarWidth = 16;
            }
	    }
		return this.scrollbarWidth;
	}
	catch(error)
	{
		return false;
	}
};

Telerik.Web.UI.Grid.IsRightToLeft = function(node)
{
	try
	{
		while (node)
		{
			if(node.currentStyle && node.currentStyle.direction.toLowerCase() == "rtl")
			{
			    return true;
			}
			else if(getComputedStyle && getComputedStyle(node, "").getPropertyValue("direction").toLowerCase() == "rtl")
			{
		        return true;
			}
            else if (node.dir.toLowerCase() == "rtl")
			{
				return true;
			}
			
			node = node.parentNode;
		}

		return false;

	}
	catch(error)
	{
		return false;
	}
};

Telerik.Web.UI.Grid.FireEvent = function (sender, eventHandler, eventArguments)
{	
	try
	{
		var returnValue = true;
		if (typeof(sender[eventHandler]) == "string")
		{
			eval(sender[eventHandler]);
		}
		else if (typeof(sender[eventHandler]) == "function")
		{
			if (eventArguments)
			{
				switch(eventArguments.length)
				{
					case 1:
					{
						returnValue = sender[eventHandler](eventArguments[0]);
						break;
					}
					case 2:
					{
						returnValue = sender[eventHandler](eventArguments[0], eventArguments[1]);
						break;
					}
				}
			}
			else
			{
				returnValue = sender[eventHandler]();
			}
		}
		
		if (typeof(returnValue) != "boolean")
		{
			return true;
		}
		else
		{
			return returnValue;
		}
	}
	catch(error)
	{
	    throw error;
	}
};

Telerik.Web.UI.Grid.GetTableColGroup = function(table)
{
	try
	{
		return table.getElementsByTagName("colgroup")[0];
	}
	catch(error)
	{
		return false;
	}
};

Telerik.Web.UI.Grid.GetTableColGroupCols = function(colGroup)
{
	try
	{
		var cols = new Array();

		var node = colGroup.childNodes[0];

		for(var i=0;i<colGroup.childNodes.length;i++)
		{
			if ((colGroup.childNodes[i].tagName) &&
				(colGroup.childNodes[i].tagName.toLowerCase() == "col"))
			{
				cols[cols.length] = colGroup.childNodes[i];
			}
		}

		return cols;
	}
	catch(error)
	{
		return false;
	}
};

Telerik.Web.UI.Grid.ClearItemStyle = function(row, itemStyle, itemStyleClass)
{
    Sys.UI.DomElement.removeCssClass(row, itemStyleClass);
    if (itemStyle)
    {
        var currentCssText = row.style.cssText.toLowerCase().replace(/ /g, "");
        var currentCssData = currentCssText.split(";");
        
        for (var j = 0; j < currentCssData.length; j++)
        {
            if (itemStyle.indexOf(currentCssData[j]) != -1)
            {
                currentCssData[j] = "";
            }
        }

        row.style.cssText = currentCssData.join(";");
    }  
};
    
Telerik.Web.UI.Grid.SetItemStyle = function(row, itemStyle, itemStyleClass)
{
    Sys.UI.DomElement.addCssClass(row, itemStyleClass);
    if(itemStyle)
    {
        row.style.cssText = row.style.cssText + ";" + itemStyle;
    }        
};

Telerik.Web.UI.Grid.ScrollIntoView = function(row)
{
	if(row.focus)
	{
		row.scrollIntoView(false);
		try
		{
	        row.focus();
		}
		catch(e)
		{
		}
	}
};

Telerik.Web.UI.Grid.GetNestedTableView = function(row)
{
    var nestedTableView = null;
    var nestedTable = Telerik.Web.UI.Grid.GetNestedTable(row);
    if (nestedTable)
    {
        nestedTableView = $find(nestedTable.id.split("__")[0]);
    } 

    return nestedTableView;
}

Telerik.Web.UI.Grid.GetLastNestedTableView = function(row)
{
    var nestedTableView = null;
    var nestedTable = Telerik.Web.UI.Grid.GetLastNestedTable(row);
    if (nestedTable)
    {
        nestedTableView = $find(nestedTable.id.split("__")[0]);
    } 

    return nestedTableView;
}

Telerik.Web.UI.Grid.GetPreviousNestedTableView = function(row)
{
    var nestedTableView = null;
    if (row.previousSibling && row.previousSibling.previousSibling)
    {
        nestedTableView = Telerik.Web.UI.Grid.GetNestedTableView(row.previousSibling);
    }

    return nestedTableView;
}

Telerik.Web.UI.Grid.GetNestedTable = function(row)
{
    var nestedTable = null;
    var nextSibling = Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName(row, "tr");
    if (nextSibling)
    {
        var domTables = nextSibling.getElementsByTagName("table");
        if (domTables.length > 0 && domTables[0].id.indexOf("Detail") != -1)
        {
            nestedTable = domTables[0];
        }
    } 

    return nestedTable;
}

Telerik.Web.UI.Grid.GetLastNestedTable = function(row)
{
    var nestedTable = null;
    var nextSibling = Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName(row, "tr");
    if (nextSibling)
    {
        var domTables = nextSibling.getElementsByTagName("table");
        for (var i=domTables.length - 1; i >= 0; i--)
        {
            var domTable = domTables[i];
            if (domTable.id.indexOf("Detail") != -1 && domTable.id.indexOf("_mainTable") == -1)
            {
                nestedTable = domTable;
                break;
            }
        }
    } 

    return nestedTable;
}

Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName = function (node, nodeTagName)
{
	var node = node.nextSibling;
	while (node != null && 
	       (node.nodeType == 3 || (node.tagName && node.tagName.toLowerCase() != nodeTagName.toLowerCase())))
	{
		node = node.nextSibling;
	}
	
	return node;
};

Telerik.Web.UI.Grid.GetNodePreviousSiblingByTagName = function (node, nodeTagName)
{
	var node = node.previousSibling;
	while ((node != null) &&
	        (node.nodeType == 3 || (node.tagName && node.tagName.toLowerCase() != nodeTagName.toLowerCase())))
	{
		node = node.previousSibling;
	}
	
	return node;
};;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridItemResizer = function(owner)
{
    Telerik.Web.UI.GridItemResizer.initializeBase(this);    
    
    this._owner = owner;
    this._onResizeMouseUpDelegate = null;
    this._cellsWithEvents = [];
}

Telerik.Web.UI.GridItemResizer.prototype = 
{
    dispose : function() 
    {
        for(var i = 0; i < this._cellsWithEvents.length; i++)
        {
            $clearHandlers(this._cellsWithEvents[i]);
            this._cellsWithEvents[i]._events = null;
            this._cellsWithEvents[i]._onResizeMouseDownDelegate = null;
        }
    
        this._cellsWithEvents = null;
        this._destroyRowResizer();
        
        if (this._onResizeMouseUpDelegate)
            $telerik.removeExternalHandler(document, "mouseup", this._onResizeMouseUpDelegate)
            //$removeHandler(document, "mouseup", this._onResizeMouseUpDelegate);
    },
    
    _detectResizeCursorsOnItems : function(e, currentElement)
    {
	    var gridControl = this;

	    if ((currentElement != null) && 
		    (currentElement.tagName.toLowerCase() == "td") 
		    && !this._owner.MoveHeaderDiv)
	    {
	        
		    var currentTable = currentElement.parentNode.parentNode.parentNode;
		    var definedTable = $find(currentTable.id);

		    if (definedTable != null)
		    {
//			    if (definedTable.get_columns() != null)
//			    {
//				    if (definedTable.get_columns()[currentElement.cellIndex].ColumnType != "GridRowIndicatorColumn")
//					    return;
//			    }

			    if (!definedTable.get_element())
				    return;

			    if (!definedTable.get_element().tBodies[0])
				    return;

			    var positionY = Telerik.Web.UI.Grid.GetEventPosY(e);
			    var startY = Telerik.Web.UI.Grid.FindPosY(currentElement);
			    var endY = startY + currentElement.offsetHeight;

			    this._resizeTolerance = 5;

			    var oldTitle = currentElement.title;

			    if ((positionY > endY - this._resizeTolerance) && 
				    (positionY < endY + this._resizeTolerance))
			    {
				    currentElement.style.cursor = "n-resize";
					
				    currentElement.title = this._owner.ClientSettings.ClientMessages.DragToResize;
                    
                    if (!currentElement._onResizeMouseDownDelegate)
                    {
                        currentElement._onResizeMouseDownDelegate = Function.createDelegate(this, this._onResizeMouseDownHandler);
                        $addHandler(currentElement, "mousedown", currentElement._onResizeMouseDownDelegate);

                        //if(!this._cellsWithEvents[currentElement])
                        {
                            this._cellsWithEvents[this._cellsWithEvents.length] = currentElement;
                        }
                    }
			    }
			    else
			    {
				    currentElement.style.cursor = "default";
				    currentElement.title = "";
				    
                    if (currentElement._onResizeMouseDownDelegate)
                    {
                        if(currentElement._events != null)
                        {
                             $removeHandler(currentElement, "mousedown", currentElement._onResizeMouseDownDelegate);
                        }
                        currentElement._onResizeMouseDownDelegate = null;
                        currentElement._events = null;
                    }    					    
			    }
		    }
	    }    
    },
    
    _moveItemResizer : function(e)
    {
		if ((this._owner._rowResizer != "undefined") &&
			(this._owner._rowResizer != null) &&
			(this._owner._rowResizer.parentNode != null))
		{		
			this._owner._rowResizer.style.top = Telerik.Web.UI.Grid.GetEventPosY(e) - 
						(Telerik.Web.UI.Grid.GetEventPosY(e) - e.clientY) + 
						document.body.scrollTop + 
						document.documentElement.scrollTop + "px";
						
						
			if (this._owner.ClientSettings.Resizing.EnableRealTimeResize)
			{
				this._destroyRowResizerAndResizeRow(e, false);
				this._updateRowResizerWidth(e);
			}
		}      
    },
    
    _destroyRowResizerAndResizeRow : function (e, shouldDestroy)
    {
	    if ((this._owner._cellToResize != "undefined") &&
		    (this._owner._cellToResize != null) &&
		    (this._owner._cellToResize.tagName.toLowerCase() == "td") &&
		    (this._owner._rowResizer != "undefined") && 
		    (this._owner._rowResizer != null))
	    {
		    var newHeight;
		    if (this._gridDataDiv)
		    {
			    newHeight = parseInt(this._owner._rowResizer.style.top) + this._gridDataDiv.scrollTop - (Telerik.Web.UI.Grid.FindPosY(this._owner._cellToResize));
		    }
		    else
		    {
			    newHeight = parseInt(this._owner._rowResizer.style.top) - (Telerik.Web.UI.Grid.FindPosY(this._owner._cellToResize));
		    }

		    if (newHeight > 0)
		    {
			    var currentTable =  this._owner._cellToResize.parentNode.parentNode.parentNode;
			    var definedTable =  $find(currentTable.id);

			    if (definedTable != null)
			    {
				    definedTable.resizeItem(this._owner._cellToResize.parentNode.rowIndex, newHeight);
			    }
		    }
	    }
		
	    if (shouldDestroy)
	    {
		    this._destroyRowResizer();
	    }
    },    
    

    _updateRowResizerWidth : function (e)
    {
	    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	    if ((currentElement != null) && (currentElement.tagName.toLowerCase() == "td"))
	    {
		    var definedTable =  this._owner._rowResizerRefTable;

		    if (definedTable != null)
		    {
			    if (this._gridDataDiv)
			    {			        
				    var tmpWidth = (Telerik.Web.UI.Grid.FindPosX(this._gridDataDiv) + 
					    this._gridDataDiv.offsetWidth) - parseInt(this._owner._rowResizer.style.left);

				    if (tmpWidth > definedTable.get_element().offsetWidth)
				    {
					    this._owner._rowResizer.style.width = definedTable.get_element().offsetWidth + "px";
				    }
				    else
				    {
					    this._owner._rowResizer.style.width = tmpWidth + "px";
				    }

				    if (parseInt(this._owner._rowResizer.style.width) > this._gridDataDiv.offsetWidth)
				    {
					    this._owner._rowResizer.style.width = this._gridDataDiv.offsetWidth + "px";
				    }
			    }
			    else
			    {
				    this._owner._rowResizer.style.width = definedTable.get_element().offsetWidth + "px";
			    }
		    }
	    }
    },      

    _createRowResizer : function (e)
    {        
	    this._destroyRowResizer();

	    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

	    if ((currentElement != null) && (currentElement.tagName.toLowerCase() == "td"))
	    {
		    if (currentElement.cellIndex > 0)
		    {
			    var rowIndex = currentElement.parentNode.rowIndex;
			    currentElement = currentElement.parentNode.parentNode.parentNode.rows[rowIndex].cells[0];
		    }
			
		    this._owner._rowResizer = null;
		    this._owner._cellToResize = currentElement;

		    var currentTable =  currentElement.parentNode.parentNode.parentNode;
		    var definedTable =  $find(currentTable.id);

		    this._owner._rowResizer = document.createElement("div");
		    this._owner._rowResizer.style.backgroundColor = "navy";
		    this._owner._rowResizer.style.height = "1px";
		    this._owner._rowResizer.style.fontSize = "1";
		    this._owner._rowResizer.style.position = "absolute";
		    this._owner._rowResizer.style.cursor = "n-resize";

		    if (definedTable != null)
		    {
			    this._owner._rowResizerRefTable = definedTable;

			    if (this._gridDataDiv)
			    {
				    this._owner._rowResizer.style.left = Telerik.Web.UI.Grid.FindPosX(this._gridDataDiv) + "px";

				    var tmpWidth = (Telerik.Web.UI.Grid.FindPosX(this._gridDataDiv) + 
					    this._gridDataDiv.offsetWidth) - parseInt(this._owner._rowResizer.style.left);

				    if (tmpWidth > definedTable.get_element().offsetWidth)
				    {
					    this._owner._rowResizer.style.width = definedTable.Control.offsetWidth + "px";
				    }
				    else
				    {
					    this._owner._rowResizer.style.width = tmpWidth + "px";
				    }

				    if (parseInt(this._owner._rowResizer.style.width) > this._gridDataDiv.offsetWidth)
				    {
					    this._owner._rowResizer.style.width = this._gridDataDiv.offsetWidth + "px";
				    }
			    }
			    else
			    {
				    this._owner._rowResizer.style.width = definedTable.get_element().offsetWidth + "px";
				    this._owner._rowResizer.style.left = Telerik.Web.UI.Grid.FindPosX(currentElement) + "px";
			    }
				
		    }

            
		    this._owner._rowResizer.style.top = Telerik.Web.UI.Grid.GetEventPosY(e) - 
					    (Telerik.Web.UI.Grid.GetEventPosY(e) - e.clientY) + 
					    document.body.scrollTop + 
					    document.documentElement.scrollTop + "px";
					    

		    var parentElem = document.body;
		    parentElem.appendChild(this._owner._rowResizer);
	    }
    },    
    
    _destroyRowResizer : function ()
    {
	    if ((this._owner._rowResizer != "undefined") && 
		    (this._owner._rowResizer != null) &&
		    (this._owner._rowResizer.parentNode != null))
	    {
		    var parentElem = this._owner._rowResizer.parentNode;
		    parentElem.removeChild(this._owner._rowResizer);
		    this._owner._rowResizer = null;
		    this._owner._rowResizerRefTable = null;
	    }
    },    
    
    //Handlers
    _onResizeMouseDownHandler : function (e)
    {
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
        
        if(currentElement)
        {//debugger;
             $clearHandlers(currentElement);
        }

	    this._createRowResizer(e);
	    Telerik.Web.UI.Grid.ClearDocumentEvents();
        this._onResizeMouseUpDelegate = Function.createDelegate(this, this._onResizeMouseUpHandler);
        $telerik.addExternalHandler(document, "mouseup", this._onResizeMouseUpDelegate);
        //$addHandler(document, "mouseup", this._onResizeMouseUpDelegate);
    },    
    
    _onResizeMouseUpHandler : function (e)
    {
         $telerik.removeExternalHandler(document, "mouseup", this._onResizeMouseUpDelegate);
        //$removeHandler(document, "mouseup", this._onResizeMouseUpDelegate);
	    this._destroyRowResizerAndResizeRow(e, true);
	    Telerik.Web.UI.Grid.RestoreDocumentEvents();    
    }
};

Telerik.Web.UI.GridItemResizer.registerClass("Telerik.Web.UI.GridItemResizer", null, Sys.IDisposable);;Telerik.Web.UI.GridDataItem = function(element) 
{
    Telerik.Web.UI.GridDataItem.initializeBase(this, [element]);
    
    this._owner = {};
    this._data = {};
    
    this._selected = false;
    this._expanded = false;
    this._display = false;
    
    this._dataKeyValue = null;
    this._dataItem = null;

    this._itemIndexHierarchical = "";
};

Telerik.Web.UI.GridDataItem.prototype =
{
    initialize: function()
    {
        Telerik.Web.UI.GridDataItem.callBaseMethod(this, 'initialize');
    },

    dispose: function()
    {
        this._owner._owner.raise_rowDestroying(Sys.EventArgs.Empty);
        if (this.get_element())
        {
            $clearHandlers(this.get_element());

            this._element.control = null;
            //this._element = null;
       }
        Telerik.Web.UI.GridDataItem.callBaseMethod(this, 'dispose');
    },

    get_owner: function()
    {
        return this._owner;
    },

    get_cell: function(columnUniqueName)
    {
        return this._owner.getCellByColumnUniqueName(this, columnUniqueName);
    },
    
    get_dataItem: function()
    {
        return this._dataItem;
    },

    findControl: function(id)
    {
        return $telerik.findControl(this.get_element(), id)
    },

    findElement: function(id)
    {
        return $telerik.findElement(this.get_element(), id)
    },

    getDataKeyValue: function(columnName)
    {
        var _itemIndexHierarchical = this.get_element().id.split("__")[1];
        var _dataKeyValues = null;
        if (this._owner._owner._clientKeyValues &&
	        this._owner._owner._clientKeyValues[_itemIndexHierarchical])
        {
            _dataKeyValues = this._owner._owner._clientKeyValues[_itemIndexHierarchical];
        }

        return (_dataKeyValues) ? _dataKeyValues[columnName] : null;
    },

    get_selected: function()
    {
        return this._selected;
    },
    set_selected: function(value)
    {
        if (this._selected != value)
        {
            var e = { "ctrlKey": false };

            if (!this._owner._owner._selection._selectRowInternal(this.get_element(), e, true, true, true))
                return;

            this._selected = value;
        }
    },

    get_expanded: function()
    {
        return this._expanded;
    },
    set_expanded: function(value)
    {
        if (this._expanded != value)
        {
            if (value && !this._owner._expandRow(this.get_element()))
            {
                return;
            }

            if (!value && !this._owner._collapseRow(this.get_element()))
            {
                return;
            }

            this._expanded = value;
        }
    },

    get_display: function()
    {
        return this._display;
    },
    set_display: function(value)
    {
        if (this._display != value)
        {
            this._display = value;
        }
    }
};

Telerik.Web.UI.GridDataItem.registerClass("Telerik.Web.UI.GridDataItem", Sys.UI.Control);



//Telerik.Web.UI.GridDataItemEventArgs = function(rowElement, domEvent) 
//{
//	Telerik.Web.UI.GridDataItemEventArgs.initializeBase(this);

//    this._id = "";
//    this._itemIndexHierarchical = "";
//    this._gridDataItem = null;
//    this._tableView = null;
//    this._dataKeyValues = null;
//    
//    if (rowElement)
//    {
//	    this._id = rowElement.id;
//	    this._itemIndexHierarchical = this._id.split("__")[1];
//	    this._gridDataItem = $find(this._id);
//	    this._tableView = $find(this._id.split("__")[0]);
//	    
//	    if(this._tableView._owner._clientKeyValues &&
//	    this._tableView._owner._clientKeyValues[this._itemIndexHierarchical])
//	    {
//	        this._dataKeyValues = this._tableView._owner._clientKeyValues[this._itemIndexHierarchical];
//	    }
//	}
//	
//	this._domEvent = domEvent;
//};

//Telerik.Web.UI.GridDataItemEventArgs.prototype = 
//{
//	get_gridDataItem : function ()
//	{
//		return this._gridDataItem;
//	},

//	get_itemIndexHierarchical : function ()
//	{
//		return this._itemIndexHierarchical;
//	},

//	get_id : function ()
//	{
//		return this._id;
//	},
//	
//    get_tableView : function ()
//	{
//		return this._tableView;
//	},

//	get_domEvent : function ()
//	{
//		return this._domEvent;
//	},

//    getDataKeyValue : function (columnName)
//	{
//		return (this._dataKeyValues)? this._dataKeyValues[columnName] : null;
//	}
//};

//Telerik.Web.UI.GridDataItemEventArgs.registerClass("Telerik.Web.UI.GridDataItemEventArgs", Sys.EventArgs);


//Telerik.Web.UI.GridDataItemCancelEventArgs = function(rowElement, domEvent) 
//{
//	Telerik.Web.UI.GridDataItemCancelEventArgs.initializeBase(this);
//	
//	this._id = "";
//	this._itemIndexHierarchical = "";
//	this._gridDataItem = null;
//	this._tableView = null;
//	this._dataKeyValues = null;
//	
//	if (rowElement)
//	{
//	    this._id = rowElement.id;
//	    this._itemIndexHierarchical = this._id.split("__")[1];
//	    this._gridDataItem = $find(this._id);
//	    this._tableView = $find(this._id.split("__")[0]);
//	    
//	    if(this._tableView._owner._clientKeyValues &&
//	    this._tableView._owner._clientKeyValues[this._itemIndexHierarchical])
//	    {
//	        this._dataKeyValues = this._tableView._owner._clientKeyValues[this._itemIndexHierarchical];
//	    }
//	}
//	
//	this._domEvent = domEvent;
//};

//Telerik.Web.UI.GridDataItemCancelEventArgs.prototype = 
//{
//	get_gridDataItem : function ()
//	{
//		return this._gridDataItem;
//	},

//	get_itemIndexHierarchical : function ()
//	{
//		return this._itemIndexHierarchical;
//	},

//	get_id : function ()
//	{
//		return this._id;
//	},
//	
//    get_tableView : function ()
//	{
//		return this._tableView;
//	},

//	get_domEvent : function ()
//	{
//		return this._domEvent;
//	},
//	
//    getDataKeyValue : function (columnName)
//	{
//		return (this._dataKeyValues)? this._dataKeyValues[columnName] : null;
//	}

//};

//Telerik.Web.UI.GridDataItemCancelEventArgs.registerClass("Telerik.Web.UI.GridDataItemCancelEventArgs", Sys.CancelEventArgs);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridScrolling = function() 
{
    Telerik.Web.UI.GridScrolling.initializeBase(this);

    this._owner = {};
    this._onGridScrollDelegate = null;
};

Telerik.Web.UI.GridScrolling.prototype = 
{
    initialize : function() 
    {
        Telerik.Web.UI.GridScrolling.callBaseMethod(this, 'initialize');
 
        this.AllowScroll = this._owner.ClientSettings.Scrolling.AllowScroll;
        this.UseStaticHeaders = this._owner.ClientSettings.Scrolling.UseStaticHeaders;
       
        this._initializeDimensions();
        this._initializeScroll();
    },
    
    updated : function() 
    {
        Telerik.Web.UI.GridScrolling.callBaseMethod(this, 'updated');
    },
    
    dispose : function() 
    {
        if(this._onResizeDelegate)
        {
             try
             {
                $removeHandler(window, "resize", this._onResizeDelegate);
                this._onResizeDelegate  = null;
             }
             catch(e) { }
        }
        if(this._onGridFrozenScrollDelegate)
        {  
            $removeHandler(this._frozenScroll, "scroll", this._onGridFrozenScrollDelegate);
            this._onGridFrozenScrollDelegate  = null;
        }
        
        if(this._onGridScrollDelegate)
        {        
            if(this._owner.GridDataDiv)
            {
                $removeHandler(this._owner.GridDataDiv, "scroll", this._onGridScrollDelegate);
            }
        	
	        if(this._owner.GridHeaderDiv)
	        {
	            $removeHandler(this._owner.GridHeaderDiv, "scroll", this._onGridScrollDelegate);                
	        }
	        this._onGridScrollDelegate  = null; 
        }       
        
        if(this._frozenScroll)
            $clearHandlers(this._frozenScroll);
       
        Telerik.Web.UI.GridScrolling.callBaseMethod(this, 'dispose');
    },
    
    _initializeDimensions : function()
    {
        var thisObject = this;

        this.applyFrozenScroll();

        this.onWindowResize();

        this.initializeAutoLayout();

        //this._owner.get_element().RadResize = function(){thisObject.onWindowResize();};

        if(navigator.userAgent.toLowerCase().indexOf("msie") != -1)
        {
            this._onResizeDelegate = Function.createDelegate(this, this.onWindowResize);
            setTimeout(function(){
		            $addHandler(window, "resize", thisObject._onResizeDelegate);
            }, 0);
        }
        else
        {
    		this._onResizeDelegate = Function.createDelegate(this, this.onWindowResize);
            $addHandler(window, "resize", this._onResizeDelegate);
        }

        //this._owner.get_element().RadShow = function(){thisObject.onWindowResize();};        
        
        if (this._owner.ClientSettings.Scrolling.FrozenColumnsCount > 0) 
        {
            if (this._owner.ClientSettings.Resizing.AllowRowResize)
                this._owner.ClientSettings.Scrolling.FrozenColumnsCount++;
                
            if (this._owner.MasterTableViewHeader && this._owner.MasterTableViewHeader._data._columnsData) 
            {
                for(var i = 0, length = this._owner.MasterTableViewHeader._data._columnsData.length; i < length;i++)
                {
                    if (this._owner.MasterTableViewHeader._data._columnsData[i].ColumnType == "GridExpandColumn")
                    {
                        this._owner.ClientSettings.Scrolling.FrozenColumnsCount++;                        
                    }
                }
            }   
            	    
//            if (this._owner.get_detailTables().length > 0)    
//                    this._owner.ClientSettings.Scrolling.FrozenColumnsCount++;
                    
//            this._owner.ClientSettings.Scrolling.FrozenColumnsCount += 
//                this._owner.get_masterTableViewHeader().ExpandCollapseColumns.length + 
//                this._owner.get_masterTableViewHeader().GroupSplitterColumns.length;
        }
        
    },
    
    applyFrozenScroll : function()
    {        
        this.isFrozenScroll = false;
        
        this._frozenScroll = $get(this._owner.ClientID + "_Frozen");               
                
        var scrollbarHeight = Telerik.Web.UI.Grid.getScrollBarHeight();               
        
	    if(this._frozenScroll)
	    {	    
	        var frozenScrollChild = $get(this._owner.ClientID + "_FrozenScroll");
	        
	        this._onGridFrozenScrollDelegate = Function.createDelegate(this, this.onGridFrozenScroll);	        
            $addHandler(this._frozenScroll, "scroll", this._onGridFrozenScrollDelegate);
    
            if(this._owner.get_masterTableView().get_element().offsetWidth > this._owner.GridDataDiv.clientWidth)
            {
                this._frozenScroll.style.height = scrollbarHeight + "px";
               

                frozenScrollChild.style.width = this._owner.GridDataDiv.scrollWidth + "px";
                frozenScrollChild.style.height = scrollbarHeight + "px";

                if(this._owner.ClientSettings.Scrolling.SaveScrollPosition && this._owner.ClientSettings.Scrolling.ScrollLeft != "")
                {
                    this._frozenScroll.scrollLeft = this._owner.ClientSettings.Scrolling.ScrollLeft;
                }

                if(this._owner.GridDataDiv.style.overflowX != null)
                {
                    this._owner.GridDataDiv.style.overflowX = "hidden";
                }
                else
                {
                     this._frozenScroll.style.marginTop = "-16px";
                     this._frozenScroll.style.zIndex = 99999;
                     this._frozenScroll.style.position = "relative";
                }
                
                if(window.netscape && !window.opera)
                {
                    this._frozenScroll.style.width = this._owner.GridDataDiv.offsetWidth - scrollbarHeight + "px";
                }
                
                if(this._owner.GridHeaderDiv && this._owner.GridDataDiv)
	            {
                    if((this._owner.GridDataDiv.clientWidth == this._owner.GridDataDiv.offsetWidth))
                    {
                        if(typeof(this._frozenScroll.style.overflowX) != "undefined" &&
                            typeof(this._frozenScroll.style.overflowY) != "undefined")
                        {
                            this._frozenScroll.style.overflowX = "auto";
                            this._frozenScroll.style.overflowY = "hidden";
                           
                            if(window.netscape)
                            {
                                this._frozenScroll.style.width = parseInt(this._frozenScroll.style.width) + scrollbarHeight + "px";
                            }
                            //frozenScroll.style.overflow = "";
                            //frozenScroll.style.width = this.GridDataDiv.clientWidth + "px";
                        }
                    }
	            }

                this.isFrozenScroll = true;
                
            }
            else
            {
                this._frozenScroll.style.height = "";
                frozenScrollChild.style.width = "";
                this._owner.GridDataDiv.style.overflow = "auto";
                this.isFrozenScroll = false;
            }
            
            
	    }
    },
    
    onGridFrozenScroll : function(args)
    {   
        if(!this._frozenScrollCounter)
        {
            this._frozenScrollCounter = 0;
        }
        
        this._frozenScrollCounter++;

        var gridControl = this;
        
        gridControl._currentElement = Telerik.Web.UI.Grid.GetCurrentElement(args);
        
        Telerik.Web.UI.Grid.frozenScrollHanlder = function(count)
        {      
            
            if (gridControl._frozenScrollCounter != count)
	            return;
            
            if(!gridControl._lastScrollIndex)
            {
                gridControl._lastScrollIndex = 0;
            }
                       
            var currentElement = gridControl._currentElement;
            
            if(gridControl._owner.ClientSettings.Scrolling.FrozenColumnsCount > gridControl._owner.get_masterTableViewHeader().get_columns().length)
            {
                gridControl.isFrozenScroll = false;
            }

            if(gridControl.isFrozenScroll)
            {
                var lastFrozenCell = gridControl._owner.get_masterTableView().get_columns()[gridControl._owner.ClientSettings.Scrolling.FrozenColumnsCount - 1].get_element();
	            var right = Telerik.Web.UI.Grid.FindPosX(lastFrozenCell) - 
									        Telerik.Web.UI.Grid.FindScrollPosX(lastFrozenCell) + 
									        document.documentElement.scrollLeft + 
									        document.body.scrollLeft + lastFrozenCell.offsetWidth;

                var scrollWidthWithoutFrozenColumns = currentElement.scrollWidth - right;

                gridControl._owner.notFrozenColumns = [];
               // var firstDataRow = gridControl._owner.get_masterTableView().get_element().tBodies[0].rows[gridControl._owner.ClientSettings.FirstDataRowClientRowIndex];
                var firstDataRow = gridControl._owner.get_masterTableView()._getFirstDataRow();
                for(var i = gridControl._owner.ClientSettings.Scrolling.FrozenColumnsCount; 
                    i < gridControl._owner.get_masterTableView().get_columns().length; i++)
                {
                    var column = gridControl._owner.get_masterTableView().get_columns()[i];

                    var restoreDisplay = false;
                    if(window.netscape && column.get_element().style.display == "none")
                    {
                        column.get_element().style.display = "table-cell";
                        restoreDisplay = true;
                    }

                    var offsetWidth = (column.get_element().offsetWidth > 0)? column.get_element().offsetWidth : firstDataRow.cells[i].offsetWidth;
                    
                    gridControl._owner.notFrozenColumns[gridControl._owner.notFrozenColumns.length] = {Index: i, Width: offsetWidth};
                
                    if(window.netscape && restoreDisplay)
                    {
                        column.get_element().style.display = "none";
                        restoreDisplay = false;
                    }
                }

                var scrollBarWidth = Telerik.Web.UI.Grid.getScrollBarHeight();
                
                if(window.netscape && !window.opera)
                {
                    scrollBarWidth = 0;
                }
        	        
                var scrollPercent = Math.ceil(currentElement.scrollLeft / (currentElement.scrollWidth - (1.5 * lastFrozenCell.offsetWidth))* 100);
                var hiddenPercent = 0;
                var i = 0;                
                        
                while (i < gridControl._owner.notFrozenColumns.length - 1)//always show the last column
                {
                    var column = gridControl._owner.notFrozenColumns[i];
                    var columnPercent = Math.floor(column.Width / scrollWidthWithoutFrozenColumns * 100);
                        
                    if (columnPercent + hiddenPercent <= scrollPercent)
                    {                        
                        //hide current
                        if(!gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay)
                            gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay = true;
                            
                        if(typeof(gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay) == "boolean" &&
                            !gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay)
                        {
                            i++;
                            continue;
                        }
                        
                        gridControl._owner.get_masterTableViewHeader()._hideNotFrozenColumn(column.Index);
                        hiddenPercent += columnPercent;
                    }
                    else
                    {
                        if(!gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay)
                            gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay = false;
                            
                        if(typeof(gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay) == "boolean" &&
                            gridControl._owner.get_masterTableView().get_columns()[column.Index].FrozenDisplay)
                        {
                            i++;
                            continue;
                        }

                        gridControl._owner.get_masterTableViewHeader()._showNotFrozenColumn(column.Index);

                    }                   
                    i++;
                }

                gridControl._owner.get_masterTableView().get_element().style.width = gridControl._owner.get_masterTableViewHeader().get_element().offsetWidth + "px";

                if(gridControl._owner.get_masterTableViewFooter())
                {
                    gridControl._owner.get_masterTableViewFooter().get_element().style.width = gridControl._owner.get_masterTableViewHeader().get_element().offsetWidth + "px";
                }

                //gridControl._owner.SavePostData("ScrolledControl", gridControl._owner.ClientID, gridControl._owner.GridDataDiv.scrollTop, currentElement.scrollLeft);
            }
            else
            {
                gridControl._owner.GridDataDiv.scrollLeft = currentElement.scrollLeft;
            }
        
        /////////////////////////////////////
                gridControl._frozenScrollCounter = 0;
    		
        };
        
	    setTimeout("Telerik.Web.UI.Grid.frozenScrollHanlder(" + this._frozenScrollCounter + ")", 0);        
    },
    
    onWindowResize : function()
    {
        this.setHeaderAndFooterDivsWidth();
        this.setDataDivHeight();
        this.applyFrozenScroll();
    },
    
    setHeaderAndFooterDivsWidth : function()
    {
        if(!this._owner.MasterTableView)
            return;

	    if (this._owner.GridDataDiv && this._owner.GridHeaderDiv)
	    {
	        if(navigator.userAgent.toLowerCase().indexOf("msie") != -1)
	        {
                if(this._owner.GridDataDiv.offsetWidth > 0
					&& (this._owner.MasterTableView.get_element().offsetWidth >= this._owner.get_element().offsetWidth - Telerik.Web.UI.Grid.getScrollBarHeight()
						|| this._owner.MasterTableView.get_element().offsetHeight > this._owner.GridDataDiv.offsetHeight)
					&& (document.compatMode && document.compatMode != "BackCompat")) // Not Quirks Mode
				{
					this._owner.GridHeaderDiv.style.width = this._owner.GridDataDiv.offsetWidth - 
					    Telerik.Web.UI.Grid.getScrollBarHeight() + "px";
				}
				else if(this._owner.GridDataDiv.offsetWidth > 0)
				{
					this._owner.GridHeaderDiv.style.width = this._owner.GridDataDiv.offsetWidth + "px";
				}
	        }

            var isRtl = Telerik.Web.UI.Grid.IsRightToLeft(this._owner.GridHeaderDiv);
            
            if (this._owner.MasterTableView.get_element().offsetWidth >= this._owner.get_element().offsetWidth - Telerik.Web.UI.Grid.getScrollBarHeight()
				|| this._owner.MasterTableView.get_element().offsetHeight > this._owner.GridDataDiv.offsetHeight
				|| navigator.userAgent.toLowerCase().indexOf("msie") == -1)
            {
				if((!isRtl && this._owner.GridHeaderDiv &&
					parseInt(this._owner.GridHeaderDiv.style.paddingRight) != Telerik.Web.UI.Grid.getScrollBarHeight()) 
					||
					(isRtl && this._owner.GridHeaderDiv &&
					parseInt(this._owner.GridHeaderDiv.style.paddingLeft) != Telerik.Web.UI.Grid.getScrollBarHeight())
					||
					(navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1))
				{
					if(!isRtl)
					{
						if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1)
						{
							this._owner.GridHeaderDiv.style.marginRight = Telerik.Web.UI.Grid.getScrollBarHeight() + "px";
							this._owner.GridHeaderDiv.style.marginLeft = "";
							this._owner.GridHeaderDiv.style.paddingRight = "";
						}
						else
						{
							this._owner.GridHeaderDiv.style.paddingRight = Telerik.Web.UI.Grid.getScrollBarHeight() + "px";
							this._owner.GridHeaderDiv.style.paddingLeft = "";
						}
					}
					else
					{
						if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1)
						{
							this._owner.GridHeaderDiv.style.marginLeft = Telerik.Web.UI.Grid.getScrollBarHeight() + "px";
							this._owner.GridHeaderDiv.style.marginRight = "";
							this._owner.GridHeaderDiv.style.paddingLeft = "";
						}
						else
						{
							this._owner.GridHeaderDiv.style.paddingLeft = Telerik.Web.UI.Grid.getScrollBarHeight() + "px";
							this._owner.GridHeaderDiv.style.paddingRight = "";
						}
					}
				}
            }
            else
            {
				this._owner.GridHeaderDiv.style.paddingLeft = "";
				this._owner.GridHeaderDiv.style.paddingRight = "";
            }
                	   
	        if(this._owner.GridHeaderDiv && this._owner.GridDataDiv)
	        {
	            var thisObject = this;
                setTimeout(function(){                    
                    if(thisObject._owner.GridDataDiv.clientWidth == thisObject._owner.GridDataDiv.offsetWidth)
                    {
                        thisObject._owner.GridHeaderDiv.style.width = "100%";
                        if(!isRtl)
                        {
                            thisObject._owner.GridHeaderDiv.style.paddingRight = "";
                        }
                        else
                        {
                            thisObject._owner.GridHeaderDiv.style.paddingLeft = "";
                        }
                    }
                    
                    if(thisObject._owner.GridFooterDiv)
                    {
                        thisObject._owner.GridFooterDiv.style.paddingRight = thisObject._owner.GridHeaderDiv.style.paddingRight;
                        thisObject._owner.GridFooterDiv.style.paddingLeft = thisObject._owner.GridHeaderDiv.style.paddingLeft;
                        thisObject._owner.GridFooterDiv.style.width = thisObject._owner.GridHeaderDiv.style.width;
                        // FF3
                        thisObject._owner.GridFooterDiv.style.marginRight = thisObject._owner.GridHeaderDiv.style.marginRight;
                        thisObject._owner.GridFooterDiv.style.marginLeft = thisObject._owner.GridHeaderDiv.style.marginLeft;
                    }
                    
                    if(thisObject._owner._groupPanel && thisObject._owner._groupPanel._items.length > 0 
                        && navigator.userAgent.toLowerCase().indexOf("msie") != -1)
	                {
	                    if(thisObject._owner.MasterTableView && thisObject._owner.get_masterTableViewHeader())
	                    {
	                        thisObject._owner.MasterTableView.get_element().style.width = 
	                            thisObject._owner.get_masterTableViewHeader().get_element().offsetWidth + "px";
	                    }
	                }
	                
                },0);
	        }

        }
    },
    
    setDataDivHeight : function()
    {
        if(this._owner.GridDataDiv && this._owner.get_element().style.height != "")
        {
            this._owner.GridDataDiv.style.height = "10px";
            var height = 0;
            var groupPanel = $get(this._owner._groupPanelClientID);
            if (groupPanel)
            {
	            height += groupPanel.offsetHeight;
            }

            if (this._owner.GridHeaderDiv)
            {
	            height += this._owner.GridHeaderDiv.offsetHeight;
            }

            if (this._owner.GridFooterDiv)
            {
	            height += this._owner.GridFooterDiv.offsetHeight;
            }
            
            if (this._owner.PagerControl)
            {
	            height += this._owner.PagerControl.offsetHeight;
            }
     
            if (this._owner.TopPagerControl)
            {
	            height += this._owner.TopPagerControl.offsetHeight;
            }
           
            if(this._owner.ClientSettings.Scrolling.FrozenColumnsCount > 0)
            {
                height += Telerik.Web.UI.Grid.getScrollBarHeight();
            }
            
            var newHeight = this._owner.get_element().clientHeight - height;

            if(newHeight > 0)
            {
                var oldPosition = this._owner.get_element().style.position;
                if(window.netscape)
                {
                    this._owner.get_element().style.position = "absolute";
                }
                
                this._owner.GridDataDiv.style.height = newHeight + "px";
                
                if(window.netscape)
                {
                    this._owner.get_element().style.position = oldPosition;
                }
            }
        }
    },
    
    initializeAutoLayout : function()
    {
	    if (this.AllowScroll && this.UseStaticHeaders)
	    {
	        if(this._owner.MasterTableView && this._owner.get_masterTableViewHeader())
            {
                if(this._owner.MasterTableView.get_element().style.tableLayout != "auto")
                    return;

                var firstDataRow = this._owner.MasterTableView._getFirstDataRow();

                if(!firstDataRow)
                {
                    this._owner.MasterTableView.get_element().style.width = 
                        this._owner.get_masterTableViewHeader().get_element().offsetWidth + "px";
                    return;
                }

                this._owner.MasterTableView.get_element().style.tableLayout = 
                    this._owner.get_masterTableViewHeader().get_element().style.tableLayout = "auto";

                
                var headerRow = this._owner.get_masterTableViewHeader().HeaderRow;
                var cellsPerRow = 0;
                
                if(firstDataRow)
                {
                    cellsPerRow = Math.min(headerRow.cells.length, firstDataRow.cells.length);
                }
                var calculatedWidth = 0;
                for (var i = 0; i < cellsPerRow; i++)
                {
                    var col = this._owner.get_masterTableViewHeader().ColGroup.Cols[i];

                    if(!col)
                        continue;

                    if(col.width != "" && !window.netscape)
                        continue;

                    var width1 = headerRow.cells[i].offsetWidth;
                    
                    var width2 = 0;
                    if(firstDataRow)
                    {
                        width2 = firstDataRow.cells[i].offsetWidth;
                    }
                    
                    var width = (width1 > width2)? width1 : width2;
                    
 		            if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().get_element())
		            {
			            if (this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0] &&
			                this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[i])
			            {
			               if(this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[i].offsetWidth > width)
			               {
					            width = this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[i].offsetWidth;
					       }
			            }
		            }
		            
		            calculatedWidth = calculatedWidth + width;

                    if(width <= 0)
                        continue;

                    headerRow.cells[i].style.width = width + "px";
                    this._owner.MasterTableView.ColGroup.Cols[i].width = width + "px";
                    col.width = width + "px";

                    if(firstDataRow)
                    {
                        firstDataRow.cells[i].style.width = width + "px";
                    }
                                        
		            if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().get_element())
		            {
			            if (this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0] &&
			                this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[i])
			            {
					       this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[i].style.width = width;
			            }
		            }
                }
                

                this._owner.MasterTableView.get_element().style.tableLayout =  this._owner.get_masterTableViewHeader().get_element().style.tableLayout = "fixed"

                if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().get_element())
	            {
                    this._owner.get_masterTableViewFooter().get_element().style.tableLayout = "fixed";
	            }

                if(window.netscape && calculatedWidth > 0)
                {
                    var tableWidth = calculatedWidth +  "px";

                    this._owner.MasterTableView.get_element().style.width = tableWidth;
                    this._owner.get_masterTableViewHeader().get_element().style.width = tableWidth;
                    
                    //this._owner.MasterTableView.get_element()["style"] = 
                    //     this._owner.MasterTableView.get_element()["style"];

                    //this._owner.MasterTableView.get_element().style.width = calculatedWidth + "px";
                   // this._owner.MasterTableViewHeader.get_element().style.width = calculatedWidth + "px";

                    this.onWindowResize();;
                }
            }
	    }
    },
    
    initializeSaveScrollPosition : function()
    {
        if (!this._owner.ClientSettings.Scrolling.SaveScrollPosition)
		    return;
			
	    if (this._owner.ClientSettings.Scrolling.ScrollTop != "" && !this._owner.ClientSettings.Scrolling.EnableVirtualScrollPaging)
	    {
		    this._owner.GridDataDiv.scrollTop = this._owner.ClientSettings.Scrolling.ScrollTop;
	    }
	    
	    var frozenScroll = $get(this._owner.ClientID + "_Frozen");

	    if (this._owner.ClientSettings.Scrolling.ScrollLeft &&
			this._owner.ClientSettings.Scrolling.ScrollLeft != "")
	    {
		    if(this._owner.GridHeaderDiv && !frozenScroll)
		    {
			    this._owner.GridHeaderDiv.scrollLeft = this._owner.ClientSettings.Scrolling.ScrollLeft;
		    }
    		
		    if(this._owner.GridFooterDiv && !frozenScroll)
		    {
			    this._owner.GridFooterDiv.scrollLeft = this._owner.ClientSettings.Scrolling.ScrollLeft;
		    }
    		
	        if(frozenScroll)
            {
                frozenScroll.scrollLeft = this._owner.ClientSettings.Scrolling.ScrollLeft;
            }
            else
            {
		        this._owner.GridDataDiv.scrollLeft = this._owner.ClientSettings.Scrolling.ScrollLeft;
		    }
	    }
	    else if (!frozenScroll && Telerik.Web.UI.Grid.IsRightToLeft(this._owner.get_masterTableView().get_element()))
	    {
			if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1 &&
				Telerik.Web.UI.Grid.IsRightToLeft(this._owner.get_element())
				)
			{
				this._owner.GridDataDiv.scrollLeft = 0;
			}
			else
			{
				this._owner.GridDataDiv.scrollLeft = this._owner.GridDataDiv.scrollWidth;
			}
	    }
    },
    
    _initializeScroll : function()
    {        
	    var thisObject = this;
	    var setupScroll = function()
	    {
		    thisObject.initializeSaveScrollPosition();
	    }
    	
	    if (window.netscape && !window.opera)
	    {
		    window.setTimeout(setupScroll, 0);
	    }
	    else
	    {
		    setupScroll();
	    }

	    this._initializeVirtualScrollPaging();
        
        if(this._owner.GridDataDiv || this._owner.GridHeaderDiv)
        {
            this._onGridScrollDelegate = Function.createDelegate(this, this._onGridScroll);
            
            if(this._owner.GridDataDiv)
            {
                $addHandlers(this._owner.GridDataDiv, {scroll:this._onGridScrollDelegate});
            }
        	
	        if(this._owner.GridHeaderDiv)
	        {
                $addHandlers(this._owner.GridHeaderDiv, {scroll:this._onGridScrollDelegate});
	        }
	    }
    },

    _hideRadComboBoxes : function()
    {        
        if (Telerik.Web.UI.RadComboBox)
        {
            var children = document.getElementsByTagName("div");
            var dropDowns = [];
            for (var i = 0, length = children.length; i < length; i++)
            {
                var child = children[i];
                
                if (Sys.UI.DomElement.containsCssClass(child, "rcbSlide"))
                {
                    Array.add(dropDowns, child);
                }
            }
            
            for (var i = 0, length = dropDowns.length; i < length; i++)
            {
                var innerDivs = dropDowns[i].getElementsByTagName("div");
                if (innerDivs)
                {
                    for (var j = 0, length1 = innerDivs.length; j < length1; j++)
                    {
                        if (innerDivs[j].id.indexOf("_DropDown") > -1)
                        {
                            var comboId = innerDivs[j].id.substr(0, innerDivs[j].id.indexOf("_DropDown"));
                            var combo = $find(comboId);
                            if (combo && combo.get_dropDownVisible() && Telerik.Web.UI.Grid.IsChildOf(combo.get_element(),this._owner.get_element()))                                 
                                combo.hideDropDown();
                        }
                    }
                }
            }            
        }
    },
    
    _onGridScroll : function(e)
    {   
        if(this._owner._getFilterMenu())
        {
            this._owner._getFilterMenu().hide();
        }        
        
        this._hideRadComboBoxes();
        
        if (Telerik.Web.UI.RadDatePicker){
            var popups = Telerik.Web.UI.RadDatePicker.PopupInstances;
            for(var item in popups)
            {                
                if ($find(item) &&
                    (
                        ($find(item).get_id().indexOf(this._owner.ClientID + "_" + "gdtcSharedCalendar") > -1) ||
                        ($find(item).get_id().indexOf(this._owner.ClientID + "_" + "gdtcSharedTimeView") > -1)
                    )
                   )
                {
                    Telerik.Web.UI.RadDatePicker.PopupInstances[item].Hide();
                }
            }

        }
        
        var currentElement = (e.srcElement)? e.srcElement : e.target;
        if(window.opera && this.isFrozenScroll)
        {
            this._owner.GridDataDiv.scrollLeft =  this._owner.GridHeaderDiv.scrollLeft =  0;
            return;
        }
        
	    if (this.UseStaticHeaders)
	    {	        
	        this._updateDataDivScrollPos(currentElement);
	    }
	    
	    if (!Telerik.Web.UI.GridSelection)
	    {	        
	        var selectedItems =  this._owner._selectedItemsInternal;
	        if(selectedItems.length > 0)
            {
                for(var i = 0; i < selectedItems.length; i++)
                {
                    if (selectedItems != null)
                        Array.add(this._owner._selectedIndexes,  selectedItems[i].itemIndex);
                }
            }
        }
	    this._owner.updateClientState();
        
        this._owner.raise_scroll(new Telerik.Web.UI.GridScrollEventArgs(this._owner._gridDataDiv));
    },
    
    _updateDataDivScrollPos : function(currentElement)
    {
        if(!currentElement)
            return;
            
        if(!this.isFrozenScroll)
        {       
            if (this._owner.GridHeaderDiv)
            {
                if(currentElement == this._owner.GridHeaderDiv)
                {                    
                    if($telerik.isSafari)
                    {   
                        if(this._owner.GridHeaderDiv.scrollLeft && 
                            this._owner.GridHeaderDiv.scrollLeft != this._owner.GridDataDiv.scrollLeft)
                        {                            
                            this._owner.GridDataDiv.scrollLeft = this._owner.GridHeaderDiv.scrollLeft;                        
                        }
                    }
                    else
                    {
                        this._owner.GridDataDiv.scrollLeft = this._owner.GridHeaderDiv.scrollLeft;
                    }
                }

                if(currentElement == this._owner.GridDataDiv)
                {
                    if($telerik.isSafari)
                    { 
                       if(this._owner.GridHeaderDiv.scrollLeft != this._owner.GridDataDiv.scrollLeft)
                        this._owner.GridHeaderDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft; 
                    }
                    else
                    {
                        this._owner.GridHeaderDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft;
                    }
                }
            }
            
            if (this._owner.GridFooterDiv)
            {               
	           this._owner.GridFooterDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft;
            }
        }
        else
        {
             if(this._owner.GridHeaderDiv)
             {
                if($telerik.isSafari)
                { 
                    if(this._owner.GridHeaderDiv.scrollLeft &&  this._owner.GridHeaderDiv.scrollLeft != this._owner.GridDataDiv.scrollLeft)
                        this._owner.GridHeaderDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft;
                }
                else
                {                    
                    this._owner.GridHeaderDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft;
                }
             }
             if(this._owner.GridFooterDiv)
             {  
                this._owner.GridFooterDiv.scrollLeft = this._owner.GridDataDiv.scrollLeft;                
             } 
        }       
        
    },
    
    _initializeVirtualScrollPaging : function()
    {
        if (!this._owner.ClientSettings.Scrolling.EnableVirtualScrollPaging)
        {
		    return;
		}
		    
		this._scrollCounter = 0;
		this._currentAJAXScrollTop = 0;
		
		if (this._owner.ClientSettings.Scrolling.AJAXScrollTop != "")
		{
		    this._currentAJAXScrollTop = this._owner.ClientSettings.Scrolling.AJAXScrollTop;
		}
		
		
		var pixelsBefore = this._owner._currentPageIndex * this._owner.get_masterTableView().get_pageSize() * 20;
		var totalPixels = this._owner.get_masterTableView().get_pageCount() * this._owner.get_masterTableView().get_pageSize() * 20;
		var pixelsLeft = totalPixels - pixelsBefore;
		
		var masterTable = this._owner.get_masterTableView().get_element();
		
		//if(!masterTable)return;
		
		var tableHeight = masterTable.offsetHeight;
		var divHeight = this._owner._gridDataDiv.offsetHeight;
		
	    if (!window.opera)
	    {
		    masterTable.style.marginTop = pixelsBefore + "px";
		    
            if (pixelsLeft >= divHeight)
            {
                masterTable.style.marginBottom = pixelsLeft - tableHeight + "px";
            }
            else
            {
                masterTable.style.marginBottom = divHeight - tableHeight + "px";
            }
	    }
	    else
	    {
		    //opera does not posisition the table properly when you set marginTop
		    //the current code still has problems -- the scroll position is incorrect, 
		    //but you can still scroll to the desired page and the tooltip shows correct data.
		    masterTable.style.position = "relative";
		    masterTable.style.top = pixelsBefore + "px";
		    masterTable.style.marginBottom = totalPixels - tableHeight + "px";
	    }
    	
	    this._currentAJAXScrollTop = pixelsBefore;
	    this._owner._gridDataDiv.scrollTop = pixelsBefore;
    	
	    this._createScrollerToolTip();
	    var onAjaxScrollDelegate = Function.createDelegate(this, this._onAjaxScrollHandler);
	    $addHandler(this._owner._gridDataDiv, "scroll", onAjaxScrollDelegate);
    },
    
    _createScrollerToolTip : function()
    {
	    var scrollerToolTip = $get(this._owner.get_id() + "ScrollerToolTip");
	    if (!scrollerToolTip)
	    {
		    this._scrollerToolTip = document.createElement("span");
		    this._scrollerToolTip.id = this._owner.get_id() + "ScrollerToolTip";
		    this._scrollerToolTip.style.position = "absolute";
		    this._scrollerToolTip.style.display = "none";
		    if (this._owner.Skin != "")
		    {
				this._scrollerToolTip.className = String.format("GridToolTip_{0}", this._owner.Skin);
		    }
		    if (!this._owner._embeddedSkin || this._owner.Skin == "")
		    {
			    this._scrollerToolTip.style.border = "1px solid";
			    this._scrollerToolTip.style.backgroundColor = "#F5F5DC";
			    this._scrollerToolTip.style.font = "icon";
			    this._scrollerToolTip.style.padding = "2px";
		    }
		    document.body.appendChild(this._scrollerToolTip);
	    }
    },
    
    _onAjaxScrollHandler : function(e)
    {
	    var gridDataDiv = this._owner._gridDataDiv;
	    if (gridDataDiv)
	    {
		    this._currentScrollTop = gridDataDiv.scrollTop;
	    }

	    this._scrollCounter++;
	    
	    var thisObj = this;
	    Telerik.Web.UI.Grid.AjaxScrollInternal = function(count)
        {
            if (thisObj._scrollCounter != count)
            {
                return;
            }
            
            var gridDataDiv = thisObj._owner._gridDataDiv;
            if (thisObj._currentAJAXScrollTop != gridDataDiv.scrollTop)
            {
                if (thisObj._owner._currentPageIndex == newPageIndex)
			    {
			        return;
			    }
    				 
                thisObj._owner.get_masterTableView().page(newPageIndex + 1);
            }
            
	        thisObj._scrollCounter = 0;
	        thisObj._hideScrollerToolTip();      
        };

	    this._owner.raise_scroll(new Telerik.Web.UI.GridScrollEventArgs(gridDataDiv));
    	
    	var scrollbarHeight = Telerik.Web.UI.Grid.getScrollBarHeight();
	    var scrollFraction = gridDataDiv.scrollTop / (gridDataDiv.scrollHeight - gridDataDiv.offsetHeight + scrollbarHeight);
        var newPageIndex = Math.round((this._owner.get_masterTableView().get_pageCount() - 1) * scrollFraction);
    	
	    window.setTimeout("Telerik.Web.UI.Grid.AjaxScrollInternal(" + this._scrollCounter + ")", 500);
	    
	    this._showScrollerTooltip(scrollFraction, newPageIndex);
    },
    
    _showScrollerTooltip : function(scrollFraction, newPageIndex)
    {
	    var scrollerToolTip = $get(this._owner.get_id() + "ScrollerToolTip");
	    if (scrollerToolTip)
	    {
	        var gridDataDiv = this._owner._gridDataDiv;
		    scrollerToolTip.style.display = "";
		    scrollerToolTip.style.top =  parseInt(Telerik.Web.UI.Grid.FindPosY(gridDataDiv)) + Math.round(gridDataDiv.offsetHeight * scrollFraction) + "px";
		    scrollerToolTip.style.left = parseInt(Telerik.Web.UI.Grid.FindPosX(gridDataDiv)) + gridDataDiv.offsetWidth - (gridDataDiv.offsetWidth - gridDataDiv.clientWidth) - scrollerToolTip.offsetWidth + "px";
		    
		    var pageCount = this._owner.get_masterTableView().get_pageCount();
		    this._applyPagerTooltipText(scrollerToolTip, newPageIndex, pageCount);
	    }
    },
    
    _applyPagerTooltipText : function(toolTipElement, pageIndex, pageCount)
    {
	    var toolTipString = this._owner.ClientSettings.ClientMessages.PagerTooltipFormatString;
	    var formatterZero = /\{0[^\}]*\}/g;
	    var formatterOne = /\{1[^\}]*\}/g;
    	
	    var startIndex = ((pageIndex == 0)? 1 : pageIndex + 1);
	    var endIndex = pageCount;
    	
	    toolTipString = toolTipString.replace(formatterZero, startIndex).replace(formatterOne, endIndex);
	    toolTipElement.innerHTML = toolTipString;
    },
    
    _hideScrollerToolTip : function()
    {
	    var thisObj = this;
	    setTimeout(function(){
		    var scrollerToolTip = $get(thisObj._owner.get_id() + "ScrollerToolTip");
		    if (scrollerToolTip && scrollerToolTip.parentNode)
		    {
			    scrollerToolTip.style.display = "none";
		    }
	    }, 200);
    }   
};

Telerik.Web.UI.GridScrolling.registerClass('Telerik.Web.UI.GridScrolling', Sys.Component);

Telerik.Web.UI.GridScrollEventArgs = function(gridDataDiv)
{
    Telerik.Web.UI.GridScrollEventArgs.initializeBase(this);

    this.scrollTop = gridDataDiv.scrollTop;
    this.scrollLeft = gridDataDiv.scrollLeft;
    this.scrollControl = gridDataDiv;
    this.isOnTop = (gridDataDiv.scrollTop == 0) ? true : false;

    var scrollbarHeight = Telerik.Web.UI.Grid.getScrollBarHeight();
    if(gridDataDiv.clientWidth == gridDataDiv.scrollWidth)
    {
        scrollbarHeight = 0;
    }
    
    this.isOnBottom = ((gridDataDiv.scrollHeight - gridDataDiv.offsetHeight + scrollbarHeight) == gridDataDiv.scrollTop) ? true : false;
}

Telerik.Web.UI.GridScrollEventArgs.prototype =
{
    get_scrollTop : function()
    {
        return this.scrollTop;
    },
    
    get_scrollLeft : function()
    {
        return this.scrollLeft;
    },
    
    get_scrollControl : function()
    {
        return this.scrollControl;
    },
    
    get_isOnTop : function()
    {
        return this.isOnTop;
    },
    
    get_isOnBottom : function()
    {
        return this.isOnBottom;
    }
}

Telerik.Web.UI.GridScrollEventArgs.registerClass("Telerik.Web.UI.GridScrollEventArgs", Sys.EventArgs);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridSelection = function() 
{
    Telerik.Web.UI.GridSelection.initializeBase(this);

    this._owner = {};
    this._masterTable = null;
};

Telerik.Web.UI.GridSelection.prototype = 
{
    initialize : function() 
    {
        Telerik.Web.UI.GridSelection.callBaseMethod(this, 'initialize');
        
        if(this._owner._masterClientID == null)
            return;

        $addHandlers(this._owner.get_element(), {click:Function.createDelegate(this, this._click)});
        
        this._masterTable = $get(this._owner._masterClientID).tBodies[0];
        
        $addHandlers(this._masterTable, {mousedown:Function.createDelegate(this, this._mousedown)});
        $addHandlers(this._masterTable, {mousemove:Function.createDelegate(this, this._mousemove)});
        $addHandlers(this._masterTable, {mouseup:Function.createDelegate(this, this._mouseup)});
        
        //$addHandlers(document, {mouseup:Function.createDelegate(this, this._mouseup)});
        $telerik.addExternalHandler(document, "mouseup", Function.createDelegate(this, this._mouseup));
        
        if(this._owner._selectedItemsInternal.length > 0)
        {
            for(var i = 0; i < this._owner._selectedItemsInternal.length; i++)
            {
                Array.add(this._owner._selectedIndexes,  this._owner._selectedItemsInternal[i].itemIndex);
            }
        }
    },
    
    updated : function() 
    {
        Telerik.Web.UI.GridSelection.callBaseMethod(this, 'updated');
    },
    
    dispose : function() 
    {
        if(this._masterTable)
            this._masterTable._events = null;

        this._masterTable = null;
        this._owner = null;
        Telerik.Web.UI.GridSelection.callBaseMethod(this, 'dispose');
    },
    
    _mousedown: function(e) 
    {
        if (this._owner.ClientSettings.Selecting.EnableDragToSelectRows
        && this._owner.AllowMultiRowSelection)
	    {
            this._createRowSelectorArea(e);
	    }
    },

    _mousemove: function(e) 
    {
        if(this._owner._isRowDragged())
        {
            this._destroyRowSelectorArea(e);
            return;
        }

        this._resizeRowSelectorArea(e);
    },

    _mouseup: function(e) 
    {
        this._destroyRowSelectorArea(e);
    },
    
    _createRowSelectorArea : function(e)
    {
        if (e.ctrlKey)
		    return;
    
	    var clickedObject = null;
	    if (e.srcElement)
	    {
		    clickedObject = e.srcElement;
	    }
	    else if (e.target)
	    {
		    clickedObject = e.target;
	    }
    	
	    if (!clickedObject.tagName)
		    return;
            
	    if (clickedObject.tagName.toLowerCase() == "input" || clickedObject.tagName.toLowerCase() == "textarea" ||
	        clickedObject.tagName.toLowerCase() == "select" || clickedObject.tagName.toLowerCase() == "option")
		    return;
		
        
	    if ((!this._owner.ClientSettings.Selecting.AllowRowSelect) ||
		    (!this._owner.AllowMultiRowSelection))
		    return;
    		
	    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
	    

	    if ((!currentElement) || 
		    (!Telerik.Web.UI.Grid.IsChildOf(currentElement, this._owner.get_element())))
		    return;

        this._firstRow = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "tr");
        
        if(this._firstRow.id == "")
            return;

	    if (!this._rowSelectorArea)
	    {	        
		    this._rowSelectorArea = document.createElement("span");
		    this._rowSelectorArea.style.position = "absolute";
            this._rowSelectorArea.style.zIndex = 1000100;
			if (this._owner.Skin != "")
			{
				this._rowSelectorArea.className = String.format("GridRowSelector_{0}", this._owner.Skin);
			}
			if (!this._owner._embeddedSkin || this._owner.Skin == "")
			{
			    this._rowSelectorArea.style.backgroundColor = "navy";
			}
            
		    if (window.netscape && !window.opera)
		    {
			    this._rowSelectorArea.style.MozOpacity = 1/10;
		    }
		    else if(window.opera || navigator.userAgent.indexOf("Safari") > -1)
		    {
			    this._rowSelectorArea.style.opacity  = 0.1;
		    }
		    else
		    {
			    this._rowSelectorArea.style.filter = "alpha(opacity=10);";
		    }
		    

		    if (this._owner._gridDataDiv)
		    {
			    this._rowSelectorArea.style.top = Telerik.Web.UI.Grid.FindPosY(this._firstRow) - 
				    this._owner._gridDataDiv.scrollTop + "px";
			    this._rowSelectorArea.style.left = Telerik.Web.UI.Grid.FindPosX(this._firstRow) - 
				    this._owner._gridDataDiv.scrollLeft  + "px";
    				
			    if (parseInt(this._rowSelectorArea.style.left) < Telerik.Web.UI.Grid.FindPosX(this._owner.get_element()))
			    {
				    this._rowSelectorArea.style.left = Telerik.Web.UI.Grid.FindPosX(this._owner.get_element())  + "px";
			    }			    
		    }
		    else
		    {
			    this._rowSelectorArea.style.top = Telerik.Web.UI.Grid.FindPosY(this._firstRow)  + "px";
			    this._rowSelectorArea.style.left = Telerik.Web.UI.Grid.FindPosX(this._firstRow)  + "px";			    
		    }

		    document.body.appendChild(this._rowSelectorArea);


		    Telerik.Web.UI.Grid.ClearDocumentEvents();
	    }
    },

    _destroyRowSelectorArea : function(e)
    {
	    if (this._rowSelectorArea)
	    {	        
	        var height = this._rowSelectorArea.style.height;
		    document.body.removeChild(this._rowSelectorArea);
		    this._rowSelectorArea = null;
		    Telerik.Web.UI.Grid.RestoreDocumentEvents();

		    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
		    var lastRow;

		    if ((!currentElement) || 
			    (!Telerik.Web.UI.Grid.IsChildOf(currentElement, this._owner.get_element())))
			    return;

            var parent = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "td");

		    if ((currentElement.tagName.toLowerCase() == "td") || 
			    (currentElement.tagName.toLowerCase() == "tr") || (parent && parent.tagName.toLowerCase() == "td"))
		    {
			    if (currentElement.tagName.toLowerCase() == "td")
			    {
				    lastRow = currentElement.parentNode;
			    }
			    else if (parent.tagName.toLowerCase() == "td")
			    {
				    lastRow = parent.parentNode;
			    }
			    else if(currentElement.tagName.toLowerCase() == "tr")
			    {
				    lastRow = currentElement;
			    }
			    
			    if(this._firstRow.parentNode.parentNode.id == lastRow.parentNode.parentNode.id)
			    {
			        var startIndex = (this._firstRow.rowIndex < lastRow.rowIndex) ?
			                            this._firstRow.rowIndex : lastRow.rowIndex;
			        var endIndex = (startIndex == this._firstRow.rowIndex)?
			                            lastRow.rowIndex : this._firstRow.rowIndex;

			        for (var i = startIndex; i < endIndex+1; i++)
			        {
			            var currentRow = this._firstRow.parentNode.parentNode.rows[i];
			            if(currentRow.id == "") continue;
				        if (currentRow)
				        {
				            if(height != "")
				            {
					            var item = $find(currentRow.id);
					            if(item)
					            {
					                item.set_selected(true);
					            }
					            else
					            {
                                    var tableView = $find(currentRow.id.split("__")[0]);
					                tableView.selectItem(currentRow);
					            }
					        }
				        }
			        }
			    }
			    else
			    {
			        //TODO: hierarchical select
			    }
		    }
	    }
    },

    _resizeRowSelectorArea : function(e)
    {        
	    if ((this._rowSelectorArea) && (this._rowSelectorArea.parentNode))
	    {
		    var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

		    if ((!currentElement) || 
			    (!Telerik.Web.UI.Grid.IsChildOf(currentElement, this._owner.get_element())))
			    return;

		    var oldPosX = parseInt(this._rowSelectorArea.style.left);
    		
		    if (this._owner._gridDataDiv)
		    {
			    var newPosX = Telerik.Web.UI.Grid.GetEventPosX(e) - 
				    this._owner._gridDataDiv.scrollLeft;
		    }
		    else
		    {
			    var newPosX = Telerik.Web.UI.Grid.GetEventPosX(e);
		    }

		    var oldPosY = parseInt(this._rowSelectorArea.style.top);

		    if (this._owner._gridDataDiv)
		    {
			    var newPosY = Telerik.Web.UI.Grid.GetEventPosY(e) -
				    this._owner._gridDataDiv.scrollTop;
		    }
		    else
		    {
			    var newPosY =Telerik.Web.UI.Grid.GetEventPosY(e);
		    }
    		
	        if ((newPosX - oldPosX - 5) > 0)
		        this._rowSelectorArea.style.width = newPosX - oldPosX - 5 + "px";

	        if (this._rowSelectorArea.offsetWidth > this._owner.get_element().offsetWidth)
	        {
		        this._rowSelectorArea.style.width = this._owner.get_element().offsetWidth + "px";
	        }
	        
            
            
           if(newPosY > oldPosY)
            {
		        if ((newPosY - oldPosY - 5) > 0)
			        this._rowSelectorArea.style.height = newPosY - oldPosY - 5 + "px";
		    }
		    else
		    {
		        if ((oldPosY - newPosY - 5) > 0)
		        {			            	            
		            this._rowSelectorArea.style.top = newPosY - 5 + "px";
			        var height = Telerik.Web.UI.Grid.FindPosY(this._firstRow) 
			            -  parseInt(this._rowSelectorArea.style.top) - 5;
			            
			        if(height > 0)
			        {   
			            if (this._owner._gridDataDiv)
			            {
			                if ((this._owner._gridDataDiv.offsetHeight + this._owner._gridDataDiv.offsetTop) > parseInt(this._rowSelectorArea.style.top) + height)
			                {
			                    this._rowSelectorArea.style.height = height + "px";
			                }
			                else    
			                {
			                   var currentHeight = (this._owner._gridDataDiv.offsetHeight + this._owner._gridDataDiv.offsetTop) - parseInt(this._rowSelectorArea.style.top) - 5;
			                   this._rowSelectorArea.style.height = (currentHeight >= 0) ? currentHeight + "px" : 0 + "px";			                  
			                }
			            }
			            else
			            {
			                this._rowSelectorArea.style.height = height + "px";
			            }
			        }              
			        
			     }		    
		    }
                
//		    var maxHeight = (Telerik.Web.UI.Grid.FindPosX(this._owner.get_element()) 
//		                    + this._owner.get_element().offsetHeight) - 
//						    parseInt(this._rowSelectorArea.style.top); 

//		    if (this._rowSelectorArea.offsetHeight > maxHeight)
//		    {		        
////			    if (maxHeight > 0)
////			    {
////				    this._rowSelectorArea.style.height = maxHeight + "px";
////			    }
//		    }
	    }
    },

    _click: function(e) 
    {
        var el = (e.target)? e.target : e.srcElement;
        if(!el.tagName) return;        
        
        if (el.tagName.toLowerCase() == "label" && el.htmlFor) return;

        if(this._owner.ClientSettings.Selecting && this._owner.ClientSettings.Selecting.AllowRowSelect)
        {
            var isClientSelectCheckBox = (el.tagName.toLowerCase() == "input" && 
                                          el.type.toLowerCase() == "checkbox" &&
                                         (el.id && el.id.indexOf("SelectCheckBox") != -1));

	        if((el.tagName.toLowerCase() == "input" && !isClientSelectCheckBox) || 
	            el.tagName.toLowerCase() == "select" || 
	            el.tagName.toLowerCase() == "option" || 
	            el.tagName.toLowerCase() == "button" || 
	            el.tagName.toLowerCase() == "a" || 
	            el.tagName.toLowerCase() == "textarea" ||
	            el.tagName.toLowerCase() == "img"
	            )
	            return;

            if(el.tagName.toLowerCase() != "tr")
                el = Telerik.Web.UI.Grid.GetFirstParentByTagName(el, "tr");
            
            var originalEl = el;
            var found = false;
            while (el && Telerik.Web.UI.Grid.IsChildOf(el, this._owner.get_element()))
            {                
                if (el.id && el.id.split("__").length == 2)
                {
                    found = true;
                    break;
                }
                el = Telerik.Web.UI.Grid.GetFirstParentByTagName(el.parentNode, "tr");
            }
            if (!found) 
                el = originalEl;
            
            if(el && (el.parentNode.parentNode.parentNode == this._owner.get_element() 
            || el.parentNode.parentNode.parentNode == this._owner._gridDataDiv ||
            Array.contains(this._owner.get_detailTables(), $find(el.parentNode.parentNode.id))
            ) && el.id && el.id.split("__").length == 2)
            {
                if(this._owner.get_allowMultiRowSelection())
                {
                    if(e.shiftKey && this._owner._selectedItemsInternal[0])
                    {
                        var selectedRow = $get(this._owner._selectedItemsInternal[0].id);
                        if(selectedRow.rowIndex > el.rowIndex)
                        {
                            for (var i = el.rowIndex; i < selectedRow.rowIndex + 1; i++)
                            {
                                var tr = selectedRow.parentNode.parentNode.rows[i];
                                if(tr.id)
                                {
                                    this._selectRowInternal(tr, e, true, false, true);
                                }
                            }
                        }

                        if(selectedRow.rowIndex < el.rowIndex)
                        {
                            for (var i = selectedRow.rowIndex; i < el.rowIndex + 1; i++)
                            {
                                var tr = selectedRow.parentNode.parentNode.rows[i];
                                if(tr.id)
                                {
                                    this._selectRowInternal(tr, e, true, false, true);
                                }
                            }
                        }
                        return;
                    }
                    
                    this._selectRowInternal(el, e, isClientSelectCheckBox, true, true);
               }
               else
               {
                   this._selectRowInternal(el, e, false, false, true);
               }
            }
        }
        
       if(this._owner.ClientSettings && this._owner.ClientSettings.EnablePostBackOnRowClick && el)
       {
            if(el && el.tagName.toLowerCase() != "tr")
                el = Telerik.Web.UI.Grid.GetFirstParentByTagName(el, "tr");

            if(el && el.id != "" && el.id.split("__").length == 2)
            {
                var itemIndex = el.id.split("__")[1];
                var postBackFunction = this._owner.ClientSettings.PostBackFunction;
                postBackFunction = postBackFunction.replace("{0}", this._owner.UniqueID);
                postBackFunction = postBackFunction.replace("{1}", "RowClick;" + itemIndex);
                setTimeout(function(){
                eval(postBackFunction);
                }, 100);
            }
       }
    },   
    
    _selectRowInternal : function(rowEl, e, isClientSelectCheckBox, toggleSelection, shouldSaveState, selectAllCheckBoxChecked)
    {        
        if (typeof(selectAllCheckBoxChecked) == "undefined")
            selectAllCheckBoxChecked = true;
    
        var itemIndex = rowEl.id.split("__")[1];
        var tableView = $find(rowEl.id.split("__")[0]);   
        
        if(!isClientSelectCheckBox)
        {
            if( !this._owner.AllowMultiRowSelection || 
                (this._owner.AllowMultiRowSelection && !e.ctrlKey))
            {                
                if(this._owner._selectedItemsInternal.length > 0)
                {
                    var i = this._owner._selectedItemsInternal.length - 1;
                    while(i >= 0)
                    {   
                        var currRow = $get(this._owner._selectedItemsInternal[i].id);                     
                        
                        if(currRow == null) {i--;continue};
                        
                        var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(currRow, e);
                        this._owner.raise_rowDeselecting(args);
                        
                        if(args.get_cancel())
                        {
                            i--;
                            continue;
                        }

                        
                        Sys.UI.DomElement.removeCssClass(currRow, tableView._data._selectedItemStyleClass);
                        if(tableView._data._selectedItemStyle)
                        {
                            var currentCssText = currRow.style.cssText.toLowerCase().replace(/ /g, "");
                            var currentCssData = currentCssText.split(";");
                            
                            for(var j = 0; j < currentCssData.length; j++)
                            {
                                if(tableView._data._selectedItemStyle.toLowerCase().indexOf(currentCssData[j]) != -1)
                                {
                                    currentCssData[j] = "";
                                }
                            }

                            currRow.style.cssText = currentCssData.join(";");
                        }
                        this._checkClientSelectColumn(currRow, false);
                        
                        var item = $find(this._owner._selectedItemsInternal[i].id);
                        if(item)
                        {
                            item._selected = false;
                        }

                        Array.remove(this._owner._selectedItemsInternal, this._owner._selectedItemsInternal[i]);
                        Array.remove(this._owner._selectedIndexes, this._owner._selectedIndexes[i]);                     

                        this._owner.raise_rowDeselected(new Telerik.Web.UI.GridDataItemEventArgs(currRow, e));
                        
                        i--;
                    }
                }

                var headerRow = Telerik.Web.UI.Grid.getTableHeaderRow(rowEl.parentNode.parentNode);
                if(headerRow)
                {
                    this._checkClientSelectColumn(headerRow, false);
                }
            }
        }
                

        if(!Array.contains(this._owner._selectedIndexes, itemIndex))
        {
            if (!isClientSelectCheckBox || selectAllCheckBoxChecked)
            {
                var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(rowEl, e);
                this._owner.raise_rowSelecting(args);

                if (args.get_cancel())
                {
                    if(isClientSelectCheckBox)
                    {
                        this._checkClientSelectColumn(rowEl, false);
                        var headerRow = Telerik.Web.UI.Grid.getTableHeaderRow(rowEl.parentNode.parentNode);
                        if(headerRow)
                        {
                            this._checkClientSelectColumn(headerRow, false);
                        }
                   }
			       return false;
			    }

                Sys.UI.DomElement.addCssClass(rowEl, tableView._data._selectedItemStyleClass);
                if(tableView._data._selectedItemStyle != "")
                {
                    rowEl.style.cssText = rowEl.style.cssText + ";" + tableView._data._selectedItemStyle;
                }
                Array.add(this._owner._selectedItemsInternal, {"itemIndex": itemIndex, "id" : rowEl.id});
                Array.add(this._owner._selectedIndexes, itemIndex);
                this._checkClientSelectColumn(rowEl, true);
                
                var item = $find(rowEl.id);
                if(item)
                {
                    item._selected = true;
                }
                
                this._owner.raise_rowSelected(new Telerik.Web.UI.GridDataItemEventArgs(rowEl, e));
            }
        }
        else
        {
            if (toggleSelection || (isClientSelectCheckBox && !selectAllCheckBoxChecked))
            {
                var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(rowEl, e);
                this._owner.raise_rowDeselecting(args);
                
                if(!args.get_cancel())
                {
                    Sys.UI.DomElement.removeCssClass(rowEl, tableView._data._selectedItemStyleClass);
                    if(tableView._data._selectedItemStyle)
                    {
                        var currentCssText = rowEl.style.cssText.toLowerCase().replace(/ /g, "");
                        var currentCssData = currentCssText.split(";");
                        
                        for(var j = 0; j < currentCssData.length; j++)
                        {
                            if(tableView._data._selectedItemStyle.toLowerCase().indexOf(currentCssData[j]) != -1)
                            {
                                currentCssData[j] = "";
                            }
                        }

                        rowEl.style.cssText = currentCssData.join(";");
                    }
                                        
                   
                    for(var i = 0; i < this._owner._selectedItemsInternal.length; i++)
                    {
                        if(this._owner._selectedItemsInternal[i].itemIndex == itemIndex)
                        {
                            var item = $find(this._owner._selectedItemsInternal[i].id);
                            if(item)
                            {
                                item._selected = false;
                            }
                            Array.remove(this._owner._selectedItemsInternal, this._owner._selectedItemsInternal[i]);
                            break;
                        }
                    }
                    
                    for(var i = 0; i < this._owner._selectedIndexes.length; i++)
                    {
                        if(this._owner._selectedIndexes[i] == itemIndex)
                        {
                            Array.remove(this._owner._selectedIndexes, this._owner._selectedIndexes[i]);
                            break;
                        }
                    }
                    
                    this._checkClientSelectColumn(rowEl, false);
                    
                    this._owner.raise_rowDeselected(new Telerik.Web.UI.GridDataItemEventArgs(rowEl, e));
                }
            }
        }
        
        if (shouldSaveState)
            this._owner.updateClientState();
        
        return true;
    },
    
    _checkClientSelectColumn : function(tableRow, shouldSelect)
    {
        var inputs = tableRow.getElementsByTagName("input");
        for(var i = 0; i < inputs.length; i++)
        {
            var input = inputs[i];
            if(input.type.toLowerCase() != "checkbox")
                continue;
            
            if(input.id && input.id.indexOf("SelectCheckBox") != -1)
            {
                input.checked = shouldSelect;
                if ($telerik.isSafari) input.safarichecked = shouldSelect;
            }
        }
    }
};

Telerik.Web.UI.GridSelection.registerClass('Telerik.Web.UI.GridSelection', Sys.Component);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridTableView = function(element)
{
    Telerik.Web.UI.GridTableView.initializeBase(this, [element]);

    this._owner = {};
    this._data = {};

    this._dataItems = [];

    this._columnsInternal = [];
    this._sortExpressions = new Telerik.Web.UI.GridSortExpressions();
    this._filterExpressions = new Telerik.Web.UI.GridFilterExpressions();
    this._firstDataRow = null;

    this._dataSource = null;
    this._virtualItemCount = 0;
};

Telerik.Web.UI.GridTableView.prototype =
{
    initialize: function()
    {
        Telerik.Web.UI.GridTableView.callBaseMethod(this, 'initialize');

        if (this._data._selectedItemStyleClass == "" && this._data._selectedItemStyle == "")
        {
            this._data._selectedItemStyle = "background-color:navy;color:white;";
        }

        if (this._data._renderActiveItemStyleClass == "" && this._data._renderActiveItemStyle == "")
        {
            this._data._renderActiveItemStyle = "background-color:navy;color:white;";
        }

        this.ColGroup = Telerik.Web.UI.Grid.GetTableColGroup(this.get_element());
        if (this.ColGroup)
        {
            this.ColGroup.Cols = Telerik.Web.UI.Grid.GetTableColGroupCols(this.ColGroup);
        }

        this.PageSize = this._data.PageSize;
        this.PageCount = this._data.PageCount;
        this.CurrentPageIndex = this._data.CurrentPageIndex;
        this._virtualItemCount = this._data.VirtualItemCount;


        var isStaticHeaders = (this._owner.ClientSettings.Scrolling &&
            this._owner.ClientSettings.Scrolling.AllowScroll &&
            this._owner.ClientSettings.Scrolling.UseStaticHeaders);

        if ((this.get_element().id.indexOf("_Header") != -1 && isStaticHeaders) ||
            (!isStaticHeaders && this.get_element().id.indexOf("_Header") == -1) ||
            (this.get_element().id.indexOf("_Detail") != -1))
        {
            var headerRow = Telerik.Web.UI.Grid.getTableHeaderRow(this.get_element());

            if (!headerRow)
            {
                var headerTbl = $get(this.get_element().id + "_Header");
                if (headerTbl)
                {
                    headerRow = Telerik.Web.UI.Grid.getTableHeaderRow(headerTbl);
                }
            }

            this.HeaderRow = headerRow;

            var _columnsData = this._data._columnsData;
            for (var i = 0; i < _columnsData.length && headerRow; i++)
            {
                if (!headerRow)
                    continue;

                var data = _columnsData[i];
                var cell = headerRow.cells[i];

                if (!cell)
                    continue;

                this._owner.raise_columnCreating(new Sys.EventArgs());

                var column = $create(
                        Telerik.Web.UI.GridColumn,
                {
                    _owner: this,
                    _data: data
                },
                        null,
                        null,
                        headerRow.cells[i]
                );

                var args = new Sys.EventArgs();
                args.get_column = function()
                {
                    return column;
                }

                Array.add(this._columnsInternal, column);

                this._owner.raise_columnCreated(args);
            }
        }

        if (this._owner.get_events().getHandler("rowCreating") ||
            this._owner.get_events().getHandler("rowCreated"))
        {
            this.get_dataItems();
        }
    },

    dispose: function()
    {
        this._owner.raise_tableDestroying(Sys.EventArgs.Empty);
        
        $clearHandlers(this.get_element());
        
        if(this.get_element().tBodies[0])
            $clearHandlers(this.get_element().tBodies[0]);

        for (var i = 0; i < this._dataItems.length; i++)
        {
            if (this._dataItems[i])
            {
                this._dataItems[i].dispose();
                this._dataItems[i] = null;
            }
        }

        this._dataItems = [];
        if(this.ColGroup != null && this.ColGroup.Cols != null)
        {
            this.ColGroup.Cols = null;        
        }
        
        if(this.ColGroup != null)
        {
            this.ColGroup = null;
        }

        this._element.control = null;
        //this._element = null;

        Telerik.Web.UI.GridTableView.callBaseMethod(this, 'dispose');
    },

    get_columns: function()
    {
        return this._columnsInternal;
    },

    showFilterItem: function()
    {
        this._toggleFilterItemVisibility(true);
    },

    hideFilterItem: function()
    {
        this._toggleFilterItemVisibility(false);
    },
    
    get_isFilterItemVisible : function()
    {
        return this._data.isFilterItemExpanded;
    },
     
    _toggleFilterItemVisibility: function(display)
    {
        var filterRow = this._getTableFilterRow();
        if (filterRow && display != this._data.isFilterItemExpanded)
        {
            if (display)
            {
                filterRow.style["display"] = "";
            }
            else
            {
                filterRow.style["display"] = "none";
            }
            this._data.isFilterItemExpanded = display;

            Array.add(this._owner._expandedFilterItems, this._data.UniqueID + "!");
            this._owner.updateClientState();
        }
    },
    get_tableFilterRow: function()
    {
        return this._getTableFilterRow();
    },
    _getTableFilterRow: function()
    {
        filterRow = null;
        var table = this.get_element();
        if (table.tHead)
        {
            if (!this.HeaderRow)
                return null;

            var startRowIndex = (this.HeaderRow) ? this.HeaderRow.rowIndex : 1;
            for (var i = startRowIndex; i < table.tHead.rows.length; i++)
            {
                if (table.tHead.rows[i] != null)
                {
                    if (table.tHead.rows[i].cells[0] != null)
                    {
                        if (table.tHead.rows[i].cells[0].tagName != null)
                        {
                            if (table.tHead.rows[i].cells[0].tagName.toLowerCase() != "th")
                            {
                                filterRow = table.tHead.rows[i];
                                break;
                            }
                        }
                    }
                }
            }
        }
        else if (this._owner.get_masterTableViewHeader() && this._owner.get_masterTableViewHeader().get_element())
        {
            table = this._owner.get_masterTableViewHeader().get_element();
            for (var i = 1; i < table.rows.length; i++)
            {
                if (table.tHead.rows[i] != null)
                {
                    if (table.tHead.rows[i].cells[0] != null)
                    {
                        if (table.tHead.rows[i].cells[0].tagName != null)
                        {
                            filterRow = table.tHead.rows[i];
                            break;
                        }
                    }
                }
            }
        }

        return filterRow;
    },

    get_clientDataKeyNames: function()
    {
        var clientDataKeyNames = [];
        if (this._data.clientDataKeyNames)
        {
            clientDataKeyNames = this._data.clientDataKeyNames;
        }

        return clientDataKeyNames;
    },

    get_dataItems: function()
    {
        if (this._dataItems.length > 0)
            return this._dataItems;

        var rows = this.get_element().tBodies[0].rows;
        for (var i = 0, l = rows.length; i < l; i++)
        {
            var row = rows[i];

            if (!row.id) continue;

            var gridItem = $find(row.id);

            var data = {};

            this._owner.raise_rowCreating(new Sys.EventArgs());

            var isSelected = false;
            for (var j = 0; j < this._owner._selectedItemsInternal.length; j++)
            {
                if (this._owner._selectedItemsInternal[j].id == row.id)
                {
                    isSelected = true;
                    break;
                }
            }

            if (!gridItem)
            {
                gridItem = $create(
                        Telerik.Web.UI.GridDataItem,
                {
                    _owner: this,
                    _data: data
                },
                        null,
                        null,
                        row
                );
            }
            gridItem._selected = isSelected;

            gridItem._itemIndexHierarchical = row.id.split("__")[1];

            this._owner.raise_rowCreated(new Telerik.Web.UI.GridDataItemEventArgs(row, null));

            this._dataItems[this._dataItems.length] = gridItem;
        }

        return this._dataItems;
    },

    get_owner: function()
    {
        return this._owner;
    },

    get_name: function()
    {
        return this._data.Name;
    },

    get_isItemInserted: function()
    {
        return this._data.IsItemInserted;
    },

    _showNotFrozenColumn: function(index)
    {
        this._hideShowNotFrozenColumn(index, true);
    },

    _hideNotFrozenColumn: function(index)
    {
        this._hideShowNotFrozenColumn(index, false);
    },

    showColumn: function(index)
    {
        var args = new Telerik.Web.UI.GridColumnCancelEventArgs(this.get_columns()[index], null);
        this._owner.raise_columnShowing(args);
        if (args.get_cancel())
        {
            return false;
        }

        this._hideShowColumn(index, true);

        this._owner._showedColumns +=
            this._data.UniqueID
            + ","
            + this.get_columns()[index].get_uniqueName()
            + ";";

        this._owner.updateClientState();

        var args = new Telerik.Web.UI.GridColumnEventArgs(this.get_columns()[index], null);
        this._owner.raise_columnShown(args);
    },

    hideColumn: function(index)
    {
        var args = new Telerik.Web.UI.GridColumnCancelEventArgs(this.get_columns()[index], null);
        this._owner.raise_columnHiding(args);
        if (args.get_cancel())
        {
            return false;
        }

        this._hideShowColumn(index, false);


        this._owner._hidedColumns +=
            this._data.UniqueID
            + ","
            + this.get_columns()[index].get_uniqueName()
            + ";";

        this._owner.updateClientState();

        var args = new Telerik.Web.UI.GridColumnEventArgs(this.get_columns()[index], null); ;
        this._owner.raise_columnHidden(args);
    },

    _hideShowColumn: function(index, display)
    {
        var display = this.get_columns()[index].Display = display;

        if (this != this._owner.get_masterTableViewHeader() /*&& this != this._owner.get_element()*/
            && this != this._owner.get_masterTableViewFooter() && this != this._owner.get_masterTableView())
        {
            if (window.netscape || this._owner.get_masterTableViewHeader())
                this._hideShowCol(this, index, display);

            Telerik.Web.UI.Grid.hideShowCells(this.get_element(), index, display, this.ColGroup.Cols);
            return;
        }

        if (this._owner.get_masterTableViewHeader())
        {
            if (window.netscape || this._owner.get_masterTableViewHeader())
                this._hideShowCol(this._owner.get_masterTableViewHeader(), index, display);

            Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableViewHeader().get_element(), index, display, this._owner.get_masterTableView().ColGroup.Cols);
        }

        if (this._owner.get_masterTableView())
        {
            if (window.netscape || this._owner.get_masterTableViewHeader())
                this._hideShowCol(this._owner.get_masterTableView(), index, display);

            Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableView().get_element(), index, display, this._owner.get_masterTableView().ColGroup.Cols);
        }

        if (this._owner.get_masterTableViewFooter())
        {
            if (window.netscape || this._owner.get_masterTableViewHeader())
                this._hideShowCol(this._owner.get_masterTableViewFooter(), index, display);

            Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableViewFooter().get_element(), index, display, this._owner.get_masterTableViewFooter().ColGroup.Cols);
        }
    },

    _hideShowCol: function(tableView, index, display)
    {
        if (tableView && tableView.ColGroup && tableView.ColGroup.Cols && tableView.ColGroup.Cols[index])
        {
            var currentDisplay = (tableView.ColGroup.Cols[index].style.display == "") ? true : false;
            if (currentDisplay != display)
            {
                tableView.ColGroup.Cols[index].style.display = (display) ? "" : "none";
            }
        }
    },

    _hideShowNotFrozenColumn: function(index, display)
    {

        if (this._owner.get_masterTableViewHeader())
        {
            this._owner.get_masterTableViewHeader().get_columns()[index].FrozenDisplay = display;

            if (!window.netscape && navigator.userAgent.toLowerCase().indexOf("safari") == -1)
            {
                this._hideShowCol(this._owner.get_masterTableViewHeader(), index, display);

                if (navigator.userAgent.toLowerCase().indexOf("msie") != -1 &&
                    navigator.userAgent.toLowerCase().indexOf("6.0") != -1)
                {
                    var selects = this._owner.get_masterTableViewHeader().get_element().getElementsByTagName("select");
                    if (selects.length > 0)
                    {
                        var table = this._owner.get_masterTableViewHeader().get_element();
                        setTimeout(function()
                        {
                            for (var i = 0, l = table.rows.length; i < l; i++)
	                        {
	                            var cell = table.rows[i].cells[index];
	                            Telerik.Web.UI.Grid._hideShowSelect(cell, display);
	                        }
	                     },0);
//                        var thisObject = this;
//                        setTimeout(function()
//                        {
//                            Telerik.Web.UI.Grid.hideShowCells(thisObject._owner.get_masterTableViewHeader().get_element(), index, display, thisObject._owner.get_masterTableViewHeader().ColGroup.Cols);
//                        }, 0);
                    }
                }
            }
            else
            {
                Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableViewHeader().get_element(), index, display, this._owner.get_masterTableViewHeader().ColGroup.Cols);
            }
        }

        if (this._owner.get_masterTableView())
        {

            this._owner.get_masterTableView().get_columns()[index].FrozenDisplay = display;

            if (!window.netscape && navigator.userAgent.toLowerCase().indexOf("safari") == -1)
            {
                this._hideShowCol(this._owner.get_masterTableView(), index, display);

                if (navigator.userAgent.toLowerCase().indexOf("msie") != -1 &&
                    navigator.userAgent.toLowerCase().indexOf("6.0") != -1)
                {
                    var selects = this._owner.get_masterTableView().get_element().getElementsByTagName("select");
                    if (selects.length > 0)
                    {
                        var table = this._owner.get_masterTableView().get_element();
                        setTimeout(function()
                        {
                            for (var i = 0, l = table.rows.length; i < l; i++)
	                        {
	                            var cell = table.rows[i].cells[index];
	                            Telerik.Web.UI.Grid._hideShowSelect(cell, display);
	                        }
	                     },0);
//                        var thisObject = this;
//                        setTimeout(function()
//                        {
//                            Telerik.Web.UI.Grid.hideShowCells(thisObject._owner.get_masterTableView().get_element(), index, display, thisObject._owner.get_masterTableView().ColGroup.Cols);
//                        }, 0);
                    }
                }
            }
            else
            {
                Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableView().get_element(), index, display, this._owner.get_masterTableView().ColGroup.Cols);
            }
        }

        if (this._owner.get_masterTableViewFooter())
        {
            //this._owner.get_masterTableViewFooter().get_columns()[index].FrozenDisplay = display;

            if (!window.netscape && navigator.userAgent.toLowerCase().indexOf("safari") == -1)
            {
                this._hideShowCol(this._owner.get_masterTableViewFooter(), index, display);

                if (navigator.userAgent.toLowerCase().indexOf("msie") != -1 &&
                    navigator.userAgent.toLowerCase().indexOf("6.0") != -1)
                {
                    var selects = this._owner.get_masterTableViewFooter().get_element().getElementsByTagName("select");
                    if (selects.length > 0)
                    {
//                        var thisObject = this;
//                        setTimeout(function()
//                        {
//                            Telerik.Web.UI.Grid.hideShowCells(thisObject._owner.get_masterTableViewFooter().get_element(), index, display, thisObject._owner.get_masterTableViewFooter().ColGroup.Cols);
//                        }, 0);
                        var table = this._owner.get_masterTableViewFooter().get_element();
                        setTimeout(function()
                        {
                            for (var i = 0, l = table.rows.length; i < l; i++)
	                        {
	                            var cell = table.rows[i].cells[index];
	                            Telerik.Web.UI.Grid._hideShowSelect(cell, display);
	                        }
	                     },0);
                    }
                }
            }
            else
            {
                Telerik.Web.UI.Grid.hideShowCells(this._owner.get_masterTableViewFooter().get_element(), index, display, this._owner.get_masterTableViewFooter().ColGroup.Cols);
            }
        }
    },

    hideItem: function(index)
    {
        if (!this._canShowHideItem(index))
            return false;

        var item = null;



        if (this.get_element()
	        && this.get_element().tBodies[0]
	        && this.get_element().tBodies[0].rows[index])
        {
            item = this.get_element().tBodies[0].rows[index];
        }

        var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(item, null);
        this._owner.raise_rowHiding(args);

        if (args.get_cancel())
            return false;

        if (item)
            item.style.display = "none";

        if (item && item.id != "" && item.id.split("__").length == 2)
        {
            var itemIndex = item.id.split("__")[1];
            this._owner._hidedItems +=
                this.get_id()
                + ","
                + itemIndex
                + ";";

            this._owner.updateClientState();
        }

        var args = new Telerik.Web.UI.GridDataItemEventArgs(item, null);
        this._owner.raise_rowHidden(args);
    },

    showItem: function(index)
    {
        if (!this._canShowHideItem(index)) return false;

        var item = null;

        if (this.get_element()
	        && this.get_element().tBodies[0]
	        && this.get_element().tBodies[0].rows[index])
        {
            item = this.get_element().tBodies[0].rows[index];
        }

        var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(item, null);
        this._owner.raise_rowShowing(args);

        if (args.get_cancel())
            return false;

        if (item)
        {
            if (window.netscape)
            {
                item.style.display = "table-row";
            }
            else
            {
                item.style.display = "";
            }
        }

        if (item && item.id != "" && item.id.split("__").length == 2)
        {
            var itemIndex = item.id.split("__")[1];
            this._owner._showedItems +=
                this.get_id()
                + ","
                + itemIndex
                + ";";

            this._owner.updateClientState();
        }

        var args = new Telerik.Web.UI.GridDataItemEventArgs(item, null);
        this._owner.raise_rowShown(args);
    },

    _canShowHideItem: function(index)
    {
        if (isNaN(parseInt(index)))
        {
            var message = "Row index must be of type \"Number\"!";
            alert(message);
            return false;
        }

        if (index < 0)
        {
            var message = "Row index must be non-negative!";
            alert(message);
            return false;
        }

        if (this.get_element()
	        && this.get_element().tBodies[0]
	        && this.get_element().tBodies[0].rows[index]
	        && (index > (this.get_element().tBodies[0].rows[index].length - 1)))
        {
            var message = "Row index must be less than rows count!";
            alert(message);
            return false;
        }

        return true;
    },

    _getFirstDataRow: function()
    {
        if (this._firstDataRow != null)
        {
            return this._firstDataRow;
        }

        if (this._dataItems.length > 0)
        {
            return this._dataItems[0].get_element();
        }

        var rows = this.get_element().tBodies[0].rows;
        for (var i = 0, l = rows.length; i < l; i++)
        {
            var row = rows[i];
            if (row.id != "" && row.id.split("__").length == 2)
            {
                this._firstRow = row;
                break;
            }
        }

        return this._firstRow;
    },

    _getLastDataRow: function()
    {
        var lastRow = null;
        var rows = this.get_element().tBodies[0].rows;
        for (var i = rows.length - 1; i >= 0; i--)
        {
            var row = rows[i];
            if (row.id != "" && row.id.split("__").length == 2)
            {
                lastRow = row;
                break;
            }
        }

        return lastRow;
    },

    _getNextDataRow: function(row)
    {
        var nextRow = null;
        var rows = this.get_element().tBodies[0].rows;
        for (var i = row.sectionRowIndex + 1, l = rows.length; i < l; i++)
        {
            var row = rows[i];
            if (row.id != "" && row.id.split("__").length == 2)
            {
                nextRow = row;
                break;
            }
        }

        return nextRow;
    },

    _getNextNestedDataRow: function(row)
    {
        var nextRow = null;
        var nestedTable = Telerik.Web.UI.Grid.GetNestedTable(row);
        if (nestedTable)
        {
            var rows = nestedTable.tBodies[0].rows;
            for (var i = 0; i < rows.length; i++)
            {
                var row = rows[i];
                if (row.id != "" && row.id.split("__").length == 2)
                {
                    nextRow = row;
                    break;
                }
            }
        }

        return nextRow;
    },

    _getPreviousDataRow: function(row)
    {
        var previousRow = null;
        var rows = this.get_element().tBodies[0].rows;
        for (var i = row.sectionRowIndex - 1; i >= 0; i--)
        {
            var row = rows[i];
            if (row.id != "" && row.id.split("__").length == 2)
            {
                previousRow = row;
                break;
            }
        }

        return previousRow;
    },

    _getPreviousNestedDataRow: function(row)
    {
        var previousRow = null;
        var nestedTable = Telerik.Web.UI.Grid.GetNestedTable(row);
        if (nestedTable)
        {
            var rows = nestedTable.tBodies[0].rows;
            for (var i = row.sectionRowIndex - 1; i >= 0; i--)
            {
                var row = rows[i];
                if (row.id != "" && row.id.split("__").length == 2)
                {
                    previousRow = row;
                    break;
                }
            }
        }

        return previousRow;
    },

    get_parentView: function()
    {
        var parentView = null;
        if (this.get_id() != this._owner.get_masterTableView().get_id())
        {
            parentView = $find(this.get_parentRow().id.split("__")[0]);
        }

        return parentView;
    },

    get_parentRow: function()
    {
        var parentRow = null;
        if (this.get_id() != this._owner.get_masterTableView().get_id())
        {
            parentRow = this.get_element().parentNode.parentNode.previousSibling;
        }

        return parentRow;
    },

    get_selectedItems: function()
    {
        var selectedItems = [];

        for (var i = 0; i < this._owner._selectedItemsInternal.length; i++)
        {
            var itemParentId = this._owner._selectedItemsInternal[i].id.split("__")[0];
            if (itemParentId == this.get_id())
            {
                var item = $find(this._owner._selectedItemsInternal[i].id);

                if (item == null)
                {
                    if ($get(this._owner._selectedItemsInternal[i].id))
                    {
                        item = $create(
                            Telerik.Web.UI.GridDataItem,
                        {
                            _owner: this,
                            _data: this._data,
                            _selected: true
                        },
                            null,
                            null,
                            $get(this._owner._selectedItemsInternal[i].id)
                        );
                        Array.add(selectedItems, item);
                    }
                }
                else
                {
                    if (item && item._owner.get_element().id == this.get_element().id)
                    {
                        Array.add(selectedItems, item);
                    }
                }
            }
        }

        return selectedItems;
    },

    clearSelectedItems: function()
    {
        if (this._owner._selectedItemsInternal.length > 0)
        {
            var i = this._owner._selectedItemsInternal.length - 1;
            while (i >= 0)
            {
                var item = $find(this._owner._selectedItemsInternal[i].id);
                if (item)
                {
                    if (item._owner.get_element().id == this.get_element().id)
                    {
                        item.set_selected(false);
                    }
                }
                else
                {
                    if ($get(this._owner._selectedItemsInternal[i].id).parentNode.parentNode.id
                         == this.get_element().id)
                    {
                        this.deselectItem($get(this._owner._selectedItemsInternal[i].id));
                    }
                }
                i--;
            }
        }
    },

    selectItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);
        if (this._owner._selection && rowElement && rowElement.id)
        {
            if (!this._owner.AllowMultiRowSelection)
            {
                this.clearSelectedItems();
            }
            this._owner._selection._selectRowInternal(rowElement, { "ctrlKey": false }, true, false, true)
        }
    },

    deselectItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);

        if (this._owner._selection && rowElement && rowElement.id)
        {
            this._owner._selection._selectRowInternal(rowElement, { "ctrlKey": false }, true, true, true)
        }
    },

    _getRowByIndexOrItemIndexHierarchical: function(rowElement)
    {
        if (typeof (rowElement) == "number")
        {
            var row = null;

            if (this.get_element().tBodies.length > 0)
            {
                if (this.get_element().tBodies[0].rows[rowElement])
                {
                    row = this.get_element().tBodies[0].rows[rowElement];
                }
                if (row && row.id == "")
                {
                    row = this._getNextDataRow(row);
                }
            }

            rowElement = row
        }

        if (typeof (rowElement) == "string")
        {
            rowElement = $get(this.get_element().id + "__" + rowElement);
        }

        return rowElement;
    },

    reorderColumns: function(columnName1, columnName2)
    {

        if (!this._owner.ClientSettings.AllowColumnsReorder)
            return;

        if (this._owner.ClientSettings.ColumnsReorderMethod != 1)
            return;

        var column1 = this.getColumnByUniqueName(columnName1);
        var column2 = this.getColumnByUniqueName(columnName2);

        if (!column1 || !column2)
            return;

        var row = column1.get_element().parentNode;

        var columnIndex1 = this._getCellIndexByColumnUniqueNameFromTableRowElement(row, columnName1);
        var columnIndex2 = this._getCellIndexByColumnUniqueNameFromTableRowElement(row, columnName2);

        var oldReorderColumnsOnClient = this._owner.ClientSettings.ReorderColumnsOnClient;
        this._owner.ClientSettings.ReorderColumnsOnClient = true;

        var currentReorderMethod = this._owner.ClientSettings.ColumnsReorderMethod;
        this._owner.ClientSettings.ColumnsReorderMethod = 0;
        if (columnIndex2 > columnIndex1)
        {
            var args = new Telerik.Web.UI.GridColumnCancelEventArgs(column1, null);
            this._owner.raise_columnMovingToLeft(args);
            if (args.get_cancel())
                return false;

            while (columnIndex1 < columnIndex2)
            {
                var col1 = this.getColumnUniqueNameByCellIndex(row, columnIndex1 + 1);
                var col2 = this.getColumnUniqueNameByCellIndex(row, columnIndex1);
                this.swapColumns(col1, col2);
                columnIndex1++;
            }

            var args = new Telerik.Web.UI.GridColumnEventArgs(column1, null);
            this._owner.raise_columnMovedToLeft(args);
        }
        else
        {
            var args = new Telerik.Web.UI.GridColumnCancelEventArgs(column1, null);
            this._owner.raise_columnMovingToRight(args);
            if (args.get_cancel())
                return false;


            while (columnIndex2 < columnIndex1)
            {
                var col1 = this.getColumnUniqueNameByCellIndex(row, columnIndex1 - 1);
                var col2 = this.getColumnUniqueNameByCellIndex(row, columnIndex1);
                this.swapColumns(col1, col2);
                columnIndex1--;
            }

            var args = new Telerik.Web.UI.GridColumnEventArgs(column1, null);
            this._owner.raise_columnMovedToRight(args);
        }
        this._owner.ClientSettings.ColumnsReorderMethod = currentReorderMethod;

        this._owner.ClientSettings.ReorderColumnsOnClient = oldReorderColumnsOnClient;

        if (!this._owner.ClientSettings.ReorderColumnsOnClient)
        {
            var postBackFunction = this._owner.ClientSettings.PostBackFunction;
            postBackFunction = postBackFunction.replace("{0}", this._owner.UniqueID);
            eval(postBackFunction);
            return;
        }
    },

    swapColumns: function(columnName1, columnName2)
    {
        var column1 = this.getColumnByUniqueName(columnName1);
        var column2 = this.getColumnByUniqueName(columnName2);

        if (!column1 || !column2)
            return;

        if (!this._owner.ClientSettings.AllowColumnsReorder)
            return;

        if (!column1.get_reorderable() || !column2.get_reorderable())
            return;

        if (!this._owner.ClientSettings.ReorderColumnsOnClient)
        {
            var postBackFunction = this._owner.ClientSettings.PostBackFunction;
            postBackFunction = postBackFunction.replace("{0}", this._owner.UniqueID);
            postBackFunction = postBackFunction.replace("{1}", "ReorderColumns," + this._data.UniqueID + "," + column1.get_uniqueName() + "," + column2.get_uniqueName());
            eval(postBackFunction);
            return;
        }

        if (this._owner.ClientSettings.ColumnsReorderMethod != 0)
            return;


        var index1 = this._getCellIndexByColumnUniqueNameFromTableRowElement(column1.get_element().parentNode, columnName1);
        var index2 = this._getCellIndexByColumnUniqueNameFromTableRowElement(column2.get_element().parentNode, columnName2);

        var args = new Sys.CancelEventArgs();
        args.get_gridSourceColumn = function()
        {
            return column1;
        }
        args.get_gridTargetColumn = function()
        {
            return column2;
        }
        this._owner.raise_columnSwapping(args);
        if (args.get_cancel())
            return false;
                    
        if (this.get_id() && this.get_id().indexOf("Detail") != -1)
        {
            this._reorderColumnsInternal(columnName1, columnName2);
        }

        if (this._owner.get_masterTableViewHeader())
        {
            this._owner.get_masterTableViewHeader()._reorderColumnsInternal(columnName1, columnName2);
        }

        if (this._owner.get_masterTableView())
        {
            this._owner.get_masterTableView()._reorderColumnsInternal(columnName1, columnName2);
        }
        
        if (this._owner.get_masterTableViewFooter())
        {
            var isStaticHeaders = (this._owner.ClientSettings.Scrolling &&
            this._owner.ClientSettings.Scrolling.AllowScroll &&
            this._owner.ClientSettings.Scrolling.UseStaticHeaders);
            
            //debugger;
            if((this.get_id() && this.get_id().indexOf("Detail") == -1) && isStaticHeaders)
            {
                this._owner.get_masterTableViewFooter()._reorderFooterInStaticHeaders(columnName1, columnName2);
            }
            else
            {
                this._owner.get_masterTableViewFooter()._reorderColumnsInternal(columnName1, columnName2);
            }
        }

        
        var cellUniqueName2 = column2.get_element().UniqueName;
        var cellUniqueName1 = column1.get_element().UniqueName;

        column1.get_element().UniqueName = cellUniqueName2;
        column2.get_element().UniqueName = cellUniqueName1;


        column1._data.UniqueName = cellUniqueName2;
        column2._data.UniqueName = cellUniqueName1;

        this.get_columns()[index2] = column2;
        this.get_columns()[index1] = column1;

        var args = new Sys.EventArgs();
        args.get_gridSourceColumn = function()
        {
            return column1;
        }
        args.get_gridTargetColumn = function()
        {
            return column2;
        }
        this._owner.raise_columnSwapped(args);

        var _reorderedColumnsData = this._data.UniqueID + "," + columnName1 + "," + columnName2;
        Array.add(this._owner._reorderedColumns, _reorderedColumnsData);
        this._owner.updateClientState();
    },
    
    _reorderFooterInStaticHeaders: function(columnName1, columnName2)
    {
        for (var i = 0; i < this.get_element().rows.length; i++)
        {
            var row = this.get_element().rows[i];            

            var cell1 = this._getCellByFooterColumnUniqueNameFromTableRowElement(row, columnName1);
            var cell2 = this._getCellByFooterColumnUniqueNameFromTableRowElement(row, columnName2);

            if (!cell1 || !cell2)
                continue;

            this._reorderControls(cell1, cell2);

        }
    },
    
    _getCellByFooterColumnUniqueNameFromTableRowElement: function(rowEl, uniqueName)
    {
        for (var i = 0,j = this.get_owner().get_masterTableView().get_columns().length; i < j; i++)
        {
            if (this.get_owner().get_masterTableView().get_columns()[i].get_element().UniqueName.toUpperCase() == uniqueName.toUpperCase())
            {
                return rowEl.cells[i];
            }
        }

        return null;
    },
    
    _reorderColumnsInternal: function(columnName1, columnName2)
    {
        for (var i = 0; i < this.get_element().rows.length; i++)
        {
            var row = this.get_element().rows[i];

            if (!row.id && row.parentNode.tagName.toLowerCase() == "tbody")
                continue;

            var cell1 = this._getCellByColumnUniqueNameFromTableRowElement(row, columnName1);
            var cell2 = this._getCellByColumnUniqueNameFromTableRowElement(row, columnName2);

            if (!cell1 || !cell2)
                continue;

            this._reorderControls(cell1, cell2);

        }
    },
    
    _reorderControls: function(source, target)
    {
        var container1 = document.createElement("div");
        var container2 = document.createElement("div");
        document.body.appendChild(container1);
        document.body.appendChild(container2);

        this._moveNodes(source, container2);
        this._moveNodes(target, container1);

        source.innerHTML = target.innerHTML = "";

        this._moveNodes(container2, target);
        this._moveNodes(container1, source);

        this._recreateControls(source);
        this._recreateControls(target);
        
        container1.parentNode.removeChild(container1);
        container2.parentNode.removeChild(container2);
    },
    
    _moveNodes: function(source, target) 
    {
        var nodes = source.childNodes;
        while (nodes.length > 0) 
        {
            target.appendChild(nodes[0]);
        }
    },
    
    _recreateControls: function(parent) 
    {
        var nodes = parent.getElementsByTagName("*");
        for (var i = 0, l = nodes.length; i < l; i++) 
        {
            var node = nodes[i];
            if (typeof (node.id) != "undefined" && node.id != "") 
            {
                var control = $find(node.id);
                if (!control) continue;
                control._element = $get(node.id);
            }
        }
    },

    getColumnByUniqueName: function(uniqueName)
    {
        for (var i = 0; i < this.get_columns().length; i++)
        {
            if (this.get_columns()[i].get_element().UniqueName == uniqueName)
                return this.get_columns()[i];
        }

        return null;
    },

    getCellByColumnUniqueName: function(rowObject, uniqueName)
    {
        for (var i = 0; i < this.get_columns().length; i++)
        {
            if (this.get_columns()[i].get_element().UniqueName.toUpperCase() == uniqueName.toUpperCase())
            {
                return rowObject.get_element().cells[i];
            }
        }

        return null;
    },

    _getCellByColumnUniqueNameFromTableRowElement: function(rowEl, uniqueName)
    {
        for (var i = 0; i < this.get_columns().length; i++)
        {
            if (this.get_columns()[i].get_element().UniqueName.toUpperCase() == uniqueName.toUpperCase())
            {
                return rowEl.cells[i];
            }
        }

        return null;
    },

    _getCellIndexByColumnUniqueNameFromTableRowElement: function(rowEl, uniqueName)
    {
        for (var i = 0; i < this.get_columns().length; i++)
        {
            if (this.get_columns()[i].get_element().UniqueName.toUpperCase() == uniqueName.toUpperCase())
            {
                return i;
            }
        }

        return null;
    },

    getColumnUniqueNameByCellIndex: function(rowEl, index)
    {
        for (var i = 0; i < rowEl.cells.length; i++)
        {
            if (rowEl.cells[i].UniqueName && i == index)
            {
                return rowEl.cells[i].UniqueName;
            }
        }

        return null;
    },

    _sliderClientValueChanged: function(labelId, sliderId)
    {
        var label = $get(labelId);
        var slider = $find(sliderId);
        if (label && slider)
        {
            var newPageIndex = slider.get_value();
            this._applyPagerLabelText(label, newPageIndex, this.get_pageCount());
        }
    },

    _applyPagerLabelText: function(labelElement, pageIndex, pageCount)
    {
        var toolTipString = this._owner.ClientSettings.ClientMessages.PagerTooltipFormatString;
        var formatterZero = /\{0[^\}]*\}/g;
        var formatterOne = /\{1[^\}]*\}/g;

        var startIndex = ((pageIndex == 0) ? 1 : pageIndex + 1);
        var endIndex = pageCount;

        toolTipString = toolTipString.replace(formatterZero, startIndex).replace(formatterOne, endIndex);
        labelElement.innerHTML = toolTipString;
    },

    resizeItem: function(index, height, isDataRow)
    {
        if (!this._owner.ClientSettings.Resizing.AllowRowResize)
            return;

        var currentItem = this.get_element().rows[index];

        if (currentItem && currentItem.id != "" && currentItem.id.split("__").length == 2)
        {
            var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(currentItem, null);
            this._owner.raise_rowResizing(args);

            if (args.get_cancel())
            {
                return false;
            }
        }

        var controlLayOut = this.get_element().style.tableLayout;
        this.get_element().style.tableLayout = "";

        var parentTable = this.get_element().parentNode.parentNode.parentNode.parentNode;
        var definedTable = $find(parentTable.id);

        var parentTableLayOut;
        if (definedTable != null)
        {
            parentTableLayOut = definedTable.get_element().style.tableLayout;
            definedTable.get_element().style.tableLayout = "";
        }

        if (!isDataRow)
        {
            if (this.get_element())
            {
                if (this.get_element().rows[index])
                {
                    if (this.get_element().rows[index].cells[0])
                    {
                        this.get_element().rows[index].cells[0].style.height = height + "px";
                        this.get_element().rows[index].style.height = height + "px";
                    }
                }
            }
        }
        else
        {
            if (this.get_element())
            {
                if (this.get_element().tBodies[0])
                {
                    if (this.get_element().tBodies[0].rows[index])
                    {
                        if (this.get_element().tBodies[0].rows[index].cells[0])
                        {
                            this.get_element().tBodies[0].rows[index].cells[0].style.height = height + "px";
                            this.get_element().tBodies[0].rows[index].style.height = height + "px";
                        }
                    }
                }
            }
        }

        this.get_element().style.tableLayout = controlLayOut;

        if (definedTable != null)
        {
            definedTable.get_element().style.tableLayout = parentTableLayOut;
        }

        if (currentItem && currentItem.id != "" && currentItem.id.split("__").length == 2)
        {

            var itemIndex = currentItem.id.split("__")[1];
            this._owner._resizedItems +=
                this.get_id()
                + ","
                + itemIndex
                + ","
                + height + "px"
                + ";";
            this._owner.raise_rowResized(new Telerik.Web.UI.GridDataItemEventArgs(currentItem, null));
        }

        this._owner.updateClientState();
    },

    resizeColumn: function(index, width)
    {
        if (!this._validateResizeColumnParams(index, width))
            return;

        if (typeof (index) == "string")
            index = parseInt(index);

        var args = new Telerik.Web.UI.GridColumnCancelEventArgs(this.get_columns()[index], null);
        this._owner.raise_columnResizing(args);

        if (args.get_cancel())
            return false;

        if (this == this._owner.get_masterTableView() && this._owner.get_masterTableViewHeader())
        {
            this._owner.get_masterTableViewHeader().resizeColumn(index, width);
        }

        var lastWidth = this.get_element().clientWidth;
        var lastGridWidth = this._owner.get_element().clientWidth;

        if (this.HeaderRow)
            var deltaWidth = this.HeaderRow.cells[index].scrollWidth - width;

        if (window.netscape || $telerik.isOpera)
        {
            if (this.HeaderRow)
            {
                if (this.HeaderRow.cells[index])
                {
                    this.HeaderRow.cells[index].style.width = width + "px";
                }
            }

            if (this._owner.get_masterTableViewHeader() && (this.get_id() == this._owner.get_masterTableViewHeader().get_id()))
            {
                var firstDataRow = this._owner.get_masterTableView().get_element().tBodies[0].rows[this._owner.ClientSettings.FirstDataRowClientRowIndex];
                if (firstDataRow)
                {
                    if (firstDataRow.cells[index])
                    {
                        firstDataRow.cells[index].style.width = width + "px";
                    }
                }


                if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().get_element())
                {
                    if (this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0] &&
		                this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[index])
                    {
                        if (width > 0)
                        {
                            this._owner.get_masterTableViewFooter().get_element().tBodies[0].rows[0].cells[index].style.width = width + "px";
                        }
                    }
                }
            }
        }

        if (this.ColGroup)
        {
            if (this.ColGroup.Cols[index])
            {
                if (width > 0)
                {
                    this.ColGroup.Cols[index].width = width + "px";
                }
            }
        }

        if (this._owner.get_masterTableViewHeader()
		    && (this.get_id() == this._owner.get_masterTableViewHeader().get_id()))
        {
            if (this._owner.get_masterTableView().ColGroup)
            {
                if (this._owner.get_masterTableView().ColGroup.Cols[index])
                {
                    if (width > 0)
                    {
                        this._owner.get_masterTableView().ColGroup.Cols[index].width = width + "px";
                    }
                }
            }

            if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().ColGroup)
            {
                if (this._owner.get_masterTableViewFooter().ColGroup.Cols[index])
                {
                    if (width > 0)
                    {
                        this._owner.get_masterTableViewFooter().ColGroup.Cols[index].width = width + "px";
                    }
                }
            }
        }



        if (width.toString().indexOf("px") != -1)
        {
            width = width.replace("px", "");
        }

        if (width.toString().indexOf("%") == -1)
        {
            width = width + "px";
        }

        this._owner._resizedColumns +=
            this._data.UniqueID
            + ","
            + this.get_columns()[index].get_uniqueName()
            + ","
            + width
            + ";";

        this._owner.updateClientState();

        if (this._owner.get_masterTableViewHeader())
            this._owner.ClientSettings.Resizing.ResizeGridOnColumnResize = true;


        if (this._owner.ClientSettings.Resizing.ResizeGridOnColumnResize)
            this._resizeGridOnColumnResize(index, deltaWidth);
        else
            this._noResizeGridOnColumnResize(lastWidth, index, lastGridWidth);


        if (this._owner.GroupPanelObject && this._owner.GroupPanelObject.Items.length > 0 && navigator.userAgent.toLowerCase().indexOf("msie") != -1)
        {
            if (this._owner.get_masterTableView() && this._owner.get_masterTableViewHeader())
            {
                this._owner.get_masterTableView().get_element().style.width = this._owner.get_masterTableViewHeader().get_element().offsetWidth + "px";
            }
        }

        var args = new Telerik.Web.UI.GridColumnEventArgs(this.get_columns()[index], null);
        this._owner.raise_columnResized(args);

        if (window.netscape)
        {
            this.get_element().style.cssText = this.get_element().style.cssText;
        }
    },

    _resizeGridOnColumnResize: function(index, deltaWidth)
    {
        var _controlWidth;
        var _offsetWidth;
        var _offsetHeight;

        if (this._owner.get_masterTableViewHeader() && (this.get_id() == this._owner.get_masterTableViewHeader().get_id()))
        {
            for (var i = 0; i < this.ColGroup.Cols.length; i++)
            {
                if (i != index && this.ColGroup.Cols[i].width == "")
                {
                    this.ColGroup.Cols[i].width = this.HeaderRow.cells[i].scrollWidth + "px";
                    this._owner.get_masterTableView().ColGroup.Cols[i].width = this.ColGroup.Cols[i].width;
                    if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().ColGroup)
                    {
                        this._owner.get_masterTableViewFooter().ColGroup.Cols[i].width = this.ColGroup.Cols[i].width;
                    }
                }
            }

            this.get_element().style.width = (this.get_element().offsetWidth - deltaWidth) + "px";
            this._owner.get_masterTableView().get_element().style.width = this.get_element().style.width;

            if (this._owner.get_masterTableViewFooter() && this._owner.get_masterTableViewFooter().get_element())
            {
                this._owner.get_masterTableViewFooter().get_element().style.width = this.get_element().style.width;
            }

            var controlWidth = (this.get_element().scrollWidth > this.get_element().offsetWidth) ? this.get_element().scrollWidth : this.get_element().offsetWidth;
            var scrollWidth = this._owner._gridDataDiv.offsetWidth;

            _controlWidth = controlWidth + "px";
            _offsetWidth = scrollWidth + "px";
            _offsetHeight = this._owner.get_element().offsetHeight + "px";
        }
        else
        {
            if (window.netscape || $telerik.isOpera)
            {
                this.get_element().style.width = (this.get_element().offsetWidth - deltaWidth) + "px";
                this._owner.get_element().style.width = this.get_element().style.width;
            }
            var controlWidth = (this.get_element().scrollWidth > this.get_element().offsetWidth) ? this.get_element().scrollWidth : this.get_element().offsetWidth;

            _controlWidth = controlWidth + "px";
            _offsetWidth = this._owner.get_element().offsetWidth + "px";
            _offsetHeight = this._owner.get_element().offsetHeight + "px";
        }

        this._owner._resizedControl +=
            this._data.UniqueID
            + ","
            + _controlWidth
            + ","
            + _offsetWidth
            + ","
            + _offsetHeight
            + ";";

        this._owner.updateClientState();
    },

    _noResizeGridOnColumnResize: function(lastWidth, index, lastGridWidth)
    {
        var delta = (this.get_element().offsetWidth - lastGridWidth) / this.ColGroup.Cols.length;
        var widths = "";
        for (var i = index + 1; i < this.ColGroup.Cols.length; i++)
        {
            var newColWidth = 0;
            if (this.ColGroup.Cols[i].width != "")
            {
                newColWidth = parseInt(this.ColGroup.Cols[i].width) - delta;
            }
            if (this.HeaderRow)
            {
                newColWidth = this.HeaderRow.cells[i].scrollWidth - delta;
            }

            //this.ColGroup.Cols[i].width	= newColWidth + "px";
            this.ColGroup.Cols[i].width = "";
            if (this._owner.get_masterTableViewHeader() && this.get_id() == this._owner.get_masterTableViewHeader().get_id())
            {
                this._owner.get_masterTableView().ColGroup.Cols[i].width = "";
            }

            if (this._owner.get_masterTableViewFooter())
            {
                this._owner.get_masterTableViewFooter().ColGroup.Cols[i].width = "";
            }

        }
        if (lastGridWidth > 0)
        {
            this._owner.get_element().style.width = lastGridWidth + "px";
        }
        this.get_element().style.width = lastWidth + "px";

        if (this._owner.get_masterTableViewHeader() && this.get_id() == this._owner.get_masterTableViewHeader().get_id())
        {
            this._owner.get_masterTableView().get_element().style.width = this.get_element().style.width;
        }

        if (this._owner.get_masterTableViewFooter())
        {
            this._owner.get_masterTableViewFooter().get_element().style.width = this.get_element().style.width;
        }
    },

    _validateResizeColumnParams: function(index, width)
    {
        if (isNaN(parseInt(index)))
        {
            var message = "Column index must be of type \"Number\"!";
            alert(message);
            return false;
        }

        if (isNaN(parseInt(width)))
        {
            var message = "Column width must be of type \"Number\"!";
            alert(message);
            return false;
        }

        if (index < 0)
        {
            var message = "Column index must be non-negative!";
            alert(message);
            return false;
        }

        if (width < 0)
        {
            var message = "Column width must be non-negative!";
            alert(message);
            return false;
        }

        if (index > (this.get_columns().length - 1))
        {
            var message = "Column index must be less than columns count!";
            alert(message);
            return false;
        }

        if (!this._owner.ClientSettings.Resizing.AllowColumnResize)
            return false;

        if (!this.get_columns())
            return false;

        if (!this.get_columns()[index].get_resizable())
            return false;

        return true;
    },


    get_pageCount: function()
    {
        return this.PageCount;
    },

    get_pageSize: function()
    {
        return this.PageSize;
    },
    set_pageSize: function(value)
    {
        if (this.PageSize != value)
        {
            this.PageSize = value;

            this.fireCommand("PageSize", value);
        }
    },

    get_virtualItemCount: function()
    {
        return this._virtualItemCount;
    },
    set_virtualItemCount: function(value)
    {
        if (this._virtualItemCount != value)
        {
            this._virtualItemCount = value;

            this.set_currentPageIndex(0);

            this.PageCount = Math.ceil(value / this.get_pageSize());

            var id2 = String.format("{0}PCN", this.get_id());
            var id5 = String.format("{0}DSC", this.get_id());
            var id4 = String.format("{0}LIP", this.get_id());

            if ($get(id2))
            {
                $get(id2).innerHTML = this.PageCount;
            }

            if ($get(id5))
            {
                $get(id5).innerHTML = value;
            }

            if ($get(id4) && $get(id5))
            {
                var value1 = parseInt($get(id4).innerHTML);
                var value2 = parseInt($get(id5).innerHTML);
                if (value1 > value2)
                {
                    $get(id4).innerHTML = value2;
                }
            }

            if (this._data.sliderClientID != "")
            {
                var slider = $find(this._data.sliderClientID);
                if (slider != null)
                {
                    slider.set_maximumValue(this.PageCount - 1);
                    this._applyPagerLabelText($get(this._data.sliderLabelClientID), 0, this.get_pageCount());
                }
            }
        }
    },

    get_currentPageIndex: function()
    {
        return this.CurrentPageIndex;
    },

    set_currentPageIndex: function(value, doNotCallCommand)
    {
        if (this.CurrentPageIndex != value)
        {
            this.CurrentPageIndex = value;

            var id1 = String.format("{0}CPI", this.get_id());
            var id2 = String.format("{0}PCN", this.get_id());
            var id3 = String.format("{0}FIP", this.get_id());
            var id4 = String.format("{0}LIP", this.get_id());
            var id5 = String.format("{0}DSC", this.get_id());

            if ($get(id1))
            {
                $get(id1).innerHTML = value + 1;
            }

            if ($get(id3))
            {
                $get(id3).innerHTML = (value + 1) * this.get_pageSize() - this.get_pageSize() + 1;
            }

            var totalItems = 0;
            if ($get(id5))
            {
                totalItems = parseInt($get(id5).innerHTML);
            }

            if ($get(id4))
            {
                var newValue = (value + 1) * this.get_pageSize();
                if (newValue > totalItems)
                {
                    newValue = totalItems;
                }
                $get(id4).innerHTML = newValue;
            }

            if (!doNotCallCommand)
                this.fireCommand("Page", value);
        }
    },

    get_dataSource: function()
    {
        return this._dataSource;
    },
    set_dataSource: function(value)
    {
        if (this._dataSource != value)
        {
            this._dataSource = value;
        }
    },

    get_allowMultiColumnSorting: function()
    {
        return this._data.AllowMultiColumnSorting;
    },
    set_allowMultiColumnSorting: function(value)
    {
        if (this._data.AllowMultiColumnSorting != value)
        {
            this._data.AllowMultiColumnSorting = value;
        }
    },

    dataBind: function()
    {
        var dataItems = this.get_dataItems();
        var columns = this.get_columns();

        var tableElement = ($telerik.isOpera) ? this.get_element() : this.get_element().tBodies[0];
        /*
        if (this._dataSource.length < dataItems.length || tableElement.rows.length == 1)
        {
        var i = 0;
        while (tableElement.rows.length > 0)
        {
        //this._owner._destroyTree(tableElement.rows[i]);
                
                
        tableElement.deleteRow(-1);

                if (dataItems[i])
        {
        dataItems[i].dispose();
        }

                i++;
        }

            Array.clear(this._dataItems);
        }
        */

        if (this._dataSource.length < dataItems.length || tableElement.rows.length == 1)
        {
            for (var i = 0, l1 = dataItems.length; i < l1; i++)
            {
                dataItems[i].get_element().style.display = "none";
            }
        }

        for (var i = 0, l1 = this._dataSource.length; i < l1; i++)
        {           
            var dataItem = dataItems[i];

            if (dataItem == null)
            {
                var newRow = tableElement.insertRow(-1);
                for (var j = 0, l2 = columns.length; j < l2; j++)
                {
                    newRow.insertCell(-1);
                }

                var lastId;
                if (dataItems.length > 0)
                {
                    var lastDataItem = dataItems[dataItems.length - 1];
                    lastId = lastDataItem.get_id();
                }
                else
                {
                    lastId = String.format("{0}__{1}", this.get_id(), 0);
                    newRow.className = String.format("GridRow_{0}", this._owner.Skin);
                }

                if (i == 1)
                {
                    newRow.className = String.format("GridAltRow_{0}", this._owner.Skin);
                }

                var itemIndexHierarchical = parseInt(lastId.split("__")[1]) + 1;

                newRow.id = String.format("{0}__{1}", lastId.split("__")[0], itemIndexHierarchical);

                if (dataItems[dataItems.length - 2])
                {
                    newRow.className = dataItems[dataItems.length - 2].get_element().className;
                }

                dataItem = $create(
                    Telerik.Web.UI.GridDataItem,
                {
                    _owner: this,
                    _data: {},
                    _itemIndexHierarchical : itemIndexHierarchical
                },
                    null,
                    null,
                    newRow
                    );

                Array.add(this._dataItems, dataItem);

                //this._owner._clientKeyValues[i] = { "EmployeeID": this._dataSource[i].EmployeeID };
            }

            if (dataItem.get_element().style.display == "none")
            {
                dataItem.get_element().style.display = (window.netscape) ? "table-row" : "";
            }

            var isInEditMode = Array.contains(this._owner._editIndexes, dataItem._itemIndexHierarchical);       
            
            if(this.get_owner()._clientKeyValues && this._data && this._data.clientDataKeyNames)
            {                
                for (var k=0, len = this._data.clientDataKeyNames.length; k < len; k++)
                {
                    var clientDataKeyName = this._data.clientDataKeyNames[k];
                    var clientDataKeyValue = this._dataSource[i][clientDataKeyName];
                    if(clientDataKeyValue)
                    {
                        if(this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical])
                        {
                            this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical][clientDataKeyName] = clientDataKeyValue;
                        }
                        else
                        {
                            if(this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical] != null)
                            {
                                var obj = this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical];
                                obj[clientDataKeyName] = clientDataKeyValue;
                                this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical] = obj;                            
                            }
                            else
                            {
                                var obj = new Object();
                                obj[clientDataKeyName] = clientDataKeyValue;
                                this.get_owner()._clientKeyValues[dataItem._itemIndexHierarchical] = obj;                            
                            }
                        }
                    }
                }
            }
            
            for (var j = 0, l2 = columns.length; j < l2; j++)
            {
                var uniqueName = columns[j].get_uniqueName();
                var cell = this.getCellByColumnUniqueName(dataItem, uniqueName);

                if (!cell) continue;

                var value = this._dataSource[i][uniqueName];

                if (value == null)
                {
                    value = "";
                }
                
                if (typeof (value) != "undefined")
                {
                    if (columns[j]._data.ColumnType == "GridCheckBoxColumn")
                    {
                        var inputs = cell.getElementsByTagName("input");
                        if (inputs.length > 0 && inputs[0].type == "checkbox")
                        {
                            inputs[0].checked = value;
                        }
                    }
                    else if (   columns[j]._data.ColumnType == "GridTemplateColumn" ||
                                columns[j]._data.ColumnType == "GridButtonColumn" ||
                                columns[j]._data.ColumnType == "GridEditCommandColumn" ||
                                columns[j]._data.ColumnType == "GridExpandColumn" ||
                                columns[j]._data.ColumnType == "GridClientDeleteColumn" ||
                                columns[j]._data.ColumnType == "GridClientSelectColumn" ||
                                columns[j]._data.ColumnType == "GridGroupSplitterColumn")
                    {

                    }
                    else if (columns[j]._data.ColumnType == "GridCalculatedColumn")
                    {
                        var cellValue = "";
                        if (columns[j]._data.DataFormatString != "")
                        {
                            var newValue = String.format(columns[j]._data.Expression, columns[j]._data.DataFields)
                            cellValue = String.localeFormat(columns[j]._data.DataFormatString, eval(newValue));
                        }

                        cell.innerHTML = (cellValue != "") ? cellValue : "&nbsp;";
                    }
                    else
                    {
                        if (!isInEditMode)
                        {
                            if (typeof (columns[j]._data.DataFormatString) != "undefined" && columns[j]._data.DataFormatString != "")
                            {
                                var cellValue = String.localeFormat(columns[j]._data.DataFormatString, value);

                                cell.innerHTML = (cellValue != "") ? cellValue : "&nbsp;";
                            }
                            else
                            {
                                cell.innerHTML = (value != "") ? value : "&nbsp;";
                            }
                        }
                        else
                        {
                            if (columns[j]._data.ColumnType == "GridBoundColumn")
                            {
                                var inputs = cell.getElementsByTagName("input");
                                if (inputs.length > 0)
                                {
                                    var newValue = (columns[j]._data.DataFormatString != "") ? String.localeFormat(columns[j]._data.DataFormatString, value) : value;
                                    inputs[0].value = newValue;
                                }
                            }

                            if (columns[j]._data.ColumnType == "GridDateTimeColumn")
                            {
                                var inputs = cell.getElementsByTagName("input");
                                for (var k = 0; k < inputs.length; k++)
                                {
                                    var dateInput = $find(inputs[k].id);
                                    if (dateInput != null)
                                    {
                                        dateInput.set_selectedDate(value);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {

                }
            } 
            
            var args = new Object();
            var rowData = this._dataSource[i];
            args.get_dataItem = function()
            {
                return rowData;
            }
            args.get_item = function()
            {
                return dataItem;
            }
            
            dataItem._dataItem = rowData;

            this._owner.raise_rowDataBound(args);
        }
                
        for (var i = 0, l2 = columns.length; i < l2; i++)
        {
            var isVisible = false;
            
            if(columns[i].get_visible() && columns[i].Display == null && 
                (columns[i]._data.Display == null || columns[i]._data.Display)
              )
            {
                isVisible = true;
            }  
                         
            if (!isVisible)               
                this._hideShowColumn(i, isVisible);
        }
    },


    expandItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);

        return this._expandRow(rowElement);
    },

    _expandRow: function(rowElement)
    {
        if (!this._owner.ClientSettings.AllowExpandCollapse)
            return false;

        var dataRow = rowElement;
        var itemIndex = dataRow.id.split("__")[1];

        var nestedViewRow = dataRow.parentNode.rows[dataRow.sectionRowIndex + 1];

        if (nestedViewRow && nestedViewRow.style.display == "none")
        {
            var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(dataRow, null);
            args.get_nestedViewItem = function()
            {
                return nestedViewRow;
            }

            this._owner.raise_hierarchyExpanding(args);
            if (args.get_cancel())
            {
                return false;
            }

            var item = $find(dataRow.id);
            if (item)
            {
                item._expanded = false;
            }

            nestedViewRow.style.display = (window.netscape) ? "table-row" : "";

            var args = new Telerik.Web.UI.GridDataItemEventArgs(dataRow, null);
            args.get_nestedViewItem = function()
            {
                return nestedViewRow;
            }

            this._owner.raise_hierarchyExpanded(args);
            
            Array.add(this._owner._expandedItems, itemIndex);
            this._owner.updateClientState();            
        }
        
            
        if (this.get_element().parentNode.parentNode.tagName.toLowerCase() == "tr")
        {
            if (this.get_id() != this._owner._masterClientID)
            {
                var parentNestedViewEl = this.get_element().parentNode.parentNode.parentNode.parentNode;
                var parentNestedView = $find(parentNestedViewEl.id);
                var parentDataRow = parentNestedViewEl.rows[this.get_element().parentNode.parentNode.rowIndex - 1]
                if (parentDataRow)
                {
                    parentNestedView._expandRow(parentDataRow);
                }
            }
        }

        return true;
    },

    collapseItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);

        return this._collapseRow(rowElement);
    },

    _collapseRow: function(rowElement)
    {
        if (!this._owner.ClientSettings.AllowExpandCollapse)
            return false;

        var dataRow = rowElement;
        var itemIndex = dataRow.id.split("__")[1];

        var nestedViewRow = dataRow.parentNode.rows[dataRow.sectionRowIndex + 1];

        if (nestedViewRow && nestedViewRow.style.display != "none")
        {
            var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(dataRow, null);
            args.get_nestedViewItem = function()
            {
                return nestedViewRow;
            }

            this._owner.raise_hierarchyCollapsing(args);
            if (args.get_cancel())
            {
                return false;
            }

            var item = $find(dataRow.id);
            if (item)
            {
                item._expanded = false;
            }

            nestedViewRow.style.display = "none";

            var args = new Telerik.Web.UI.GridDataItemEventArgs(dataRow, null);
            args.get_nestedViewItem = function()
            {
                return nestedViewRow;
            }

            this._owner.raise_hierarchyCollapsed(args);            
            
            Array.add(this._owner._expandedItems, itemIndex);
            this._owner.updateClientState();
        }

        return true;
    },

    _toggleExpand: function(e)
    {
        var expandCollapseButton = Telerik.Web.UI.Grid.GetCurrentElement(e);

        if (!this._owner.ClientSettings.AllowExpandCollapse)
            return;

        var dataRow = expandCollapseButton.parentNode.parentNode;
        var nestedViewRow = dataRow.parentNode.rows[dataRow.sectionRowIndex + 1];

        if (nestedViewRow.style.display != "none")
        {
            if (!this._collapseRow(dataRow))
                return false;
            
            if(expandCollapseButton.title == this._owner._hierarchySettings.CollapseTooltip)
            {
                expandCollapseButton.title = this._owner._hierarchySettings.ExpandTooltip;
            }
            
            if (expandCollapseButton.src)
            {
                var column = this.get_columns()[expandCollapseButton.parentNode.cellIndex];
                if (column)
                {
                    expandCollapseButton.src = column._data.ExpandImageUrl;
                }
            }
            else
            {
                var column = this.get_columns()[expandCollapseButton.parentNode.cellIndex];
                if (column)
                {
                    expandCollapseButton.className = "rgExpand";
                }
            }
        }
        else
        {
            if (!this._expandRow(dataRow))
                return false;

            if(expandCollapseButton.title == this._owner._hierarchySettings.ExpandTooltip)
            {
                expandCollapseButton.title = this._owner._hierarchySettings.CollapseTooltip;
            }

            if (expandCollapseButton.src)
            {
                var column = this.get_columns()[expandCollapseButton.parentNode.cellIndex];
                if (column)
                {
                    expandCollapseButton.src = column._data.CollapseImageUrl;
                }
            }
            else
            {
                var column = this.get_columns()[expandCollapseButton.parentNode.cellIndex];
                if (column)
                {
                    expandCollapseButton.className = "rgCollapse";
                }
            }
        }
    },

    _toggleGroupsExpand: function(sender, e)
    {
        var expandCollapseButton = sender;

        if (!this._owner.ClientSettings.AllowGroupExpandCollapse)
            return;

        var tableViewClientID = expandCollapseButton.id.split("__")[0];

        var tableView = $find(tableViewClientID);
        var serverRowIndex = expandCollapseButton.id.split("__")[1];
        var groupLevel = expandCollapseButton.id.split("__")[2];

        var cellIndex = expandCollapseButton.parentNode.cellIndex;
        var rowIndex = expandCollapseButton.parentNode.parentNode.sectionRowIndex;
        var table = tableView.get_element().tBodies[0];

        var rowDisplay = (window.netscape) ? "table-row" : "";
        var display = "";

        var column = this.get_columns()[cellIndex];

        var args = new Sys.CancelEventArgs();

        if (expandCollapseButton.src)
        {
            if (expandCollapseButton.src.indexOf(column._data.ExpandImageUrl) == -1)
            {
                this._owner.raise_groupCollapsing(args);
            }
            else
            {
                this._owner.raise_groupExpanding(args);
            }
        }
        else
        {
            if (expandCollapseButton.className.indexOf("rgExpand") == -1)
            {
                this._owner.raise_groupCollapsing(args);
            }
            else
            {
                this._owner.raise_groupExpanding(args);
            }
        }

        if (args.get_cancel())
        {
            return false;
        }


        if (column)
        {
            if (expandCollapseButton.src)
            {
                if (expandCollapseButton.src.indexOf(column._data.ExpandImageUrl) != -1)
                {
                    expandCollapseButton.src = column._data.CollapseImageUrl;
                    expandCollapseButton.title = tableView._owner._groupingSettings.CollapseTooltip;
                    display = rowDisplay;
                    //firstGroupHeader.set_expanded(true);
                }
                else
                {
                    expandCollapseButton.src = column._data.ExpandImageUrl;
                    expandCollapseButton.title = tableView._owner._groupingSettings.ExpandTooltip;
                    display = "none";
                    //firstGroupHeader.set_expanded(false);
                }
            }
            else
            {
                if (expandCollapseButton.className.indexOf("rgExpand") != -1)
                {
                    expandCollapseButton.className = "rgCollapse";
                    expandCollapseButton.title = tableView._owner._groupingSettings.CollapseTooltip;
                    display = rowDisplay;
                    //firstGroupHeader.set_expanded(true);
                }
                else
                {
                    expandCollapseButton.className = "rgExpand";
                    expandCollapseButton.title = tableView._owner._groupingSettings.ExpandTooltip;
                    display = "none";
                    //firstGroupHeader.set_expanded(false);
                }
            }
        }

        var nestedGroupLevel = groupLevel;

        for (var i = rowIndex + 1; i < table.rows.length; i++)
        {
            var row = table.rows[i];

            var btn = this._getGroupExpandButton(row);
            if (!btn)
            {
                if (nestedGroupLevel == groupLevel)
                    row.style.display = display;
                //row.style.display = (row.style.display == "none")? rowDisplay : "none";
            }
            else
            {
                nestedGroupLevel = btn.id.split("__")[2]
                if (nestedGroupLevel == groupLevel || (parseInt(nestedGroupLevel) < parseInt(groupLevel)))
                {
                    break;
                }
                else
                {
                    if (parseInt(nestedGroupLevel) - parseInt(groupLevel) == 1)
                    {
                        if (btn.src == expandCollapseButton.src || (expandCollapseButton.className == btn.className))
                        {
                            if (display == "none")
                            {
                                if (expandCollapseButton.src)
                                {
                                    btn.src = expandCollapseButton.src;
                                }
                                else
                                {
                                    btn.className = "rgCollapse";
                                }
                            }

                            this._toggleGroupsExpand(btn, e);
                        }

                        row.style.display = display;
                        //row.style.display = (row.style.display == "none")? rowDisplay : "none";
                    }
                }
            }
        }

        Array.add(this._owner._expandedGroupItems, tableView._data.UniqueID + "!" + serverRowIndex);
        this._owner.updateClientState();

        var args = new Sys.EventArgs();
        if (expandCollapseButton.src)
        {
            if (expandCollapseButton.src.indexOf(column._data.ExpandImageUrl) == -1)
            {
                this._owner.raise_groupExpanded(args);
            }
            else
            {
                this._owner.raise_groupCollapsed(args);
            }
        }
        else
        {
            if (expandCollapseButton.className.indexOf("rgExpand") == -1)
            {
                this._owner.raise_groupExpanded(args);
            }
            else
            {
                this._owner.raise_groupCollapsed(args);
            }
        }
    },

    _getGroupExpandButton: function(row)
    {
        var button = null;

        var images = row.getElementsByTagName("img");
        for (var i = 0, l = images.length; i < l; i++)
        {
            var img = images[i];
            if (img.onclick != null && img.onclick.toString().indexOf("_toggleGroupsExpand") != -1)
            {
                button = img;
                break;
            }
        }

        var inputs = row.getElementsByTagName("input");
        for (var i = 0, l = inputs.length; i < l; i++)
        {
            var input = inputs[i];
            if (input.onclick != null && input.onclick.toString().indexOf("_toggleGroupsExpand") != -1)
            {
                button = input;
                break;
            }
        }

        return button;
    },

    editItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);
        var itemIndex = rowElement.id.split("__")[1];
        if (!this.fireCommand("Edit", itemIndex))
            return false;
    },

    updateItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);
        var itemIndex = rowElement.id.split("__")[1];
        if (!this.fireCommand("Update", itemIndex))
            return false;
    },

    deleteItem: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);
        var itemIndex = rowElement.id.split("__")[1];
        if (!this.fireCommand("Delete", itemIndex))
            return false;
    },

    rebind: function()
    {
        if (!this.fireCommand("RebindGrid", ""))
            return false;
    },

    insertItem: function()
    {
        if (!this.fireCommand("PerformInsert", ""))
            return false;
    },

    showInsertItem: function()
    {
        if (!this.fireCommand("InitInsert", ""))
            return false;
    },

    cancelInsert: function()
    {
        if (!this.fireCommand("CancelInsert", ""))
            return false;
    },

    sort: function(expression)
    {
        var sortExpression = new Telerik.Web.UI.GridSortExpression();
        var fieldName = expression.split(" ")[0];

        if (expression.toUpperCase().indexOf(" ASC") != -1)
        {
            sortExpression.set_sortOrder(Telerik.Web.UI.GridSortOrder.Ascending);
        }
        else if (expression.toUpperCase().indexOf(" DESC") != -1)
        {
            sortExpression.set_sortOrder(Telerik.Web.UI.GridSortOrder.Descending);
        }
        else
        {
            sortExpression.set_sortOrder(Telerik.Web.UI.GridSortOrder.Ascending);

            var id1 = String.format("{0}__{1}__SortAsc", this.get_id(), fieldName);
            var id2 = String.format("{0}__{1}__SortDesc", this.get_id(), fieldName);
            if ($get(id1))
            {
                $get(id1).style.display = "";
            }
            if ($get(id2))
            {
                $get(id2).style.display = "none";
            }
        }

        sortExpression.set_fieldName(fieldName);

        var foundExpression = this._sortExpressions.find(sortExpression.get_fieldName());
        if (foundExpression != null)
        {
            var newOrder = Telerik.Web.UI.GridSortOrder.None;

            if (foundExpression.get_sortOrder() == 0)
            {
                newOrder = Telerik.Web.UI.GridSortOrder.Ascending;
            }
            else if (foundExpression.get_sortOrder() == 1)
            {
                newOrder = Telerik.Web.UI.GridSortOrder.Descending;
                var id1 = String.format("{0}__{1}__SortAsc", this.get_id(), foundExpression.get_fieldName());
                var id2 = String.format("{0}__{1}__SortDesc", this.get_id(), foundExpression.get_fieldName());
                if ($get(id1))
                {
                    $get(id1).style.display = "none";
                }
                if ($get(id2))
                {
                    $get(id2).style.display = "";
                }
            }
            else if (foundExpression.get_sortOrder() == 2)
            {
                this._sortExpressions.remove(foundExpression);
                var id1 = String.format("{0}__{1}__SortAsc", this.get_id(), foundExpression.get_fieldName());
                var id2 = String.format("{0}__{1}__SortDesc", this.get_id(), foundExpression.get_fieldName());
                if ($get(id1))
                {
                    $get(id1).style.display = "none";
                }
                if ($get(id2))
                {
                    $get(id2).style.display = "none";
                }
            }

            foundExpression.set_sortOrder(newOrder);
        }

        if (foundExpression == null)
        {
            if (!this.get_allowMultiColumnSorting())
            {
                for (var i = 0; i < this._sortExpressions._array.length; i++)
                {
                    var id1 = String.format("{0}__{1}__SortAsc", this.get_id(), this._sortExpressions._array[i].get_fieldName());
                    var id2 = String.format("{0}__{1}__SortDesc", this.get_id(), this._sortExpressions._array[i].get_fieldName());
                    if ($get(id1))
                    {
                        $get(id1).style.display = "none";
                    }
                    if ($get(id2))
                    {
                        $get(id2).style.display = "none";
                    }
                }

                this._sortExpressions.clear();
            }

            this._sortExpressions.add(sortExpression);
        }

        if (!this.fireCommand("Sort", expression))
            return false;
    },

    get_sortExpressions: function()
    {
        return this._sortExpressions;
    },

    filter: function(columnUniqueName, value, filterFunction)
    {
        var filterExpression = new Telerik.Web.UI.GridFilterExpression();

        var column = this.getColumnByUniqueName(columnUniqueName);
        var dataField = column._data.DataField;

        filterExpression.set_fieldName(dataField);
        filterExpression.set_columnUniqueName(columnUniqueName);
        filterExpression.set_dataTypeName(column._data.DataTypeName);

        var foundExpression = this._filterExpressions.find(filterExpression.get_columnUniqueName());
        if (foundExpression != null)
        {
            if (Telerik.Web.UI.GridFilterFunction.parse(filterFunction)
                 == Telerik.Web.UI.GridFilterFunction.NoFilter)
            {
                this._filterExpressions.remove(foundExpression);
            }
            foundExpression.set_filterFunction(filterFunction);
            foundExpression.set_fieldValue(value);
        }

        if (foundExpression == null)
        {
            filterExpression.set_filterFunction(filterFunction);
            filterExpression.set_fieldValue(value);

            this._filterExpressions.add(filterExpression);
        }

        //this.set_currentPageIndex(0);

        if (!this.fireCommand("Filter", columnUniqueName + "|" + value + "|" + filterFunction))
            return false;
    },

    get_filterExpressions: function()
    {
        return this._filterExpressions;
    },

    page: function(command)
    {
        var newIndex = this.get_currentPageIndex();
        if (command == "Next")
        {
            newIndex++;
        }
        else if (command == "Prev")
        {
            newIndex--;
        }
        else if (command == "First")
        {
            newIndex = 0;
        }
        else if (command == "Last")
        {
            newIndex = this.get_pageCount() - 1;
        }
        else
        {
            newIndex = parseInt(command) - 1;
        }

        if (newIndex < 0 || newIndex > (this.get_pageCount() - 1))
            return false;

        this.set_currentPageIndex(newIndex, true);

        if (!this.fireCommand("Page", command))
            return false;
    },

    exportToExcel: function()
    {
        if (!this.fireCommand("ExportToExcel", ""))
            return false;
    },

    exportToWord: function()
    {
        if (!this.fireCommand("ExportToWord", ""))
            return false;
    },

    exportToCsv: function()
    {
        if (!this.fireCommand("ExportToCsv", ""))
            return false;
    },

    exportToPdf: function()
    {
        if (!this.fireCommand("ExportToPdf", ""))
            return false;
    },

    editSelectedItems: function()
    {
        if (!this.fireCommand("EditSelected", ""))
            return false;
    },

    updateEditedItems: function()
    {
        if (!this.fireCommand("UpdateEdited", ""))
            return false;
    },

    deleteSelectedItems: function()
    {
        if (!this.fireCommand("DeleteSelected", ""))
            return false;
    },

    editAllItems: function()
    {
        if (!this.fireCommand("EditAll", ""))
            return false;
    },

    cancelAll: function()
    {
        if (!this.fireCommand("CancelAll", ""))
            return false;
    },

    cancelUpdate: function(rowElement)
    {
        rowElement = this._getRowByIndexOrItemIndexHierarchical(rowElement);
        var itemIndex = rowElement.id.split("__")[1];
        if (!this.fireCommand("CancelUpdate", itemIndex))
            return false;
    },

    groupColumn: function(columnUniqueName)
    {
        if (!this.fireCommand("GroupByColumn", columnUniqueName))
            return false;
    },

    ungroupColumn: function(columnUniqueName)
    {
        if (!this.fireCommand("UnGroupByColumn", columnUniqueName))
            return false;
    },

    _clientDelete: function(e)
    {
        var btn = Telerik.Web.UI.Grid.GetCurrentElement(e);
        var row = btn.parentNode.parentNode;
        var table = row.parentNode.parentNode;

        var itemIndex = row.id.split("__")[1];
        var cellsLength = row.cells.length;

        var index = row.rowIndex;

        var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(row, e);
        this._owner.raise_rowDeleting(args);

        if (args.get_cancel())
        {
            return false;
        }

        table.deleteRow(row.rowIndex);

        for (var i = index; i < table.rows.length; i++)
        {
            if (table.rows[i].cells.length != cellsLength && table.rows[i].style.display != "none")
            {
                table.deleteRow(i);
                i--;
            }
            else
            {
                break;
            }
        }

        if (table.tBodies[0].rows.length == 1 && table.tBodies[0].rows[0].style.display == "none")
        {
            table.tBodies[0].rows[0].style.display = "";
        }

        this._owner.raise_rowDeleted(new Telerik.Web.UI.GridDataItemEventArgs(row, e));

        Array.add(this._owner._deletedItems, itemIndex);

        this.deselectItem(row);

        var dataItem = $find(row.id);
        if (dataItem)
        {
            dataItem.dispose();
            Array.remove(this._dataItems, dataItem);
        }

        this._owner.updateClientState();
    },

    fireCommand: function(commandName, commandArgument)
    {
        var args = new Sys.CancelEventArgs();
        args.get_commandName = function()
        {
            return commandName;
        }
        args.get_commandArgument = function()
        {
            return commandArgument;
        }
        args.get_tableView = function()
        {
            return this;
        }

        this._owner.raise_command(args);

        if (args.get_cancel())
        {
            return false;
        }

        this._executePostBackEvent("FireCommand:" + this._data.UniqueID + ";" + commandName + ";" + commandArgument);
    },

    _executePostBackEvent: function(data)
    {
        var postBackFunction = this._owner.ClientSettings.PostBackFunction;
        postBackFunction = postBackFunction.replace("{0}", this._owner.UniqueID);
        postBackFunction = postBackFunction.replace("{1}", data);
        eval(postBackFunction);
    },

    getDataServiceQuery: function(tableName)
    {
        var sortExpressions = this.get_sortExpressions().toString().replace(" ASC", " asc").replace(" DESC", " desc");
        var filterExpressions = this.get_filterExpressions().toDataService();
        var currentPageIndex = this.get_currentPageIndex();
        var pageSize = this.get_pageSize();

        var sb = new Sys.StringBuilder();
        sb.append(String.format("{0}?", tableName));

        if (sortExpressions != "")
        {
            sb.append(String.format("&$orderby={0}", sortExpressions));
        }

        if (filterExpressions != "")
        {
            sb.append(String.format("&$filter={0}", filterExpressions));
        }

        sb.append(String.format("&$top={0}&$skip={1}", pageSize, currentPageIndex * pageSize));

        return sb.toString();
    }
};

Telerik.Web.UI.GridTableView.registerClass("Telerik.Web.UI.GridTableView", Sys.UI.Control);


Telerik.Web.UI.GridFilterFunction = function()
{
    //
};

Telerik.Web.UI.GridFilterFunction.prototype = 
{
    NoFilter                : 0,
    Contains                : 1,
    DoesNotContain          : 2,
    StartsWith              : 3,
    EndsWith                : 4,
    EqualTo                 : 5,
    NotEqualTo              : 6,
    GreaterThan             : 7,
    LessThan                : 8,
    GreaterThanOrEqualTo    : 9,
    LessThanOrEqualTo       : 10,
    Between                 : 11,
    NotBetween              : 12,
    IsEmpty                 : 13,
    NotIsEmpty              : 14,
    IsNull                  : 15,
    NotIsNull               : 16,
    Custom                  : 17
};

Telerik.Web.UI.GridFilterFunction.registerEnum("Telerik.Web.UI.GridFilterFunction", false);

Telerik.Web.UI.GridSortOrder = function()
{
    //
};

Telerik.Web.UI.GridSortOrder.prototype =
{
    None: 0,
    Ascending: 1,
    Descending: 2
};

Telerik.Web.UI.GridSortOrder.registerEnum("Telerik.Web.UI.GridSortOrder", false);

Telerik.Web.UI.GridSortExpression = function() 
{ 
    this._fieldName = "";
    this._sortOrder = null;
};

Telerik.Web.UI.GridSortExpression.prototype =
{
    get_fieldName: function()
    {
        return this._fieldName;
    },
    set_fieldName: function(value)
    {
        if (this._fieldName != value)
        {
            this._fieldName = value;
            this.FieldName = value;
        }
    },

    get_sortOrder: function()
    {
        return this._sortOrder;
    },
    set_sortOrder: function(value)
    {
        if (this._sortOrder != value)
        {
            this._sortOrder = value;
            this.SortOrder = value;
        }
    },

    dispose: function()
    {
        this._fieldName = null;
        this._sortOrder = null;
    }
}

Telerik.Web.UI.GridSortExpression.registerClass("Telerik.Web.UI.GridSortExpression", null, Sys.IDisposable);

Telerik.Web.UI.GridFilterFunctionsSqlFormat = function()
{
    var _knownFilterFunctions = {};
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Contains] = "[{0}] LIKE '%{1}%'";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.DoesNotContain] = "[{0}] NOT LIKE '%{1}%'";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.StartsWith] = "[{0}] LIKE '{1}%'";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EndsWith] = "[{0}] LIKE '%{1}'";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EqualTo] = "[{0}] = {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotEqualTo] = "[{0}] <> {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThan] = "[{0}] > {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThan] = "[{0}] < {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThanOrEqualTo] = "[{0}] >= {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThanOrEqualTo] = "[{0}] <= {1}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Between] = "([{0}] >= {1}) AND ([{0}] <= {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotBetween] = "([{0}] < {1}) OR ([{0}] > {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsEmpty] = "[{0}] = ''";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsEmpty] = "[{0}] <> ''";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsNull] = "[{0}] IS NULL";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsNull] = "NOT ([{0}] IS NULL)";
    return _knownFilterFunctions;
}

Telerik.Web.UI.GridFilterFunctionsDynamicLinqFormat = function()
{
    var _knownFilterFunctions = {};
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Contains] = "{0}.Contains({1}){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.DoesNotContain] = "!{0}.Contains({1}){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.StartsWith] = "{0}.StartsWith({1}){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EndsWith] = "{0}.EndsWith({1}){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EqualTo] = "{0} = {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotEqualTo] = "{0} <> {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThan] = "{0} > {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThan] = "{0} < {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThanOrEqualTo] = "{0} >= {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThanOrEqualTo] = "{0} <= {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Between] = "({0} >= {1}) AND ({0} <= {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotBetween] = "({0} < {1}) OR ({0} > {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsEmpty] = "{0} = \"\"{1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsEmpty] = "{0} <> \"\"{1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsNull] = "{0} == null{1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsNull] = "({0} != null){1}{2}";
    return _knownFilterFunctions;
}

Telerik.Web.UI.GridFilterFunctionsADONetDataServices = function()
{
    var _knownFilterFunctions = {};
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Contains] = "contains({0},'{1}'){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.DoesNotContain] = "not contains({0},'{1}'){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.StartsWith] = "startswith({0},'{1}'){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EndsWith] = "endswith({0},'{1}'){2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.EqualTo] = "{0} eq {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotEqualTo] = "{0} ne {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThan] = "{0} gt {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThan] = "{0} lt {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.GreaterThanOrEqualTo] = "{0} ge {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.LessThanOrEqualTo] = "{0} le {1}{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.Between] = "({0} ge {1} and {0} le {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotBetween] = "({0} le {1} or {0} ge {2})";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsEmpty] = "{0} eq ''{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsEmpty] = "{0} ne ''{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.IsNull] = "{0} eq null{2}";
    _knownFilterFunctions[Telerik.Web.UI.GridFilterFunction.NotIsNull] = "{0} ne null{2}";
    return _knownFilterFunctions;
}

Telerik.Web.UI.GridFilterExpression = function()
{
    this._fieldName = "";
    this._fieldValue = null;
    this._filterFunction = null;
    this._columnUniqueName = null;
    this._dataTypeName = null;
};

Telerik.Web.UI.GridFilterExpression.prototype =
{
    get_columnUniqueName: function()
    {
        return this._columnUniqueName;
    },
    set_columnUniqueName: function(value)
    {
        if (this._columnUniqueName != value)
        {
            this._columnUniqueName = value;
            this.ColumnUniqueName = value;
        }
    },

    get_fieldName: function()
    {
        return this._fieldName;
    },
    set_fieldName: function(value)
    {
        if (this._fieldName != value)
        {
            this._fieldName = value;
            this.FieldName = value;
        }
    },

    get_fieldValue: function()
    {
        return this._fieldValue;
    },
    set_fieldValue: function(value)
    {
        if (this._fieldValue != value)
        {
            this._fieldValue = value;
            this.FieldValue = value;
        }
    },

    get_filterFunction: function()
    {
        return this._filterFunction;
    },
    set_filterFunction: function(value)
    {
        if (this._filterFunction != value)
        {
            this._filterFunction = value;
            this.FilterFunction = value;
        }
    },

    get_dataTypeName: function()
    {
        return this._dataTypeName;
    },
    set_dataTypeName: function(value)
    {
        if (this._dataTypeName != value)
        {
            this._dataTypeName = value;
            this.DataTypeName = value;
        }
    },

    toString: function(parameter)
    {
        var instanceName = "";

        if (typeof (parameter) != "undefined")
        {
            instanceName = parameter;
        }
        
        var fieldName = this._fieldName;

        if (instanceName != "")
        {
            fieldName = String.format("{0}.{1}", instanceName, fieldName);
        }

        var result = "";

        if (this._filterFunction != null)
        {
            var formats = Telerik.Web.UI.GridFilterFunctionsSqlFormat();
            var format = formats[Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction)];
            if (format != null)
            {
                var parsed = Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction);
                if (parsed != Telerik.Web.UI.GridFilterFunction.Between
                 && parsed != Telerik.Web.UI.GridFilterFunction.NotBetween)
                {
                    if ((this.get_dataTypeName() == "System.String" || this.get_dataTypeName() == "System.Char") &&
                        parsed == Telerik.Web.UI.GridFilterFunction.Contains || parsed == Telerik.Web.UI.GridFilterFunction.DoesNotContain ||
                        parsed == Telerik.Web.UI.GridFilterFunction.StartsWith || parsed == Telerik.Web.UI.GridFilterFunction.EndsWith)
                    {
                        result = String.format(format, fieldName, this._fieldValue);
                    }
                    else
                    {
                        result = String.format(format, fieldName, this.getQuotedValue(this._fieldValue));
                    }
                }
                else
                {
                    var value1 = this._fieldValue.split(" ")[0];
                    var value2 = (this._fieldValue.split(" ").length > 0) ? this._fieldValue.split(" ")[1] : "";
                    result = String.format(format, fieldName, this.getQuotedValue(value1), this.getQuotedValue(value2));
                }
            }
        }

        return result;
    },

    getQuotedValue: function(value)
    {
        if (this.get_dataTypeName() == "System.String" || this.get_dataTypeName() == "System.Char" ||
            this.get_dataTypeName() == "System.DateTime" || this.get_dataTypeName() == "System.TimeSpan" ||
            this.get_dataTypeName() == "System.Guid")
        {
            return String.format("'{0}'", value);
        }

        return value;
    },
    
    getDataServiceValue: function(value)
    {
        if (this.get_dataTypeName() == "System.String" || this.get_dataTypeName() == "System.Char")
        {
            return String.format("'{0}'", value);
        }
        else if(this.get_dataTypeName() == "System.DateTime")
        {
             return String.format("datetime'{0}'", new Date(value).format("yyyy-MM-ddThh:mm:ss"));
        }
        else if(this.get_dataTypeName() == "System.TimeSpan")
        {
             return String.format("time'{0}'", value);
        }
        else if(this.get_dataTypeName() == "System.Guid")
        {
             return String.format("guid'{0}'", value);
        }

        return value;
    },

    getDynamicLinqValue: function(value)
    {
        if (this.get_dataTypeName() == "System.String")
        {
            return String.format("\"{0}\"", value);
        }
        else if (this.get_dataTypeName().indexOf("DateTime") != -1)
        {
            return String.format("DateTime.Parse(\"{0}\")", value);
        }
        else if (this.get_dataTypeName().indexOf("TimeSpan") != -1)
        {
            return String.format("TimeSpan.Parse(\"{0}\")", value);
        }
        else if (this.get_dataTypeName().indexOf("Guid") != -1)
        {
            return String.format("Guid(\{0}\")", value);
        }

        return value;
    },

    toDynamicLinq: function(parameter)
    {
        var instanceName = "";

        if (typeof (parameter) != "undefined")
        {
            instanceName = parameter;
        }

        var result = "";

        if (this._filterFunction != null)
        {
            var formats = Telerik.Web.UI.GridFilterFunctionsDynamicLinqFormat();
            var format = formats[Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction)];
            if (format != null)
            {
                var parsed = Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction);
                var newValue = "";
                var optionalValue = "";

                if (parsed == Telerik.Web.UI.GridFilterFunction.IsNull ||
                    parsed == Telerik.Web.UI.GridFilterFunction.NotIsNull)
                {
                    newValue = "";
                }
                else if (parsed == Telerik.Web.UI.GridFilterFunction.Between ||
                    parsed == Telerik.Web.UI.GridFilterFunction.NotBetween)
                {
                    optionalValue = this.getDynamicLinqValue(this._fieldValue.split(' ')[1]);
                    newValue = this.getDynamicLinqValue(this._fieldValue.split(' ')[0]);
                }
                else
                {
                    newValue = this.getDynamicLinqValue(this._fieldValue);
                }

                var fieldName = this._fieldName;

                if (instanceName != "")
                {
                    fieldName = String.format("{0}.{1}", instanceName, fieldName);
                }

                result = String.format(format, fieldName, newValue, optionalValue);
            }
        }

        return result;
    },

    toDataService: function()
    {
        var result = "";

        if (this._filterFunction != null)
        {
            var formats = Telerik.Web.UI.GridFilterFunctionsADONetDataServices();
            var format = formats[Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction)];
            if (format != null)
            {
                var parsed = Telerik.Web.UI.GridFilterFunction.parse(this._filterFunction);
                var newValue = "";
                var optionalValue = "";

                if (parsed == Telerik.Web.UI.GridFilterFunction.IsNull ||
                    parsed == Telerik.Web.UI.GridFilterFunction.NotIsNull)
                {
                    newValue = "";
                }
                else if (parsed == Telerik.Web.UI.GridFilterFunction.Between ||
                    parsed == Telerik.Web.UI.GridFilterFunction.NotBetween)
                {
                    optionalValue = this._fieldValue.split(' ')[1];
                    newValue = this._fieldValue.split(' ')[0];
                }
                else
                {
                    newValue = this._fieldValue;
                }

                result = String.format(format, this._fieldName, 
                    this.getDataServiceValue(newValue), 
                    (optionalValue != "")? this.getDataServiceValue(optionalValue) : optionalValue);
            }
        }

        return result;
    },

    dispose: function()
    {
        this._fieldName = null;
        this._fieldValue = null;
        this._filterFunction = null;
        this._columnUniqueName = null;
        this._dataTypeName = null;
    }
}

Telerik.Web.UI.GridFilterExpression.registerClass("Telerik.Web.UI.GridFilterExpression", null, Sys.IDisposable);

Telerik.Web.UI.Collection = function ()
{
	this._array = new Array();
}

Telerik.Web.UI.Collection.prototype =
{
    add: function(item)
    {
        var index = this._array.length;
        this.insert(index, item);
    },

    insert: function(index, item)
    {
        Array.insert(this._array, index, item);
    },

    remove: function(item)
    {
        Array.remove(this._array, item);
    },

    removeAt: function(index)
    {
        var item = this.getItem(index);
        if (item)
            this.remove(item);
    },

    clear: function()
    {
        this._array = new Array();
    },
    
    toList: function()
    {
        return this._array;
    },

    get_count: function()
    {
        return this._array.length;
    },

    getItem: function(index)
    {
        return this._array[index];
    },

    indexOf: function(item)
    {
        return Array.indexOf(this._array, item);
    },

    forEach: function(lambda)
    {
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            lambda(this._array[i]);
        }
    },

    dispose: function()
    {
        this._array = null;
    }
}

Telerik.Web.UI.Collection.registerClass("Telerik.Web.UI.Collection", null, Sys.IDisposable);


Telerik.Web.UI.GridSortExpressions = function()
{
    Telerik.Web.UI.GridSortExpressions.initializeBase(this);
};

Telerik.Web.UI.GridSortExpressions.prototype =
{
    find: function(fieldName)
    {
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            if (item.get_fieldName() == fieldName)
                return item;
        }

        return null;
    },

    sortOrderAsString: function(sortOrder)
    {
        if (sortOrder == 0)
        {
            return "";
        }
        else if (sortOrder == 1)
        {
            return "ASC";
        }
        else if (sortOrder == 2)
        {
            return "DESC";
        }
    },

    toString: function()
    {
        var result = [];
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            result[result.length] = String.format("{0} {1}", item.get_fieldName(), this.sortOrderAsString(item.get_sortOrder()));
        }

        return result.join(",");
    }
}

Telerik.Web.UI.GridSortExpressions.registerClass("Telerik.Web.UI.GridSortExpressions", Telerik.Web.UI.Collection);


Telerik.Web.UI.GridFilterExpressions = function()
{
    Telerik.Web.UI.GridFilterExpressions.initializeBase(this);
};

Telerik.Web.UI.GridFilterExpressions.prototype =
{
    find: function(columnUniqueName)
    {
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            if (item.get_columnUniqueName() == columnUniqueName)
                return item;
        }

        return null;
    },

    toString: function(parameter)
    {
        var instanceName = "";

        if (typeof (parameter) != "undefined")
        {
            instanceName = parameter;
        }

        var result = [];
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            result[result.length] = item.toString(instanceName);
        }

        return result.join(" AND ");
    },

    toDynamicLinq: function(parameter)
    {
        var instanceName = "";

        if (typeof (parameter) != "undefined")
        {
            instanceName = parameter;
        }

        var result = [];
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            result[result.length] = item.toDynamicLinq(instanceName);
        }

        return result.join(" AND ");
    },

    toDataService: function()
    {
        var result = [];
        for (var i = 0, count = this.get_count(); i < count; i++)
        {
            var item = this.getItem(i);
            result[result.length] = item.toDataService();
        }

        return result.join(" and ");
    }
}

Telerik.Web.UI.GridFilterExpressions.registerClass("Telerik.Web.UI.GridFilterExpressions", Telerik.Web.UI.Collection);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridGroupPanel = function(element) 
{
    Telerik.Web.UI.GridGroupPanel.initializeBase(this, [element]);

    this._owner = {};
};

Telerik.Web.UI.GridGroupPanel.prototype = 
{
    initialize : function() 
    {   
        Telerik.Web.UI.GridGroupPanel.callBaseMethod(this, 'initialize');

	    this.groupPanelItemCounter = 0;
	    this._createGroupPanelItems(this.get_element(), 0);
    },

    dispose : function() 
    {
        $clearHandlers(this.get_element());
        this._element.control = null;
        //this._element = null;

        Telerik.Web.UI.GridGroupPanel.callBaseMethod(this, 'dispose');
    },

    _createGroupPanelItems : function(table)
    {
        this._itemsInternal = eval(this._owner._groupPanelItems);
        this._items = [];
        for(var i = 0; i < table.rows.length; i++)
	    {
		    var foundItemsOnThisRow = false;
		    var row = table.rows[i];

		    for(var j = 0; j < row.cells.length; j++)
		    {
			    var cell = row.cells[j];

			    if (cell.tagName.toLowerCase() == "th")
			    {
				    var hierarchicalIndex;
				    if (this._itemsInternal[this.groupPanelItemCounter])
				    {
					    hierarchicalIndex = this._itemsInternal[this.groupPanelItemCounter].HierarchicalIndex;
				    }
    				
				    if (hierarchicalIndex)
				    {
				        this._items[this._items.length] = 
				            $create(
				                    Telerik.Web.UI.GridGroupPanelItem, 
				                    {
				                        _hierarchicalIndex : hierarchicalIndex, 
				                        _owner : this
				                    }, 
				                    null, 
				                    null, 
				                    cell
				                );
					    foundItemsOnThisRow = true;
					    this.groupPanelItemCounter++;
				    }
			    }

			    if ((cell.firstChild) && (cell.firstChild.tagName))
			    {
				    if (cell.firstChild.tagName.toLowerCase() == "table")
				    {
					    this._createGroupPanelItems(cell.firstChild);
				    }
			    }
		    }
	    }
    },
    
    _isItem : function(element)
    {
	    for (var i = 0; i < this._items.length; i++)
	    {
		    if (this._items[i].get_element() == element)
			    return this._items[i];
	    }
	    return null;
    }
};

Telerik.Web.UI.GridGroupPanel.registerClass('Telerik.Web.UI.GridGroupPanel', Sys.UI.Control);

Telerik.Web.UI.GridGroupPanelItem = function(element) 
{
    Telerik.Web.UI.GridGroupPanelItem.initializeBase(this, [element]);
    
    this._hierarchicalIndex = null;
    this._owner = {};
};

Telerik.Web.UI.GridGroupPanelItem.prototype =
{
    initialize: function()
    {
        Telerik.Web.UI.GridGroupPanelItem.callBaseMethod(this, 'initialize');

        this.get_element().style.cursor = "move";

        this._onMouseDownDelegate = Function.createDelegate(this, this._onMouseDownHandler);
        $addHandler(this.get_element(), "mousedown", this._onMouseDownDelegate);
    },

    dispose: function()
    {
       $clearHandlers(this.get_element());
       this._element.control = null;
       //this._element = null;

       Telerik.Web.UI.GridGroupPanelItem.callBaseMethod(this, 'dispose');
    },

    _onMouseDownHandler: function(e)
    {
        this._onMouseUpDelegate = Function.createDelegate(this, this._onMouseUpHandler);
        $telerik.addExternalHandler(document, "mouseup", this._onMouseUpDelegate);
        //$addHandler(document, "mouseup", this._onMouseUpDelegate);

        this._onMouseMoveDelegate = Function.createDelegate(this, this._onMouseMoveHandler);
        //$addHandler(document, "mousemove", this._onMouseMoveDelegate);
        $telerik.addExternalHandler(document, "mousemove", this._onMouseMoveDelegate);

        Telerik.Web.UI.Grid.CreateDragDrop(e, this, false);

        Telerik.Web.UI.Grid.CreateReorderIndicators(this.get_element(), this._owner._owner.Skin, this._owner._owner.ImagesPath, false, this._owner._owner.get_id());
    },

    _onMouseUpHandler: function(e)
    {
        $telerik.removeExternalHandler(document, "mouseup", this._onMouseUpDelegate);
        $telerik.removeExternalHandler(document, "mousemove", this._onMouseMoveDelegate);
        // $removeHandler(document, "mouseup", this._onMouseUpDelegate);
        // $removeHandler(document, "mousemove", this._onMouseMoveDelegate);

        this._fireDropAction(e);

        Telerik.Web.UI.Grid.DestroyDragDrop();
    },

    _onMouseMoveHandler: function(e)
    {
        Telerik.Web.UI.Grid.MoveDragDrop(e, this, false);
    },

    _fireDropAction: function(e)
    {
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
        if (currentElement != null)
        {
            var postBackFunction = this._owner._owner.ClientSettings.PostBackFunction;
            postBackFunction = postBackFunction.replace("{0}", this._owner._owner.UniqueID);

            if (!Telerik.Web.UI.Grid.IsChildOf(currentElement, this._owner.get_element()))
            {
                var commandName = "UnGroupByExpression";
                var commandArgument = this._hierarchicalIndex;
                
                var args = new Sys.CancelEventArgs();
                args.get_commandName = function()
                {
                    return commandName;
                }
                args.get_commandArgument = function()
                {
                    return commandArgument;
                }

                this._owner._owner.raise_command(args);

                if (args.get_cancel())
                {
                    return false;
                }

                postBackFunction = postBackFunction.replace("{1}", "UnGroupByExpression," + this._hierarchicalIndex);
                eval(postBackFunction);
            }
            else
            {
                var item = this._owner._isItem(currentElement);
                if ((currentElement != this.get_element()) &&
				    (item != null) &&
				    (currentElement.parentNode == this.get_element().parentNode))
                {
                    var commandName = "ReorderGroupByExpression";
                    var commandArgument = this._hierarchicalIndex + "," + item._hierarchicalIndex;

                    var args = new Sys.CancelEventArgs();
                    args.get_commandName = function()
                    {
                        return commandName;
                    }
                    args.get_commandArgument = function()
                    {
                        return commandArgument;
                    }

                    this._owner._owner.raise_command(args);

                    if (args.get_cancel())
                    {
                        return false;
                    }

                    postBackFunction = postBackFunction.replace("{1}", "ReorderGroupByExpression," + this._hierarchicalIndex + "," + item._hierarchicalIndex);
                    eval(postBackFunction);
                }
            }
        }
    }
};

Telerik.Web.UI.GridGroupPanelItem.registerClass('Telerik.Web.UI.GridGroupPanelItem', Sys.UI.Control);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.GridMenu = function() 
{
    Telerik.Web.UI.GridMenu.initializeBase(this);

    this._owner = {};
    this._items = [];
    this._onMenuElementClickDelegate = null;
    this._onMenuElementMouseoverDelegate = null;
	this._onMenuElementMouseoutDelegate = null;
	this._element = null;
	this._overRow = null;
};

Telerik.Web.UI.GridMenu.prototype = 
{
    initialize : function() 
    {   
        Telerik.Web.UI.GridMenu.callBaseMethod(this, 'initialize');

	    this._element = document.createElement("table");	
	    this.get_element().style.backgroundColor = this.SelectColumnBackColor;
	    this.get_element().style.border = "outset 1px";
	    this.get_element().style.fontSize = "small";
	    this.get_element().style.textAlign = "left";
	    this.get_element().cellPadding = "0";
	    this.get_element().style.borderCollapse = "collapse";
	    this.get_element().style.zIndex = 998;
    	
	    this.Skin = (this._owner && this._owner._owner && this._owner._owner.Skin) || "";
	    
	    var isRtl = Telerik.Web.UI.Grid.IsRightToLeft(this._owner.get_element());
	    if (isRtl)
	    {
	        this.get_element().style.direction = "rtl";
	        Sys.UI.DomElement.addCssClass(this.get_element(), "RadGridRTL_" + this._owner.Skin);    
	    }
    	
	    Sys.UI.DomElement.addCssClass(this.get_element(), "GridFilterMenu_" + this._owner.Skin);
	    Sys.UI.DomElement.addCssClass(this.get_element(), this._owner._filterMenuData.CssClass);

	    this.createItems(this._owner._filterMenuData.Items);

	    this.get_element().style.position = "absolute";
	    this.get_element().style.display = "none";
	    document.body.appendChild(this.get_element());
    	
	    var image1 = document.createElement("img");
	    image1.src = this._owner._filterMenuData.SelectedImageUrl;
	    image1.src = this._owner._filterMenuData.NotSelectedImageUrl;

	    this.get_element().style.zIndex = 100000;
    },

    dispose : function() 
    {    
        if (this._items){       
            this._items = null;
        }        
        if (this._owner)
            this._owner = null;
            
        if (this._onMenuElementClickDelegate)
        {
            $removeHandler(this.get_element(), "click", this._onMenuElementClickDelegate);
            this._onMenuElementClickDelegate = null;                    
        }
        
        if (this._onMenuElementMouseoverDelegate)
        {
            $removeHandler(this.get_element(), "mouseover", this._onMenuElementMouseoverDelegate); 
            this._onMenuElementMouseoverDelegate = null
        }
        
        if (this._onMenuElementMouseoutDelegate)
        {
            $removeHandler(this.get_element(), "mouseout", this._onMenuElementMouseoutDelegate); 
            this._onMenuElementMouseoutDelegate = null;
        }  
            
        if(this.get_element() && this.get_element().parentNode)
        {
            this.get_element().parentNode.removeChild(this.get_element());
        }
        
        this._element = null;

        Telerik.Web.UI.GridMenu.callBaseMethod(this, 'dispose');
    },
    
    get_element : function(){
        return this._element;
    },
    
    click : function(e)
    {
	    if (!e.cancelBubble)
	    {
		    this.hide();
	    }
    },

    keyPress : function(e)
    {
	    if (e.charCode == 27)
	    {
		    this.hide();
	    }
    },

    createItems : function(items)
    {
        this._onMenuElementClickDelegate = Function.createDelegate(this, this._menuElementClick);
	    this._onMenuElementMouseoverDelegate = Function.createDelegate(this, this._menuElementMouseover);
	    this._onMenuElementMouseoutDelegate = Function.createDelegate(this, this._menuElementMouseout);
	        
        $addHandler(this.get_element(), "click", this._onMenuElementClickDelegate);
        $addHandler(this.get_element(), "mouseover", this._onMenuElementMouseoverDelegate);
        $addHandler(this.get_element(), "mouseout", this._onMenuElementMouseoutDelegate);
        
	    for(var i = 0; i < items.length; i++)
	    {
	        var tr = this.get_element().insertRow(-1);
	        tr.insertCell(-1);

	        var table = document.createElement("table");
	        table.style.width = "100%";
	        table.cellPadding = "0";
	        table.cellSpacing = "0";

	        table.insertRow(-1);
	        var td1 = table.rows[0].insertCell(-1);
	        var td2 = table.rows[0].insertCell(-1);

	        if(this._owner.Skin == "")
	        {
	            td1.style.borderTop = "solid 1px " + this._owner._filterMenuData.SelectColumnBackColor;
	            td1.style.borderLeft = "solid 1px " + this._owner._filterMenuData.SelectColumnBackColor;
	            td1.style.borderRight = "none 0px";
	            td1.style.borderBottom = "solid 1px " + this._owner._filterMenuData.SelectColumnBackColor;
	            td1.style.padding = "2px";
	            td1.style.textAlign = "center";
	        }
	        else
	        {
	            Sys.UI.DomElement.addCssClass(td1, "GridFilterMenuSelectColumn_" + this._owner.Skin);
	        }

            td1.style.width = "16px";

	        td1.appendChild(document.createElement("img"));
	        td1.childNodes[0].src = this._owner._filterMenuData.NotSelectedImageUrl;

	        //this.SelectImage = td1.childNodes[0];

	        if(this._owner.Skin == "")
	        {
	            td2.style.borderTop = "solid 1px " + this._owner._filterMenuData.TextColumnBackColor;
	            td2.style.borderLeft = "none 0px";
	            td2.style.borderRight = "solid 1px " + this._owner._filterMenuData.TextColumnBackColor;
	            td2.style.borderBottom = "solid 1px " + this._owner._filterMenuData.TextColumnBackColor;
	            td2.style.padding = "2px";
	            td2.style.backgroundColor = this._owner._filterMenuData.TextColumnBackColor;
	            td2.style.cursor = "pointer";
            }
            else
            {
	            Sys.UI.DomElement.addCssClass(td2, "GridFilterMenuTextColumn_" + this._owner.Skin);
            }

	        td2.innerHTML = items[i].Text;

	        tr.cells[0].appendChild(table);
	        
	        tr.id = items[i].UID;

            var obj = {};
            obj.id = tr.id;
            obj.Value = items[i].Value;
            obj.Image = td1.childNodes[0];
            
	        this._items[this._items.length] = obj;        	                
	    }
    },
    
    _menuElementClick : function(e){
        var postBackFunc = this._owner.ClientSettings.PostBackFunction;
        var tableViewUniqueID = this.get_element().column._owner._data.UniqueID;
        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        if(row)
        {
            var outterRow = Telerik.Web.UI.Grid.GetFirstParentByTagName(row.parentNode, "tr");
            if (outterRow)
            {
                 postBackFunc = postBackFunc.replace("{0}", outterRow.id).replace("{1}", tableViewUniqueID + "!" + this.get_element().column.get_element().UniqueName);
                 eval(postBackFunc);
            }
         }       
    },
    
    _menuElementMouseover : function(e){                       
        this._removeFilterRowStyles();
                
        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        if(row)
        {
            var outterRow = Telerik.Web.UI.Grid.GetFirstParentByTagName(row.parentNode, "tr");
            if (outterRow)
            {
                var cell1 = outterRow.cells[0].childNodes[0].rows[0].cells[0];
                var cell2 = outterRow.cells[0].childNodes[0].rows[0].cells[1];
                
                if(this._owner.Skin != "")
                {                   
                    Sys.UI.DomElement.addCssClass(cell1, "GridFilterMenuHover_" + this._owner.Skin);
                    Sys.UI.DomElement.addCssClass(cell2, "GridFilterMenuHover_" + this._owner.Skin);
                }else{
                    var data = this._owner._filterMenuData; 
                    cell1.style.backgroundColor = data.HoverBackColor;
                    cell1.style.borderTop = "solid 1px " + data.HoverBorderColor;
                    cell1.style.borderLeft = "solid 1px " + data.HoverBorderColor;
                    cell1.style.borderBottom = "solid 1px " + data.HoverBorderColor;
                    cell2.style.backgroundColor = data.HoverBackColor;
                    cell2.style.borderTop = "solid 1px " + data.HoverBorderColor;
                    cell2.style.borderRight = "solid 1px " + data.HoverBorderColor;
                    cell2.style.borderBottom = "solid 1px " + data.HoverBorderColor;
                }           
                
                this._overRow = outterRow;
            }
        }
    },
    _removeFilterRowStyles : function(){
         if(this._overRow)
        {
            var cell1 = this._overRow.cells[0].childNodes[0].rows[0].cells[0];
            var cell2 = this._overRow.cells[0].childNodes[0].rows[0].cells[1];
                
            if(this._owner.Skin != "")
            {
                
                Sys.UI.DomElement.removeCssClass(cell1,"GridFilterMenuHover_" + this._owner.Skin);
                Sys.UI.DomElement.removeCssClass(cell2,"GridFilterMenuHover_" + this._owner.Skin);
            }
            else
            {
                var data = this._owner._filterMenuData;
                cell1.style.borderTop = "solid 1px " + data.SelectColumnBackColor;
                cell1.style.borderLeft = "solid 1px " + data.SelectColumnBackColor;
                cell1.style.borderBottom = "solid 1px " + data.SelectColumnBackColor;
                cell1.style.backgroundColor = "";

                cell2.style.borderTop = "solid 1px " + data.TextColumnBackColor;
                cell2.style.borderRight = "solid 1px " + data.TextColumnBackColor;
                cell2.style.borderBottom = "solid 1px " + data.TextColumnBackColor;
                cell2.style.backgroundColor = data.TextColumnBackColor;  
            }
        }
    },
    _menuElementMouseout : function(e){   
        this._removeFilterRowStyles();
        this._overRow = null;
    },
    
    show : function(column, e)
    {
        this.hide();
        this.showItems(column._data.FilterListOptions, column._data.DataTypeName, column._data.CurrentFilterFunction, column);
        
        e.cancelBubble = true;

        this._onClickDelegate = Function.createDelegate(this, this.click);
        $addHandler(document, "click", this._onClickDelegate);
        
        this._onKeyPressDelegate = Function.createDelegate(this, this.keyPress);
        $addHandler(document, "keypress", this._onKeyPressDelegate);
        
        var menuObj = this;
        var args = new Sys.CancelEventArgs();
        args.get_menu = function()
        {
            return menuObj;
        }
        args.get_tableView = function()
        {
            return menuObj._owner;
        }
        args.get_column = function()
        {
            return column;
        }
        args.get_domEvent = function()
        {
            return e;
        }
               
        this._owner.raise_filterMenuShowing(args);
        
        if(args.get_cancel())
        {
            return;
        }

        this.get_element().style.display = "";
	    this.get_element().style.top = e.clientY + document.documentElement.scrollTop + document.body.scrollTop + 5 + "px";
	    this.get_element().style.left = e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft + 5 + "px";
        
        this.get_element().column = column;
    },
    
    hide : function()
    {
        if(this._onClickDelegate)
        {
            $removeHandler(document, "click", this._onClickDelegate);
            this._onClickDelegate = null;
        }

        if(this._onKeyPressDelegate)
        {
            $removeHandler(document, "keypress", this._onKeyPressDelegate);
            this._onKeyPressDelegate = null;
        }

	    if (this.get_element() && this.get_element().style.display == "")
	    {
		    this.get_element().style.display = "none";
	    }
    },
    
    showItems : function(filterListOptions, dataTypeName, currentFilterFunction, column)
    {
        for(var i = 0; i < this._items.length; i++)
        {
            var tr = $get(this._items[i].id);
            
            if (dataTypeName == "System.Boolean")
	        {
		        if((this._items[i].Value == "GreaterThan") || 
			        (this._items[i].Value == "LessThan") || 
			        (this._items[i].Value == "GreaterThanOrEqualTo") || 
			        (this._items[i].Value == "LessThanOrEqualTo") || 
			        (this._items[i].Value == "Between") ||
			        (this._items[i].Value == "NotBetween") )
		        {
			        tr.style.display = "none";
			        continue;
		        }
	        }

	        if (dataTypeName != "System.String")
	        {
		        if((this._items[i].Value == "StartsWith") || 
			        (this._items[i].Value == "EndsWith") || 
			        (this._items[i].Value == "Contains") || 
			        (this._items[i].Value == "DoesNotContain") || 
			        (this._items[i].Value == "IsEmpty") ||
			        (this._items[i].Value == "NotIsEmpty") )
		        {
			        tr.style.display = "none";
			        continue;
		        }
	        }

	        if (filterListOptions == 0)
	        {
		        if(this._items[i].Value == "Custom")
		        {
			        tr.style.display = "none";
			        continue;
		        }
	        }
	        
	        if((column._data.ColumnType == "GridDateTimeColumn" || column._data.ColumnType == "GridMaskedColumn" || column._data.ColumnType == "GridNumericColumn")&& ((this._items[i].Value == "Between") ||
			        (this._items[i].Value == "NotBetween")))
			{
			    tr.style.display = "none";
                continue;
			}

            if(currentFilterFunction == i)
            {
                this._items[i].Image.src = this._owner._filterMenuData.SelectedImageUrl;
            }
            else
            {
                this._items[i].Image.src = this._owner._filterMenuData.NotSelectedImageUrl;
            }
	        tr.style.display = "";
        }        
    }
};

Telerik.Web.UI.GridMenu.registerClass('Telerik.Web.UI.GridMenu', Sys.Component);;Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadGrid = function(element) 
{
    var events = ["gridCreating", "gridCreated", "gridDestroying", "masterTableViewCreating",
                  "masterTableViewCreated", "tableCreating",
                  "tableCreated", "tableDestroying", "columnCreating",
                  "columnCreated", "columnDestroying", "columnResizing",
                  "columnResized", "columnSwapping", "columnSwapped",
                  "columnMovingToLeft", "columnMovedToLeft", "columnMovingToRight",
                  "columnMovedToRight", "columnHiding", "columnHidden",
                  "columnShowing", "columnShown", "rowCreating",
                  "rowCreated", "rowDestroying", "rowResizing", "rowResized",
                  "rowHiding","rowHidden","rowShowing","rowShown","rowClick",
                  "rowDblClick","columnClick","columnDblClick","rowSelecting",
                  "rowSelected","rowDeselecting","rowDeselected","rowMouseOver",
                  "rowMouseOut","columnMouseOver","columnMouseOut","columnContextMenu",
                  "rowContextMenu","scroll","keyPress","hierarchyExpanding","hierarchyExpanded",
                  "hierarchyCollapsing","hierarchyCollapsed","groupExpanding","groupExpanded",
                  "groupCollapsing","groupCollapsed","activeRowChanging","activeRowChanged",
                  "rowDeleting","rowDeleted","filterMenuShowing","rowDropping","rowDropped",
                  "rowDragStarted", "popUpShowing", "command", "rowDataBound"];

    this._initializeEvents(events);

    Telerik.Web.UI.RadGrid.initializeBase(this, [element]);

    this.Skin = "Default";
    this._imagesPath = "";
    this._embeddedSkin = true;
    this.ClientID = null;
    this.UniqueID = null;
    
    this._activeRowIndex = "";
    this._activeRow = null;
    
    this.ShowGroupPanel = false;
    this._groupPanel = null;
    this._groupPanelClientID = "";
    this._groupPanelItems = "";
    
    this._gridTableViewsData = "";
    this._popUpIds = "";
    this._popUpSettings = {};

    this.ClientSettings = {};
    
    this._selection = null;
    this._selectedIndexes = [];
    this._selectedItemsInternal = [];
    
    this._masterClientID = "";
    
    this._scrolling = null;
    
    this._gridItemResizer = null;
    
    this._resizedItems = "";
    this._resizedColumns = "";
    this._resizedControl = "";
    this._hidedItems = "";
    this._showedItems = "";
    this._hidedColumns = "";
    this._showedColumns = "";
        
    this._reorderedColumns = [];
    
    this._filterMenuData = {};
    this._filterMenu = null;
    
    this._detailTables = [];
    
    this._clientKeyValues = {};

    this._onKeyDownDelegate = null;
    this._onMouseMoveDelegate = null;
    
    this._hierarchySettings = {};
    this._groupingSettings = {};
    
    this._currentPageIndex = null;
    
    this._expandedItems = [];
    this._expandedGroupItems = [];

    this._deletedItems = [];
    
    this._expandedFilterItems = [];
    
    this._initializeRequestHandler = null;
    this._endRequestHandler = null;
    
    this._statusLabelID = null;
    this._loadingText = null;
    this._readyText = null;
    
    this._onFilterMenuClick = null    
    
    this._popUpLocations = {};
    
    window[this.ClientID] = this;
    
    this._canMoveRow = false;
    this._originalDragItem = null;
    this._dropClue = null;
    
    this._draggedItems = [];
    
    this._draggedItemsIndexes = [];
    //this._onSelectStartDelegate = null;
    this._draggingPosition = "above";
    this._editIndexes = null;
};

Telerik.Web.UI.RadGrid.prototype =
{
    initialize: function()
    {
        Telerik.Web.UI.RadGrid.callBaseMethod(this, 'initialize');

        if ((!this._masterClientID) || (!$get(this._masterClientID)))
            return;
            
        if(this._editIndexes != null)
        {
            this._editIndexes = eval(this._editIndexes);
        }

        var _popUpIdsData = eval(this._popUpIds);
        var left, top = 20;
        for (var i = 0; i < _popUpIdsData.length; i++)
        {
            var popUpId = _popUpIdsData[i];
            var popUp = $get(popUpId);
            if (popUp)
            {

                var args = new Sys.CancelEventArgs();
                args.get_popUp = function()
                {
                    return popUp;
                }

                this.raise_popUpShowing(args);

                if (args.get_cancel())
                {
                    continue;
                }

                if (this._popUpSettings.Modal)
                {
                    var modalDivId = String.format("modalDivId_{0}", this.get_id());
                    if (!$get(modalDivId))
                    {
                        var modalDiv = document.createElement("div");
                        modalDiv.id = modalDivId;
                        modalDiv.style.width = document.documentElement.scrollWidth + "px";
                        modalDiv.style.height = document.documentElement.scrollHeight + "px";
                        
                        this._onResizeDelegate = Function.createDelegate(this, this.onWindowResize);
                        var thisObject = this;
						if(navigator.userAgent.toLowerCase().indexOf("msie") != -1)
						{
							setTimeout(function(){
									$addHandler(window, "resize", thisObject._onResizeDelegate);
							}, 0);
						}
						else
						{
							$addHandler(window, "resize", this._onResizeDelegate);
						}
                        
                        modalDiv.style.top = modalDiv.style.left = 0;
                        modalDiv.style.position = "absolute";
                        modalDiv.style.backgroundColor = "threedshadow";
                        modalDiv.style.zIndex = this._popUpSettings.ZIndex - 10;

                        try{ modalDiv.style.opacity = "0.5"; }
							catch (e) {}
						
                        if (typeof (modalDiv.style.filter) != "undefined")
                        {
                            modalDiv.style.filter = "alpha(opacity=50);";
                        }
                        else if (typeof (modalDiv.style.MozOpacity) != "undefined")
                        {
                            modalDiv.style.MozOpacity = 1 / 2;
                        }

                        var form = document.getElementsByTagName("form")[0];
                        form.appendChild(modalDiv);
                    }
                }

                popUp.style.zIndex = this._popUpSettings.ZIndex;

                left = top += 20;

                if (popUp.style.left == "")
                    popUp.style.left = Telerik.Web.UI.Grid.FindPosX(this.get_element()) + left + "px";

                if (popUp.style.top == "")
                    popUp.style.top = Telerik.Web.UI.Grid.FindPosY(this.get_element()) + top + "px";

                popUp.style.display = "";
                popUp.tabIndex = 0;

                var dragHandle = popUp.getElementsByTagName("div")[0];

                if ($telerik.isIE6)
                    dragHandle.style.width = popUp.offsetWidth + "px";

                this.resizeModalBackground();

                popUp.getElementsByTagName("div")[4].style.height = popUp.offsetHeight - dragHandle.offsetHeight + "px";

                this._popUpLocations[dragHandle.id] = popUp.style.left + "," + popUp.style.top;
                this.updateClientState();

                $addHandlers(dragHandle, { mousedown: Function.createDelegate(popUp, this._popUpMouseDown) });
                $addHandlers(dragHandle, { mouseup: Function.createDelegate(popUp, this._popUpMouseUp) });
                //$addHandlers(document, {mousemove:Function.createDelegate(popUp, this._popUpMouseMove)});
                $telerik.addExternalHandler(document, "mousemove", Function.createDelegate(popUp, this._popUpMouseMove));
            }
        }

        //this.ClientSettings.AllowRowsDragDrop = true;
        if (this.ClientSettings.AllowRowsDragDrop)
        {
            $addHandlers(this.get_element(), { mousedown: Function.createDelegate(this, this._mouseDown) });
            $telerik.addExternalHandler(document, "mouseup", Function.createDelegate(this, this._mouseUp));
            $telerik.addExternalHandler(document, "mousemove", Function.createDelegate(this, this._mouseMove));

            //            $addHandlers(document, {mouseup:Function.createDelegate(this, this._mouseUp)});
            //            $addHandlers(document, {mousemove:Function.createDelegate(this, this._mouseMove)});            
        }

        $addHandlers(this.get_element(), { click: Function.createDelegate(this, this._click) });
        $addHandlers(this.get_element(), { dblclick: Function.createDelegate(this, this._dblclick) });
        $addHandlers(this.get_element(), { contextmenu: Function.createDelegate(this, this._contextmenu) });
        $addHandlers(this.get_element(), { mouseover: Function.createDelegate(this, this._mouseover) });
        $addHandlers(this.get_element(), { mouseout: Function.createDelegate(this, this._mouseout) });

        this.raise_gridCreating(new Sys.EventArgs())

        this.Control = this.get_element();

        this.get_element().tabIndex = 0;

        if (this.ShowGroupPanel)
        {
            var groupPanelEl = $get(this._groupPanelClientID);
            if (groupPanelEl)
            {
                this._groupPanel = $create(
                        Telerik.Web.UI.GridGroupPanel,
                {
                    _owner: this
                },
                        null,
                        null,
                        $get(this._groupPanelClientID)
                );
            }
        }

        this._gridDataDiv = $get(this.get_id() + "_GridData");

        if (this.ClientSettings &&
            (this.ClientSettings.Selecting && this.ClientSettings.Selecting.AllowRowSelect)
            || this.ClientSettings.EnablePostBackOnRowClick
            )
        {
            this._selection = $create(
                    Telerik.Web.UI.GridSelection,
            {
                _owner: this
            },
                    null,
                    null
                );
        }

        this._initializeTableViews();
        
        this.GridDataDiv = $get(this.ClientID + "_GridData");
        this.GridHeaderDiv = $get(this.ClientID + "_GridHeader");
        this.GridFooterDiv = $get(this.ClientID + "_GridFooter");
        this.PagerControl = $get(this._masterClientID + "_Pager");
        this.TopPagerControl = $get(this._masterClientID + "_TopPager");

        //        if(this._filterMenuData.Items)
        //        {
        //            this._filterMenu = $create(
        //                    Telerik.Web.UI.GridMenu, 
        //                    {
        //                        _owner : this
        //                    },
        //                    null,
        //                    null
        //                );
        //        }       

        var isRtl = Telerik.Web.UI.Grid.IsRightToLeft(this.get_masterTableView().get_element());
        if (isRtl)
        {
			this.get_element().className = String.format("{0} RadGridRTL_{1}", this.get_element().className, this.Skin);
        }

        if (this.ClientSettings &&
            this.ClientSettings.Scrolling &&
            (this.ClientSettings.Scrolling.AllowScroll ||
                (this.ClientSettings.Scrolling.AllowScroll &&
                    (this.ClientSettings.Scrolling.UseStaticHeaders || this.ClientSettings.Scrolling.EnableVirtualScrollPaging)
                )
            )
          )
        {
            this._scrolling = $create(
                    Telerik.Web.UI.GridScrolling,
            {
                _owner: this
            },
                    null,
                    null
                );
        }

        if (this._activeRowIndex)
        {
            var row = $get(this._activeRowIndex);
            if (row)
            {
                this.set_activeRow(row);
            }
        }

        this._attachDomEvents();

        if (Sys.WebForms && Sys.WebForms.PageRequestManager)
        {
            var requestManager = Sys.WebForms.PageRequestManager.getInstance();

            this._initializeRequestHandler = Function.createDelegate(this, this._initializeRequest);
            requestManager.add_initializeRequest(this._initializeRequestHandler);
        }

        this.raise_gridCreated(new Sys.EventArgs());
    },

    repaint: function()
    {
        if (Telerik.Web.UI.GridScrolling && this._scrolling)
        {
            this._scrolling.onWindowResize();
        }
    },
    
    onWindowResize: function()
    {
		this.resizeModalBackground();
    },
    
    resizeModalBackground: function()
    {
		var modalDivId = String.format("modalDivId_{0}", this.get_id());
		var modalDiv = $get(modalDivId);
		if (modalDiv)
		{
			modalDiv.style.width = "1px";
			modalDiv.style.height = "1px";
			modalDiv.style.width = document.documentElement.scrollWidth + "px";
			modalDiv.style.height = document.documentElement.scrollHeight + "px";
		}
    },

    _popUpMouseDown: function(e)
    {
        this.canMove = true;

        this.originalLeft = this.offsetLeft - e.clientX;
        this.originalTop = this.offsetTop - e.clientY;

        return false;
    },

    _popUpMouseUp: function(e)
    {
        this.canMove = false;

        var dragHandle = this.getElementsByTagName("div")[0];
        var popUpId = dragHandle.id;
        var tableViewId = popUpId.split("__")[0];
        var tableView = $find(tableViewId);
        if (tableView)
        {
            var grid = tableView._owner;
            grid._popUpLocations[popUpId] = this.style.left + "," + this.style.top;
            grid.updateClientState();
            grid.resizeModalBackground();
        }
    },

    _popUpMouseMove: function(e)
    {
        if (this.canMove)
        {
            this.style.left = e.clientX + this.originalLeft + "px";
            this.style.top = e.clientY + this.originalTop + "px";
            return false;
        }
    },

    _isRowDragged: function(e)
    {
        return $get(String.format("{0}_DraggedRows", this.get_id())) != null;
    },

    _mouseOut: function(e)
    {

    },
    _mouseDown: function(e)
    {
        if (!this._canRiseRowEvent(e)) return;

        if (this._selectedIndexes.length == 0 && this.get_allowMultiRowSelection())
        {
            return;
        }

        if (this._draggedItems)
            this._draggedItems = [];

        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");

        if (row.id == "")
            return;


        var item = this.get_masterTableView()._getRowByIndexOrItemIndexHierarchical(row)
        var ownerTableViewId = item.id.split("__")[0];
        var ownerTableView = $find(ownerTableViewId);

        if (!ownerTableView)
            return;

        var found = false;
        for (var i = 0; i < this._selectedItemsInternal.length; i++)
        {
            if (this._selectedItemsInternal[i].id == row.id)
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            if (Telerik.Web.UI.GridSelection &&
                this._selection &&
                !this.get_allowMultiRowSelection())
            {
                //temporary disable postback on row click
                var enablePostBackOnRowClickTemp = this.ClientSettings.EnablePostBackOnRowClick;
                this.ClientSettings.EnablePostBackOnRowClick = false;
                this._selection._click(e);
                this.ClientSettings.EnablePostBackOnRowClick = enablePostBackOnRowClickTemp;
            }
            else
            {
                return;
            }
        }

        this._canMoveRow = true;

        this._originalDragItem = row;

        var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(row, e);
        this.raise_rowDragStarted(args);
        if (args.get_cancel())
        {
            return;
        }
            
       // this.raise_rowDragStarted(new Telerik.Web.UI.GridDataItemEventArgs(this._overRow, e));
       
		this._draggedRow = document.createElement("div");
		this._draggedRow.id =  String.format("{0}_DraggedRows", this.get_id());
		this._draggedRow.style.position = "absolute";
		this._draggedRow.className = this.get_element().className;		
		
		var buffer = [];
		var selectedItems = ownerTableView.get_selectedItems();	
		
		for(var i = 0; i < selectedItems.length; i++)
		{
		    if (Array.contains(ownerTableView.get_dataItems(),selectedItems[i]))
		    {
		        var currRow = selectedItems[i].get_element();
    		    
		        buffer[buffer.length] =  String.format("<tr class='{0}'>", currRow.className);
		        buffer[buffer.length] = currRow.innerHTML;
		        buffer[buffer.length] = "</tr>";
		        
		        Array.add(this._draggedItems, selectedItems[i]);
		        
		    }
		}
		
		this._draggedRow.innerHTML = String.format("<table class='{0}'><tbody>{1}</tbody></table>",
		    row.parentNode.parentNode.className, buffer.join(""));

        var table = this._draggedRow.getElementsByTagName("table")[0];

        if (this._draggedRow.mergeAttributes)
        {
            this._draggedRow.mergeAttributes(this.get_element());
        }
        else
        {
            Telerik.Web.UI.Grid.CopyAttributes(this._draggedRow, this.get_element());
        }
        this._draggedRow.style.height = "";
        if (table.mergeAttributes)
        {
            table.mergeAttributes(row.parentNode.parentNode);
        }
        else
        {
            Telerik.Web.UI.Grid.CopyAttributes(table, row.parentNode.parentNode);
        }
        
        this._draggedRow.style.zIndex = 99999;
        this._draggedRow.style.display = "none";
        this._draggedRow.style.width = this.get_element().offsetWidth + "px";
        document.body.insertBefore(this._draggedRow, document.body.firstChild);

        this._createDropClue();
        if(!($telerik.isFirefox && e.button == 2 && navigator.userAgent.indexOf("Mac")))
        {
            Telerik.Web.UI.Grid.ClearDocumentEvents();
        }
        return false;
    },
    _createDropClue: function()
    {
        this._dropClue = document.createElement("div");

        document.body.appendChild(this._dropClue);

        this._dropClue.style.position = "absolute";
        this._dropClue.style.height = "5px";
    },

    _positionDropClue : function (e)
    { 
        if(this._dropClue == e.target) return;

        if (!this.get_masterTableView()) return;

       
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);       
        var destinationRow = null;
        if (currentElement)
        {              
            var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "tr");            
                      
            if (row && row.id != "")
            {
                var parentGrid = this._getParentRadGridControl(currentElement);
                if (Telerik.Web.UI.Grid.IsChildOf(currentElement, this.get_element()))
                {             
                  if (row != this._originalDragItem)
                  {
                     destinationRow = this.get_masterTableView()._getRowByIndexOrItemIndexHierarchical(row);            
                  }
                }
                else if (parentGrid)
                {
                    if (!parentGrid.get_masterTableView()) return;
                   
                    var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "tr"); 
                    destinationRow = parentGrid.get_masterTableView()._getRowByIndexOrItemIndexHierarchical(row);      
                }               
            }
        }        
       
        if(!destinationRow)
        {
            this._dropClue.style.visibility = "hidden";
            return;
        }                               
       
        this._dropClue.row = destinationRow;
       
        // Set drop clue width                       
        this._dropClue.style.width = destinationRow.offsetWidth + "px";
       
        // Set drop clue left coordinate
        var nodeContentElement = destinationRow;
        var elementPos = $telerik.getLocation(nodeContentElement);
        this._dropClue.style.left = elementPos.x + "px";                       
          
        var mousePos = this._getMousePosition(e);               
       
        this._dropClue.style.display = "";
        this._dropClue.style.visibility = "visible";
       
        if(mousePos.y < (elementPos.y + (nodeContentElement.offsetHeight / 2)))
        {   
            this._dropClue.style.top = (elementPos.y ) + "px";           
         
            if (this.Skin != "")
            {
                this._dropClue.className = String.format("GridItemDropIndicator_{0}", this.Skin);
            }
            else
            {
                this._dropClue.style.borderTop = "1px dotted black";
                this._dropClue.style["font-size"] = "3px";
                this._dropClue.style["line-height"] = "3px";
                this._dropClue.style.height = "1px";                  
            }   
            this._draggingPosition = "above";        
        }
        else
        {           
            this._dropClue.style.top = (elementPos.y + nodeContentElement.offsetHeight) + "px";          
            if (this.Skin != "")
            {
                this._dropClue.className = String.format("GridItemDropIndicator_{0}", this.Skin);
            }
            else
            {
                this._dropClue.style.borderTop = "1px dotted black";
                this._dropClue.style["font-size"] = "3px";
                this._dropClue.style["line-height"] = "3px";
                this._dropClue.style.height = "1px";           
            }
            this._draggingPosition = "below";
         }       
    },
    _getMousePosition: function(e)
    {
        var scrollOffset = $telerik.getScrollOffset(document.body, true);

        var mouseX = e.clientX;
        var mouseY = e.clientY;

        mouseX += scrollOffset.x;
        mouseY += scrollOffset.y;

        return { x: mouseX, y: mouseY };
    },

    _mouseUp: function(e)
    {
        this._canMoveRow = false;
        if(this._draggedRow)
        {              
            if (!this.get_masterTableView())
            {
                 this._clearDrag();
                 return;
            }
            
            this._draggedRow.parentNode.removeChild(this._draggedRow);
            this._draggedRow = null;

            var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
            if (currentElement)
            {
                if (currentElement == this._dropClue)
                {
                    currentElement = this._dropClue.row;
                }

                var r = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "tr");
                if (r == this._originalDragItem)
                {
                    this._clearDrag();
                    return;
                }
                var position = this._draggingPosition;
                
                if (r && r.id == "")
                {
                    r = null;
                    position = null;
                }
                    
                var dragedItems = this._draggedItems;
                var gridDataItemArgs = new Telerik.Web.UI.GridDragDropCancelEventArgs(r, e, dragedItems, currentElement, null, position);


                //                gridDataItemArgs.get_draggedItems = function()
                //                {
                //                    return dragedItems;
                //                }
                //                gridDataItemArgs.get_destinationHtmlElement = function()
                //                {
                //                    return currentElement;
                //                }  

                this.raise_rowDropping(gridDataItemArgs);
                //                
                if (!gridDataItemArgs.get_cancel())
                {

                    //get item's parent grid 
                    var parentGrid = this._getParentRadGridControl(currentElement);
                    if (parentGrid)
                    {           
                                     
                        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(currentElement, "tr");  
                        if (!row || row == this._originalDragItem || !parentGrid.get_masterTableView())
                        {                             
                            this._clearDrag();
                            return;
                        }

                        var destinationRow = row;
                        if (row.id != "")
                        {
                            destinationRow = parentGrid.get_masterTableView()._getRowByIndexOrItemIndexHierarchical(row);
                        }
                        else
                        {
                            var found = false;
                            if (parentGrid.get_masterTableView().get_element().tBodies.length > 0)
                            {
                                for (var j = 0, lenght = parentGrid.get_masterTableView().get_element().tBodies[0].rows.length; j < lenght; j++)
                                {
                                    if (row == parentGrid.get_masterTableView().get_element().tBodies[0].rows[j])
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            if (!found)
                                return;
                        }
                        var dragedItems = this._draggedItems;

                        var args = null;
                        if (destinationRow.id != "")
                        {
                            args = new Telerik.Web.UI.GridDragDropCancelEventArgs(destinationRow, e, dragedItems, null, parentGrid, this._draggingPosition);
                        }
                        else
                        {
                            args = new Telerik.Web.UI.GridDragDropCancelEventArgs(null, e, dragedItems, null, parentGrid, this._draggingPosition);
                        }


                        //                        args.get_draggedItems = function()
                        //                        {
                        //                            return dragedItems;
                        //                        }                        
                        //                        args.get_targetRadGrid = function()
                        //                        {
                        //                            return parentGrid;
                        //                        }
                        //                        args.get_destinationHtmlElement = function()
                        //                        {
                        //                            return null;
                        //                        } 

                        this.raise_rowDropped(args);

                        this._draggedItemsIndexes = [];
                        for (var i = 0, length = dragedItems.length; i < length; i++)
                        {
                            Array.add(this._draggedItemsIndexes, dragedItems[i]._itemIndexHierarchical);
                        }
                        this.updateClientState();
                        var destinationRowId = destinationRow.id.split("__")[1];
                        //                        if (destinationRowId == "")
                        //                        {
                        //                            destinationRowId = -1;
                        //                        }                        
                        var commandArgs = String.format("{0},{1},{2}", destinationRowId, parentGrid.UniqueID, this._draggingPosition);

                        this.get_masterTableView().fireCommand("RowDropped", commandArgs);

                    }
                    else
                    {                       
                        
                        var htmlElement = gridDataItemArgs.get_destinationHtmlElement();
                        var dragedItems = this._draggedItems;

                        var args = new Telerik.Web.UI.GridDragDropCancelEventArgs(null, e, dragedItems, htmlElement, null, null);


                        this.raise_rowDropped(args);

                        this._draggedItemsIndexes = [];
                        for (var i = 0, length = dragedItems.length; i < length; i++)
                        {
                            Array.add(this._draggedItemsIndexes, dragedItems[i]._itemIndexHierarchical);
                        }
                        this.updateClientState();
                        if (htmlElement.id)
                        {
                            var commandArgs = String.format("{0},{1},{2}", htmlElement.id, "","");
                        }

                        this.get_masterTableView().fireCommand("RowDroppedHtml", commandArgs);
                    }
                }
            }
            Telerik.Web.UI.Grid.RestoreDocumentEvents();
        }
        this._clearDrag();
    },

    _clearDrag: function()
    {
        if (this._dropClue)
        {
            document.body.removeChild(this._dropClue);
            this._dropClue = null;
        }
        if (this._draggedItems)
            this._draggedItems = [];
            
        this._draggingPosition = "above";
        
        //		if (this._onSelectStartDelegate)
        //		{    
        //		    //$removeHandler(document, "selectstart", this._onSelectStartDelegate);
        //		    $telerik.removeExternalHandler(document, "selectstart", this._onSelectStartDelegate);
        //		    this._onSelectStartDelegate = null;
        //		}
        Telerik.Web.UI.Grid.RestoreDocumentEvents();
    },

    _getParentRadGridControl: function(node)
    {
        while (node.parentNode)
        {
            if (node.parentNode.id && node.parentNode.id != "")
            {
                try
                {
                    var parentControl = $find(node.parentNode.id);

                    if (parentControl && Object.getType(parentControl).getName() == "Telerik.Web.UI.RadGrid")
                    {
                        return parentControl;
                    }
                }
                catch (e)
                {
                }
            }
            node = node.parentNode;
        }
        return null;
    },

    _cancelEvent: function(e)
    {
        //e.preventDefault();
        return false;
    },
    
    _mouseMove: function(e)
    {
        if (this._canMoveRow && this._draggedRow)
        {
            //this._onSelectStartDelegate = Function.createDelegate(this, this._cancelEvent);
            //$addHandler(document, "selectstart", this._onSelectStartDelegate);
            //$telerik.addExternalHandler(document, "selectstart", this._onSelectStartDelegate);
            // $addHandler(document,"selectstart", this._onSelectStartDelegate);

            this._draggedRow.style.display = "";
            this._draggedRow.style.position = "absolute";
            Telerik.Web.UI.Grid.PositionDragElement(this._draggedRow, e);
            this._positionDropClue(e);
            
            if (this.ClientSettings.Scrolling.AllowScroll && this.GridDataDiv)
            {                    
               this._autoScroll();
            }
            
            return false;
        }
    },
    
    _autoScroll : function()
    {
        var topY, bottomY;		        
	    var gridElement = this.GridDataDiv;
	    
		if (!this._draggedRow || !this.GridDataDiv)
		    return;
		    
	    var dragElementLocation = $telerik.getLocation(this._draggedRow);
		
        topY = $telerik.getLocation(gridElement).y;
        bottomY = topY + gridElement.offsetHeight;
	    
        var scrollAtTop = gridElement.scrollTop <= 0;
        var scrollAtBottom = gridElement.scrollTop >= (gridElement.scrollHeight - gridElement.offsetHeight + 16);
        var mouseDistanceToTop = dragElementLocation.y - topY;
        var mouseDistanceToBottom = bottomY - dragElementLocation.y;
		
		var grid = this;
		
        if (mouseDistanceToTop < 50 && !scrollAtTop)
        {
            var scrollSpeed = (10 - (mouseDistanceToTop / 5));
            gridElement.scrollTop = gridElement.scrollTop - scrollSpeed;	
            window.setTimeout( function() { grid._autoScroll(); }, 100);		
        }	
        else if (mouseDistanceToBottom < 50 && !scrollAtBottom)
        {
            var scrollSpeed = (10 - (mouseDistanceToBottom / 5));
            gridElement.scrollTop = gridElement.scrollTop + scrollSpeed;
            window.setTimeout( function() { grid._autoScroll(this._mousePos); }, 100);		
        }
    },
    
    dispose: function()
    {
        var modalDiv = $get(String.format("modalDivId_{0}", this.get_id()));
        if (modalDiv)
        {
            modalDiv.parentNode.removeChild(modalDiv);
        }
        if(this._onResizeDelegate)
        {
             try
             {
                $removeHandler(window, "resize", this._onResizeDelegate);
                this._onResizeDelegate  = null;
             }
             catch(e) { }
        }

        if(this._gridItemResizer)
        {
            this._gridItemResizer.dispose();
        }

        var _popUpIdsData = eval(this._popUpIds);
        for (var i = 0; i < _popUpIdsData.length; i++)
        {
            var el = $get(_popUpIdsData[i]);
            if(el)
            {
                var divs = el.getElementsByTagName("div");
                if(divs.length > 0)
                {
                    $clearHandlers(divs[0]);
                }
            }
        }
        if (this._isAjaxRequest)
        {

            //            for(var i = 0; i < _popUpIdsData.length; i++)
            //            {
            //                var popUpId = _popUpIdsData[i];
            //                var popUp = $find(popUpId);
            //                if(popUp)
            //                {
            //                    var el  = popUp.get_element();
            //                    popUp.dispose();
            //                    this._destroyTree(el);
            //                    el.parentNode.removeChild(el);
            //                }
            //            }
        }

        this.raise_gridDestroying(new Sys.EventArgs());

        $clearHandlers(this.get_element());

        if (this._selection)
        {
            this._selection.dispose();
        }

        if (this._scrolling)
        {
            this._scrolling.dispose();
        }

        if (this._filterMenu)
        {
            if (this._onFilterMenuClick)
            {
                this._filterMenu.remove_itemClicked(this._onFilterMenuClicking);
                this._filterMenu.remove_itemClicked(this._onFilterMenuClick);
            }
            this._filterMenu = null;
        }

        if (Sys.WebForms && Sys.WebForms.PageRequestManager)
        {
            var requestManager = Sys.WebForms.PageRequestManager.getInstance();
            if (this._initializeRequestHandler)
            {
                requestManager.remove_initializeRequest(this._initializeRequestHandler);
            }
        }
        
        if(this.GridDataDiv)
            $clearHandlers(this.GridDataDiv);
            
        if(this.GridHeaderDiv)
            $clearHandlers(this.GridHeaderDiv);
            
        if(this.GridFooterDiv)
            $clearHandlers(this.GridFooterDiv);

        if(this._groupPanel && this._groupPanel.get_element())
            $clearHandlers(this._groupPanel.get_element());

        this._draggedItems = null;
        this.Control = null;
        this.GridDataDiv = null;
        this.GridHeaderDiv = null;
        this.GridFooterDiv = null;
        this.PagerControl = null;
        this.TopPagerControl = null;

        this.MasterTableView = null;
        this.MasterTableViewHeader = null;
        this.MasterTableViewFooter = null;

        //this._onSelectStartDelegate = null;

        Telerik.Web.UI.RadGrid.callBaseMethod(this, 'dispose');
    },

    _destroyTree: function(element)
    {
        if (element.nodeType === 1)
        {
            var childNodes = element.childNodes;
            for (var i = childNodes.length - 1; i >= 0; i--)
            {
                var node = childNodes[i];
                if (node.nodeType === 1)
                {
                    if (node.dispose && typeof (node.dispose) === "function")
                    {
                        node.dispose();
                    }
                    else if (node.control && typeof (node.control.dispose) === "function")
                    {
                        node.control.dispose();
                    }
                    var behaviors = Sys.UI.Behavior.getBehaviors(node);
                    for (var j = behaviors.length - 1; j >= 0; j--)
                    {
                        behaviors[j].dispose();
                    }
                    this._destroyTree(node);
                }
            }
        }
    },

    _initializeRequest: function(sender, args)
    {
        if (Telerik.Web.UI.Grid.IsChildOf(args.get_postBackElement(), this.get_element()) ||
            args.get_postBackElement() == this.get_element())
        {
            var label = $get(this._statusLabelID);
            if (label)
            {
                label.innerHTML = this._loadingText;
            }
            this._isAjaxRequest = true;
        }
    },

    get_selectedItemsInternal: function()
    {
        return this._selectedItemsInternal;
    },
    set_selectedItemsInternal: function(value)
    {
        if (this._selectedItemsInternal != value)
        {
            this._selectedItemsInternal = value;
        }
    },

    get_allowMultiRowSelection: function()
    {
        return this.AllowMultiRowSelection;
    },
    set_allowMultiRowSelection: function(value)
    {
        if (this.AllowMultiRowSelection != value)
        {
            this.AllowMultiRowSelection = value;
        }
    },

    get_masterTableView: function()
    {
        return $find(this._masterClientID);
    },

    get_masterTableViewHeader: function()
    {
        return $find(this._masterClientID + "_Header");
    },

    get_masterTableViewFooter: function()
    {
        return $find(this._masterClientID + "_Footer");
    },


    get_selectedItems: function()
    {
        var selectedItems = [];

        for (var i = 0; i < this._selectedItemsInternal.length; i++)
        {
            Array.add(selectedItems, $find(this._selectedItemsInternal[i].id));
        }

        return selectedItems;
    },

    clearSelectedItems: function()
    {
        if (this._selectedItemsInternal.length > 0)
        {
            var i = this._selectedItemsInternal.length - 1;
            while (i >= 0)
            {
                var item = $find(this._selectedItemsInternal[i].id);
                if (item)
                {
                    item.set_selected(false);
                }
                else
                {
                    this._owner._selection._selectRowInternal($get(this._selectedItemsInternal[i].id), { "ctrlKey": false }, true, true, true)
                }
                i--;
            }
        }
    },

    _initializeTableViews: function()
    {
        var _gridTableViewsDataInternal = eval(this._gridTableViewsData);
        for (var i = 0; i < _gridTableViewsDataInternal.length; i++)
        {
            var data = _gridTableViewsDataInternal[i];

            if (!data.ClientID)
                continue;

            if ($find(data.ClientID) != null)
                continue;

            if ($get(data.ClientID) == null)
                continue;

            if (this._masterClientID != data.ClientID)
            {
                this.raise_tableCreating(new Sys.EventArgs());
            }

            var tableView = $create(
                    Telerik.Web.UI.GridTableView,
            {
                _owner: this,
                _data: data
            },
                    null,
                    null,
                    $get(data.ClientID)
            );

            if (this._masterClientID != data.ClientID)
            {
                var args = new Sys.EventArgs();
                args.get_tableView = function()
                {
                    return tableView;
                }

                Array.add(this._detailTables, tableView);

                this.raise_tableCreated(args);
            }

            if (this._masterClientID == data.ClientID)
            {
                this.raise_masterTableViewCreating(new Sys.EventArgs());

                this.MasterTableView = tableView;

                this.raise_masterTableViewCreated(new Sys.EventArgs());

                if ($get(data.ClientID + "_Header"))
                {
                    this.MasterTableViewHeader = $create(
                        Telerik.Web.UI.GridTableView,
                    {
                        _owner: this,
                        _data: data
                    },
                        null,
                        null,
                        $get(data.ClientID + "_Header")
                    );

                    this.MasterTableView._columnsInternal = this.MasterTableViewHeader._columnsInternal;
                }

                if ($get(data.ClientID + "_Footer"))
                {
                    this.MasterTableViewFooter = $create(
                        Telerik.Web.UI.GridTableView,
                    {
                        _owner: this,
                        _data: data
                    },
                        null,
                        null,
                        $get(data.ClientID + "_Footer")
                    );
                }
            }

        }
    },

    get_detailTables: function()
    {
        return this._detailTables;
    },

    _initializeEvents: function(events)
    {
        if (events)
        {
            var thisObject = this;
            for (var i = 0, l = events.length; i < l; i++)
            {
                var name = events[i];

                this["add_" + name] = function(eventName)
                {
                    return function(eventHandler)
                    {
                        this.get_events().addHandler(eventName, eventHandler);
                    };
                } (name);

                this["remove_" + name] = function(eventName)
                {
                    return function(eventHandler)
                    {
                        this.get_events().removeHandler(eventName, eventHandler);
                    };
                } (name);

                this["raise_" + name] = function(eventName)
                {
                    return function(args)
                    {
                        this.raiseEvent(eventName, args);
                    };
                } (name);
            }
        }
    },

    _selectAllRows: function(tableViewUniqueID, itemIndex, e)
    {
        var el = (e.srcElement) ? e.srcElement : e.target;
        var tableView = $find(Telerik.Web.UI.Grid._uniqueIDToClientID(tableViewUniqueID));
        var table = tableView.get_element();
        var selectAllCheckBoxChecked = (el.checked) ? true : false;

        for (var i = 0, length = table.rows.length; i < length; i++)
        {
            var row = table.rows[i];
            if (!row.id)
                continue;

            //does not save client state on every call as this cause overhead with more rows
            this._selection._selectRowInternal(row, e, true, false, false, selectAllCheckBoxChecked);
        }
        if (table.rows.length > 0)
            this.updateClientState(); // explicitly save client state
    },

    _showFilterMenu: function(tableViewUniqueID, uniqueName, e)
    {
        var tableView = $find(Telerik.Web.UI.Grid._uniqueIDToClientID(tableViewUniqueID));
        var column = tableView.getColumnByUniqueName(uniqueName);

        var filterMenu = this._getFilterMenu();
        if (this._filterMenu)
        {
            var menu = this._filterMenu;
            var args = new Sys.CancelEventArgs();
            args.get_menu = function()
            {
                return menu;
            }
            args.get_tableView = function()
            {
                return tableView;
            }
            args.get_column = function()
            {
                return column;
            }
            args.get_domEvent = function()
            {
                return e;
            }
            this.raise_filterMenuShowing(args);

            if (args.get_cancel())
            {
                return;
            }
             
            this._buildFilterMenuItemList(this._filterMenu, column._data.FilterListOptions, column._data.DataTypeName, column._data.CurrentFilterFunction, column);

            this._onFilterMenuClick = Function.createDelegate(this, this._filterMenuClickHandler);
            this._filterMenu.add_itemClicked(this._onFilterMenuClick);

            this._onFilterMenuClicking = Function.createDelegate(this, this._filterMenuClickingHandler);
            this._filterMenu.add_itemClicking(this._onFilterMenuClicking);

            this._filterMenu.show(e);
        }

    },

    _getFilterMenu: function()
    {
        if (Telerik.Web.UI.RadContextMenu && !this._filterMenu)
        {
            this._filterMenu = $find(this.ClientID + "_rfltMenu");
        }
        return this._filterMenu;
    },

    _filterMenuClickingHandler: function(sender, eventArgs)
    {
        var tableViewUniqueID = eventArgs.get_item()._filterMenu_tableID;
        var tableView = $find(Telerik.Web.UI.Grid._uniqueIDToClientID(tableViewUniqueID));

        if (tableView != null)
        {
            var filterFunction = eventArgs.get_item().get_value();
            var columnUniqueName = eventArgs.get_item()._filterMenu_column_uniqueName;
            var filterRow = tableView._getTableFilterRow()
            var index = tableView._getCellIndexByColumnUniqueNameFromTableRowElement(filterRow, columnUniqueName);

            var filterInput = filterRow.cells[index].getElementsByTagName("input")[0];
            var filterValue = filterInput.value;

            var column = tableView.getColumnByUniqueName(columnUniqueName);
            
            if(column && column._data.ColumnType == "GridDateTimeColumn")
            {
                var datePicker = $find(filterInput.id);
                if(datePicker && 
                    (
                       Object.getType(datePicker).getName() == "Telerik.Web.UI.RadDateTimePicker" ||
                       Object.getType(datePicker).getName() == "Telerik.Web.UI.RadDatePicker"
                    )
                   )
                {
                    filterValue = datePicker.get_dateInput().get_value();
                }
            }
            
            if(column && column._data.ColumnType == "GridNumericColumn")
            {
                var control = $find(filterInput.id.replace("_text", ""));
                if(control && Object.getType(control).getName() == "Telerik.Web.UI.RadNumericTextBox")
                {
                    filterValue = control.get_value();
                }
            }

            if (filterInput.type == "checkbox")
            {
                filterValue = filterInput.checked;
            }

            if (filterFunction == "NoFilter")
            {
                if (filterInput.type == "checkbox")
                {
                    filterInput.checked = false;
                }
                else
                {
                    filterInput.value = "";
                }
            }
            else
            {
                if (filterValue == "" &&
                   filterInput.type != "checkbox" &&
                    (filterFunction != "IsEmpty" &&
                    filterFunction != "NotIsEmpty" &&
                    filterFunction != "IsNull" &&
                    filterFunction != "NotIsNull"))
                {
//                    alert("No filter value!");
                    sender.hide();
                    return;
                }
            }

            if (!tableView.filter(columnUniqueName, filterValue, filterFunction))
            {
                eventArgs.set_cancel(true);
                this._filterMenu.remove_itemClicking(this._onFilterMenuClicking);
            }

            sender.hide();
        }
    },

    _filterMenuClickHandler: function(sender, eventArgs)
    {
        var item = eventArgs.get_item();
        if (item)
        {
            var menu = sender;

            menu.trackChanges();
            item.get_attributes().setAttribute("columnUniqueName", item._filterMenu_column_uniqueName);
            item.get_attributes().setAttribute("tableID", item._filterMenu_tableID);
            menu.commitChanges();
        }
    },
    _buildFilterMenuItemList: function(menu, filterListOptions, dataTypeName, currentFilterFunction, column)
    {
        for (var i = 0; i < menu.get_items().get_count(); i++)
        {
            var item = menu.get_items().getItem(i);
    
            item._filterMenu_column_uniqueName = column.get_uniqueName();
            item._filterMenu_tableID = column._owner._data.UniqueID;

            if (dataTypeName == "System.Boolean")
            {
                if ((item.get_value() == "GreaterThan") ||
			        (item.get_value() == "LessThan") ||
			        (item.get_value() == "GreaterThanOrEqualTo") ||
			        (item.get_value() == "LessThanOrEqualTo") ||
			        (item.get_value() == "Between") ||
			        (item.get_value() == "NotBetween"))
                {
                    item.set_visible(false);
                    continue;
                }
            }

            if (dataTypeName != "System.String")
            {
                if ((item.get_value() == "StartsWith") ||
			        (item.get_value() == "EndsWith") ||
			        (item.get_value() == "Contains") ||
			        (item.get_value() == "DoesNotContain") ||
			        (item.get_value() == "IsEmpty") ||
			        (item.get_value() == "NotIsEmpty"))
                {
                    item.set_visible(false);
                    continue;
                }
            }

            if (filterListOptions == 0)
            {
                if (item.get_value() == "Custom")
                {
                    item.set_visible(false);
                    continue;
                }
            }

            if ((column._data.ColumnType == "GridDateTimeColumn" ||
	            column._data.ColumnType == "GridMaskedColumn" ||
	            column._data.ColumnType == "GridNumericColumn") &&
	                ((item.get_value() == "Between") ||
			        (item.get_value() == "NotBetween")))
            {
                item.set_visible(false);
                continue;
            }

            if (item.get_value() == column._data.CurrentFilterFunctionName)
            {
                item._focused = true;
                item._updateLinkClass();
            }
            else
            {
                item._focused = false;
                item._updateLinkClass();
            }
            item.set_visible(true);
        }

    },
    saveClientState: function()
    {
        var state = {};

        state["selectedIndexes"] = this._selectedIndexes;
        state["reorderedColumns"] = this._reorderedColumns;
        state["expandedItems"] = this._expandedItems;
        state["expandedGroupItems"] = this._expandedGroupItems;

        if (this._expandedFilterItems)
        {
            state["expandedFilterItems"] = this._expandedFilterItems;
        }

        state["deletedItems"] = this._deletedItems;

        if (this._resizedColumns != "")
        {
            state["resizedColumns"] = this._resizedColumns;
        }

        if (this._resizedControl != "")
        {
            state["resizedControl"] = this._resizedControl;
        }

        if (this._resizedItems != "")
        {
            state["resizedItems"] = this._resizedItems;
        }

        if (this._hidedItems != "")
        {
            state["hidedItems"] = this._hidedItems;
        }

        if (this._showedItems != "")
        {
            state["showedItems"] = this._showedItems;
        }

        if (this._hidedColumns != "")
        {
            state["hidedColumns"] = this._hidedColumns;
        }

        if (this._showedColumns != "")
        {
            state["showedColumns"] = this._showedColumns;
        }

        if (this._activeRow)
        {
            state["activeRowIndex"] = this._activeRow.id;
        }

        if (this._gridDataDiv)
        {
            state["scrolledPosition"] = this._gridDataDiv.scrollTop + "," + this._gridDataDiv.scrollLeft;
        }

        if (this._popUpLocations)
        {
            state["popUpLocations"] = this._popUpLocations;
        }

        if (this._draggedItemsIndexes)
        {
            state["draggedItemsIndexes"] = this._draggedItemsIndexes;
        }

        return Sys.Serialization.JavaScriptSerializer.serialize(state);
    },

    _attachDomEvents: function()
    {
        this._onKeyDownDelegate = Function.createDelegate(this, this._onKeyDownHandler);
        this._onKeyPressDelegate = Function.createDelegate(this, this._onKeyPressHandler);
        this._onMouseMoveDelegate = Function.createDelegate(this, this._onMouseMoveHandler);

        $addHandler(this.get_element(), "keydown", this._onKeyDownDelegate);
        $addHandler(this.get_element(), "keypress", this._onKeyPressDelegate);
        $addHandler(this.get_element(), "mousemove", this._onMouseMoveDelegate);
    },

    _onMouseMoveHandler: function(e)
    {
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);

        if (this.ClientSettings && this.ClientSettings.Resizing.AllowRowResize)
        {
            if(this._gridItemResizer == null)
            {
                this._gridItemResizer = new Telerik.Web.UI.GridItemResizer(this);
            }
            this._gridItemResizer._detectResizeCursorsOnItems(e, currentElement);
            this._gridItemResizer._moveItemResizer(e);
        }
    },

    _onKeyDownHandler: function(e)
    {
        // IE treats arrow keys as modifiers (Ctrl, Alt, Shift) => no keypress is fired
        var arrowKeyPressed = (e.keyCode >= 37 && e.keyCode <= 40);
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && arrowKeyPressed)
        {
            this._raiseKeyPressInternal(e);
        }
    },

    _onKeyPressHandler: function(e)
    {
        this._raiseKeyPressInternal(e);
    },

    _raiseKeyPressInternal: function(e)
    {
        var args = new Telerik.Web.UI.GridKeyPressEventArgs(e);
        this.raise_keyPress(args);

        if (args.get_cancel())
        {
            return;
        }

        this._handleGridKeyboardAction(e);
    },

    _handleGridKeyboardAction: function(e)
    {
        var keyCode = e.keyCode || e.charCode;
        if (this.ClientSettings && this.ClientSettings.AllowKeyboardNavigation)
        {
            var rowNavigationInProgress = (keyCode == 38 || keyCode == 40);
            var rowSelectionInProgress = (keyCode == 32 && this.ClientSettings.Selecting && this.ClientSettings.Selecting.AllowRowSelect);
            var enterEditModeInProgress = (keyCode == 13);
            var expandCollapseInProgress = (keyCode == 37 || keyCode == 39);

            if (rowNavigationInProgress)
            {
                this._handleActiveRowNavigation(e);
            }
            else if (expandCollapseInProgress)
            {
                this._handleActiveRowExpandCollapse(e);
            }
            else if (rowSelectionInProgress)
            {
                this._handleActiveRowSelection(e);
            }
            else if (enterEditModeInProgress)
            {
                this._handleActiveRowEdit(e);
            }
        }
    },

    _handleActiveRowNavigation: function(e)
    {
        var keyCode = e.keyCode || e.charCode;
        var currentElement = Telerik.Web.UI.Grid.GetCurrentElement(e);
        if (currentElement != null && currentElement.tagName &&
	        (currentElement.tagName.toLowerCase() == "input" || currentElement.tagName.toLowerCase() == "textarea"))
        {
            return;
        }

        var nextActiveRow = null;
        if (this._activeRow)
        {
            nextActiveRow = this._getNextActiveRow(this._activeRow, keyCode);
        }
        else
        {
            nextActiveRow = this.get_masterTableView()._getFirstDataRow();
        }

        if (!nextActiveRow)
        {
            return;
        }

        this._setActiveRow(nextActiveRow, e);
        e.preventDefault();
    },

    _setActiveRow: function(row, domEvent)
    {
        if (row && this.ClientSettings && this.ClientSettings.AllowKeyboardNavigation)
        {
            var args = new Telerik.Web.UI.GridDataItemCancelEventArgs(this._activeRow, domEvent);
            this.raise_activeRowChanging(args);
            if (args.get_cancel())
            {
                return;
            }

            if (this._activeRow)
            {
                var oldTableView = $find(this._activeRow.id.split("__")[0]);
                Telerik.Web.UI.Grid.ClearItemStyle(this._activeRow, oldTableView._data._renderActiveItemStyle, oldTableView._data._renderActiveItemStyleClass);
            }

            this._activeRow = row;

            var newTableView = $find(row.id.split("__")[0]);
            Telerik.Web.UI.Grid.SetItemStyle(row, newTableView._data._renderActiveItemStyle, newTableView._data._renderActiveItemStyleClass);
            Telerik.Web.UI.Grid.ScrollIntoView(row);

            this.updateClientState();

            this.raise_activeRowChanged(new Telerik.Web.UI.GridDataItemEventArgs(this._activeRow, domEvent));
        }
    },

    set_activeRow: function(row)
    {
        this._setActiveRow(row, null);
    },

    _handleActiveRowExpandCollapse: function(e)
    {
        var keyCode = e.keyCode || e.charCode;
        if (!this._activeRow) return;
        var tableView = $find(this._activeRow.id.split("__")[0]);
        if (keyCode == 37) // left arrow
        {
            var nestedRow = tableView._getNextNestedDataRow(this._activeRow);
            if (nestedRow && nestedRow.parentNode.style.display != "none") // expanded hierarchy
            {
                tableView.collapseItem(this._activeRow);
            }
        }
        else if (keyCode == 39) // right arrow
        {
            var nextTableRow = Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName(this._activeRow, "tr");
            if (nextTableRow && nextTableRow.style.display == "none") // collapsed hierarchy
            {
                tableView.expandItem(this._activeRow);
            }
        }
    },

    _handleActiveRowSelection: function(e)
    {
        if (this._activeRow)
        {
            this._selection._selectRowInternal(this._activeRow, { "ctrlKey": this.get_allowMultiRowSelection() }, false, true, true);
            e.preventDefault();
        }
    },

    _handleActiveRowEdit: function(e)
    {
        if (this._activeRow)
        {
            e.preventDefault();

            var tableView = $find(this._activeRow.id.split("__")[0]);
            if (tableView)
            {
                tableView.editItem(this._activeRow);
            }
        }
    },

    _getNextActiveRow: function(currentRow, keyCode)
    {
        var nextActiveRow = null;
        var nestedTableView = null;
        var tableView = $find(currentRow.id.split("__")[0]);
        var isMasterTableView = (this.get_masterTableView().get_id() == tableView.get_id());

        if (keyCode == 38) //Up arrow
        {
            // check the previous item for expanded hierarchy --> need to activate the last hierarchical row in this case
            var previousDataRow = tableView._getPreviousDataRow(currentRow);
            if (previousDataRow)
            {
                var previousTableRow = Telerik.Web.UI.Grid.GetNodePreviousSiblingByTagName(currentRow, "tr");
                if (previousTableRow && previousTableRow.style.display != "none")
                {
                    nestedTableView = Telerik.Web.UI.Grid.GetLastNestedTableView(previousDataRow);
                    if (nestedTableView)
                    {
                        nextActiveRow = nestedTableView._getLastDataRow();
                    }
                }
            }

            // if not -- try to activate the previous item in the current tableview
            if (!nextActiveRow)
            {
                nextActiveRow = tableView._getPreviousDataRow(currentRow);

                // if not -- try to activate the last item in the previous sibling tableview (multiple tables at the same level)
                if (!nextActiveRow && !isMasterTableView)
                {
                    var siblingTable = Telerik.Web.UI.Grid.GetNodePreviousSiblingByTagName(tableView.get_element(), "table");
                    if (siblingTable)
                    {
                        siblingTableView = $find(siblingTable.id.split("__")[0]);
                        if (siblingTableView)
                        {
                            nextActiveRow = siblingTableView._getLastDataRow();
                        }
                    }
                }

                // if not -- try to activate the parent item for the current tableview
                if (!nextActiveRow && !isMasterTableView)
                {
                    nextActiveRow = tableView.get_parentRow();
                }
            }
        }
        else if (keyCode == 40) // Down Arrow
        {
            // check the current item for expanded hierarchy --> need to activate the first hierarchical row in this case
            var nextTableRow = Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName(currentRow, "tr");
            if (nextTableRow && nextTableRow.style.display != "none")
            {
                nestedTableView = Telerik.Web.UI.Grid.GetNestedTableView(currentRow);
                if (nestedTableView)
                {
                    nextActiveRow = nestedTableView._getNextNestedDataRow(currentRow);
                }
            }

            // if not -- try to activate the next item in the current tableview
            if (!nextActiveRow)
            {
                nextActiveRow = tableView._getNextDataRow(currentRow);

                // if not -- try to activate the first item in the next sibling tableview (multiple tables at the same level)
                if (!nextActiveRow && !isMasterTableView)
                {
                    var siblingTable = Telerik.Web.UI.Grid.GetNodeNextSiblingByTagName(tableView.get_element(), "table");
                    if (siblingTable)
                    {
                        siblingTableView = $find(siblingTable.id.split("__")[0]);
                        if (siblingTableView)
                        {
                            nextActiveRow = siblingTableView._getFirstDataRow();
                        }
                    }
                }

                // if not -- try to activate the next sibling-item for the parent of the current item
                if (!nextActiveRow && !isMasterTableView)
                {
                    var parentView = tableView.get_parentView();
                    if (parentView)
                    {
                        var parentRow = tableView.get_parentRow();
                        nextActiveRow = parentView._getNextDataRow(parentRow);
                    }
                }
            }
        }

        return nextActiveRow;
    },

    _click: function(e)
    {
        if (!this._canRiseRowEvent(e)) return;

        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        if (row && row.id != "" && row.id.split("__").length == 2)
        {
            this.raise_rowClick(new Telerik.Web.UI.GridDataItemEventArgs(row, e));
        }
    },

    _dblclick: function(e)
    {
        if (!this._canRiseRowEvent(e)) return;

        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        if (row && row.id != "")
        {
            this.raise_rowDblClick(new Telerik.Web.UI.GridDataItemEventArgs(row, e));
        }
    },

    _contextmenu: function(e)
    {
        //if(!this._canRiseRowEvent(e)) return;

        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        var args = null;
        
        if(row && row.id != "" && row.id.split("__").length == 2)
        {
            args = new Telerik.Web.UI.GridDataItemCancelEventArgs(row, e)
            this.raise_rowContextMenu(args);
        }

        if((args && !args.get_cancel()) && this.get_events().getHandler("rowContextMenu"))
        {
            if (e.preventDefault)
            {
                e.preventDefault();
            }
            else
            {
                e.returnValue = false;
                return false;
            }
        }
    },

    _mouseover: function(e)
    {
        if (this._overRow)
        {
            this.raise_rowMouseOut(new Telerik.Web.UI.GridDataItemEventArgs(this._overRow, e));

            if (this.Skin != "" && this.ClientSettings.EnableRowHoverStyle)
            {
                Sys.UI.DomElement.removeCssClass(this._overRow, "GridRowOver_" + this.Skin);
            }
        }

        var row = Telerik.Web.UI.Grid.GetFirstParentByTagName(Telerik.Web.UI.Grid.GetCurrentElement(e), "tr");
        if (row && row.id != "" && row.id.split("__").length == 2)
        {
            this.raise_rowMouseOver(new Telerik.Web.UI.GridDataItemEventArgs(row, e));

            if (this.Skin != "" && this.ClientSettings.EnableRowHoverStyle)
            {
                Sys.UI.DomElement.addCssClass(row, "GridRowOver_" + this.Skin);
            }

            this._overRow = row;
        }
    },

    _mouseout: function(e)
    {
        if (this._overRow)
        {
            this.raise_rowMouseOut(new Telerik.Web.UI.GridDataItemEventArgs(this._overRow, e));

            if (this.Skin != "" && this.ClientSettings.EnableRowHoverStyle)
            {
                Sys.UI.DomElement.removeCssClass(this._overRow, "GridRowOver_" + this.Skin);
            }
        }
        this._overRow = null;
    },

    _canRiseRowEvent: function(e)
    {
        var el = Telerik.Web.UI.Grid.GetCurrentElement(e);
        if (!el ||
            !el.tagName ||
            el.tagName.toLowerCase() == "input" ||
            el.tagName.toLowerCase() == "select" ||
            el.tagName.toLowerCase() == "option" ||
            el.tagName.toLowerCase() == "button" ||
            el.tagName.toLowerCase() == "a" ||
            el.tagName.toLowerCase() == "textarea" ||
            el.tagName.toLowerCase() == "img"
            )
            return false;

        if (this.get_masterTableView() && !Telerik.Web.UI.Grid.IsChildOf(el, this.get_masterTableView().get_element()))
            return false;


        return true;
    },

    confirm: function(text, e, title, width, height)
    {
        if (window.confirmResult)
        {
            window.confirmResult = false;
            return true;
        }

        if (typeof (GetRadWindowManager) == "undefined")
        {
            return confirm(text);
        }

        var radWindowManager = GetRadWindowManager();

        if (!radWindowManager)
        {
            return confirm(text);
        }

        var el = e.srcElement ? e.srcElement : e.target;

        var confirmWindow = radWindowManager._getStandardPopup("confirm", text);

        if (typeof (title) == "undefined")
        {
            title = "Confirm";
        }

        if (typeof (width) == "undefined")
        {
            width = 280;
        }

        if (typeof (height) == "undefined")
        {
            height = 200;
        }

        confirmWindow.set_title(title);
        confirmWindow.setSize(width, height);
        confirmWindow.show();
        confirmWindow.center();

        confirmWindow.callBack = function(result)
        {
            confirmWindow.close();
            confirmWindow.callBack = null;

            if (result)
            {
                window.confirmResult = true;

                if (window.netscape && el.href)
                {
                    eval(el.href);
                    window.confirmResult = false;
                    return;
                }

                if (window.netscape && el.type &&
                    (el.type.toLowerCase() == "image" || el.type.toLowerCase() == "submit" ||
                    el.type.toLowerCase() == "button"))
                {
                    __doPostBack(el.name, "");

                    window.confirmResult = false;
                    return;
                }

                if (el.click) el.click(e);
            }

            return false;
        };

        return false;
    }
};

Telerik.Web.UI.RadGrid.registerClass('Telerik.Web.UI.RadGrid', Telerik.Web.UI.RadWebControl);

Telerik.Web.UI.GridKeyPressEventArgs = function(domEvent)
{
    Telerik.Web.UI.GridKeyPressEventArgs.initializeBase(this);
    
    // we are firing the keypress event from the keydown handler
    // for arrow keys in IE (treats them as modifier keys)
    this._keyCode = domEvent.keyCode || domEvent.charCode;
    this._isShiftPressed = domEvent.shiftKey;
    this._isCtrlPressed = domEvent.ctrlKey;
    this._isAltPressed = domEvent.altKey;
    this._domEvent = domEvent;
}

Telerik.Web.UI.GridKeyPressEventArgs.prototype = 
{
    get_keyCode : function()
    {
        return this._keyCode;
    },
    
    get_isShiftPressed : function()
    {
        return this._isShiftPressed;
    },
    
    get_isCtrlPressed : function()
    {
        return this._isCtrlPressed;
    },
    
    get_isAltPressed : function()
    {
        return this._isAltPressed;
    },
    
    get_domEvent : function()
    {
        return this._domEvent;
    }
};

Telerik.Web.UI.GridKeyPressEventArgs.registerClass("Telerik.Web.UI.GridKeyPressEventArgs", Sys.CancelEventArgs);

Telerik.Web.UI.GridDragDropCancelEventArgs = function(rowElement, domEvent, dragedItems, htmlElement, targetRadGrid, dropPosition)
{
    Telerik.Web.UI.GridDragDropCancelEventArgs.initializeBase(this);
    
    this._targetItemId = "";
	this._targetItemIndexHierarchical = "";
	this._targetGridDataItem = null;
	this._targetItemTableView = null;
	this._targetItemDataKeyValues = null;
	
	if (rowElement)
	{
	    this._targetItemId = rowElement.id;
	    this._targetItemIndexHierarchical = this._targetItemId.split("__")[1];
	    this._targetGridDataItem = $find(this._targetItemId);
	    this._targetItemTableView = $find(this._targetItemId.split("__")[0]);
	    
	    if(this._targetItemTableView && this._targetItemTableView._owner._clientKeyValues &&
	    this._targetItemTableView._owner._clientKeyValues[this._targetItemIndexHierarchical])
	    {
	        this._targetItemDataKeyValues = this._targetItemTableView._owner._clientKeyValues[this._targetItemIndexHierarchical];
	    }
	}
	
	this._domEvent = domEvent;
	this._dragedItems = dragedItems;
	this._htmlElement = htmlElement;
	this._targetRadGrid = targetRadGrid;
	this._dropPosition = dropPosition;
}

Telerik.Web.UI.GridDragDropCancelEventArgs.prototype = 
{
    get_targetGridDataItem : function ()
	{
		return this._targetGridDataItem;
	},

	get_targetItemIndexHierarchical : function ()
	{
		return this._targetItemIndexHierarchical;
	},

	get_targetItemId : function ()
	{
		return this._targetItemId;
	},
	
    get_targetItemTableView : function ()
	{
		return this._targetItemTableView;
	},

	get_domEvent : function ()
	{
		return this._domEvent;
	},
	
    get_TargetDataKeyValue : function (columnName)
	{
		return (this._targetItemDataKeyValues)? this._targetItemDataKeyValues[columnName] : null;
	},	
	get_draggedItems : function()
    {
        return this._dragedItems;
    },
    get_destinationHtmlElement : function()
    {
        return this._htmlElement;
    },
    set_destinationHtmlElement : function(value)
    {
        this._htmlElement = value;
    },
    get_targetRadGrid : function()
    {
        return this._targetRadGrid;
    },
    get_dropPosition : function()
    {
        return this._dropPosition;
    }
};

Telerik.Web.UI.GridDragDropCancelEventArgs.registerClass("Telerik.Web.UI.GridDragDropCancelEventArgs", Sys.CancelEventArgs);

Telerik.Web.UI.GridDataItemEventArgs = function(rowElement, domEvent) 
{
	Telerik.Web.UI.GridDataItemEventArgs.initializeBase(this);

    this._id = "";
    this._itemIndexHierarchical = "";
    this._gridDataItem = null;
    this._tableView = null;
    this._dataKeyValues = null;
    
    if (rowElement)
    {
	    this._id = rowElement.id;
	    this._itemIndexHierarchical = this._id.split("__")[1];
	    this._gridDataItem = $find(this._id);
	    this._tableView = $find(this._id.split("__")[0]);
	    
	    if(this._tableView && this._tableView._owner._clientKeyValues &&
	    this._tableView._owner._clientKeyValues[this._itemIndexHierarchical])
	    {
	        this._dataKeyValues = this._tableView._owner._clientKeyValues[this._itemIndexHierarchical];
	    }
	}
	
	this._domEvent = domEvent;
};

Telerik.Web.UI.GridDataItemEventArgs.prototype = 
{
	get_gridDataItem : function ()
	{
		return this._gridDataItem;
	},

	get_itemIndexHierarchical : function ()
	{
		return this._itemIndexHierarchical;
	},

	get_id : function ()
	{
		return this._id;
	},
	
    get_tableView : function ()
	{
		return this._tableView;
	},

	get_domEvent : function ()
	{
		return this._domEvent;
	},

    getDataKeyValue : function (columnName)
	{
		return (this._dataKeyValues)? this._dataKeyValues[columnName] : null;
	}
};

Telerik.Web.UI.GridDataItemEventArgs.registerClass("Telerik.Web.UI.GridDataItemEventArgs", Sys.EventArgs);


Telerik.Web.UI.GridDataItemCancelEventArgs = function(rowElement, domEvent) 
{
	Telerik.Web.UI.GridDataItemCancelEventArgs.initializeBase(this);
	
	this._id = "";
	this._itemIndexHierarchical = "";
	this._gridDataItem = null;
	this._tableView = null;
	this._dataKeyValues = null;
	
	if (rowElement)
	{
	    this._id = rowElement.id;
	    this._itemIndexHierarchical = this._id.split("__")[1];
	    this._gridDataItem = $find(this._id);
	    this._tableView = $find(this._id.split("__")[0]);
	    
	    if(this._tableView && this._tableView._owner._clientKeyValues &&
	        this._tableView._owner._clientKeyValues[this._itemIndexHierarchical])
	    {
	        this._dataKeyValues = this._tableView._owner._clientKeyValues[this._itemIndexHierarchical];
	    }
	}
	
	this._domEvent = domEvent;
};

Telerik.Web.UI.GridDataItemCancelEventArgs.prototype = 
{
	get_gridDataItem : function ()
	{
		return this._gridDataItem;
	},

	get_itemIndexHierarchical : function ()
	{
		return this._itemIndexHierarchical;
	},

	get_id : function ()
	{
		return this._id;
	},
	
    get_tableView : function ()
	{
		return this._tableView;
	},

	get_domEvent : function ()
	{
		return this._domEvent;
	},
	
    getDataKeyValue : function (columnName)
	{
		return (this._dataKeyValues)? this._dataKeyValues[columnName] : null;
	}

};

Telerik.Web.UI.GridDataItemCancelEventArgs.registerClass("Telerik.Web.UI.GridDataItemCancelEventArgs", Sys.CancelEventArgs);;
/* END Telerik.Web.UI.Grid.RadGridScripts.js */
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
(function() {var fn = function() {$get('RadScriptManager1_HiddenField').value += ';;System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35:zh-CN:1f0f78f9-0731-4ae9-b308-56936732ccb8:52817a7d;Telerik.Web.UI, Version=2008.2.1001.0, Culture=neutral, PublicKeyToken=29ac1a93ec063d92:zh-CN:503d659c-a015-44af-a213-e294834f691d:393f5085:34f9d57d:9703c1f0:a3f85c94:665c7bcf:c4e0cafb:c6335cbd';Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);})();
