
// jsfwk 1.0. SCH 2006
var __FWKSTAT = {};
__FWKSTAT.declaredCount = 0;
__FWKSTAT.createCount = 0;

var __FWK_PROFILING = {
	Enabled : false,
	TraceArguments : false,
	ExecutionLimit : 50,
	RawResults : [],
	CurrentCallLevel : 0,
	Clear : function ()
	{
		this.RawResults = [];
		this.TreeResults = null;
	},
	ConvertResultsToTree : function ()
	{
		if (this.TreeResults)
			return;
		this.TreeResults = {};
		this.TreeResults.CallLevel = -1;
		var cur = this.TreeResults;
		for (var i = this.RawResults.length - 1; i >= 0; i--)
		{
			if (!cur.childrenInfo)
				cur.childrenInfo = [];
			this.RawResults[i].parentInfo = cur;
			cur.childrenInfo.unshift(this.RawResults[i]);
			if (i != 0)
			{
				if (this.RawResults[i-1].CallLevel > this.RawResults[i].CallLevel)
					cur = this.RawResults[i];
				for (var j=this.RawResults[i-1].CallLevel; j < this.RawResults[i].CallLevel; j++ )
					if (cur.parentInfo)	cur = cur.parentInfo;
			}
		}
	},
	ProfileStart : function ()
	{
		this.CurrentCallLevel++;
		return new Date().getTime();
	},
	ProfileEnd : function (fname, startInfo, args)
	{
		this.CurrentCallLevel--;
		var end = new Date().getTime();
		var execTime = end - startInfo;
		if (execTime < this.ExecutionLimit)
			return;
		var info = {};
		info.Name = fname;
		info.StartTime = startInfo;
		info.EndTime = end;
		info.ExecutionTime = execTime;
		info.CallLevel = this.CurrentCallLevel;
		if (__FWK_PROFILING.TraceArguments)
		{
			var al = args.length;
			var argsArr = [];
			for (var i = 0; i < al; i++)
			{
				if (typeof(args[i]) == "undefined")
					argsArr.push("null");
				else if (typeof(args[i]) == "function")
					argsArr.push("[func]");
				else if (typeof(args[i]) == "object")
				{
					//if (!args[i].GetType)
						argsArr.push("[obj]");
					//else
					//	argsArr.push("[obj:" + args[i].GetType() + "]");
				}
				else if (typeof(args[i]) == "number")
					argsArr.push(args[i] + "");
				else
				{
					var s = args[i] + "";
					s = s.replace(/\\/gi, "\\\\").replace(/\"/gi, "\\\"").replace(/\n/gi, "\\n")
					if (s.length > 100)
						s = s.substring(0, 40) + " ...";
					argsArr.push("\"" + s + "\"");
				}
			}
			info.Parameters = argsArr;
		}
		
		this.RawResults.push(info);
	},
	RedeclareMethod : function (fname, f)
	{
		if (!__FWK_PROFILING.Enabled)
			return f;
		if (typeof(f) != "function")
			return f;
		return function()
		{
			var startInfo = __FWK_PROFILING.ProfileStart();
			var v;
			try {v = f.apply(this,arguments);} catch(o){};
			__FWK_PROFILING.ProfileEnd(fname, startInfo, arguments);
			return v;
		}
	}
};

Function.Empty = function(){};

DeclareNamespace = function(s,o)
{
	DeclareEntity(s);
}
DeclareEntity = function(s,n,o)
{
	if (s == null || s.length == 0)
		return;
	var ns = s.split(".");
	var tobj = window;
	for (var i = 0; i < ns.length; i++)
	{
		if (o != null && i == (ns.length - 1)) 
		{
			if (tobj[ns[i]] != null)
				ReportCodeError("Warning: Class " + n + " already declared");
			else
				tobj[ns[i]] = o;
			return tobj[ns[i]];
		}
	
		if ( tobj[ns[i]] == null)
			tobj[ns[i]] = {};	
		tobj = tobj[ns[i]];
	}
	return tobj;
}
ReportCodeError = function(s)
{
	alert(s);
	Debug.write(s);
}
ReportError = function(s)
{
	alert(s);
	Debug.write(s);
}
CreateObjectCallback=function(c,f)
{
	return function FWK_Callback(){ return f.apply(c, arguments);};
}
Object.prototype.CreateCallback = function(f)
{
	return CreateObjectCallback(this, f);
}
DeclareMethod=function(o,n,f)
{
	if (o.prototype[n])
		return;
	o.prototype[n] = f; 
}
DeclareVirtualMethod=function(o,n,f)
{
	if (o.prototype[n])
		return;
	if (!o.__vtable)
		o.__vtable = {};
	o.__vtable[n] = o.prototype[n] = function FWK_VirtualCall()
	{
		var othis = this.__instance == null ? this : this.__instance;
		var oldBase = othis.base;
		var oldBaseInstance;
		othis.base = o.base;
		if (othis.base){oldBaseInstance = othis.base.__instance; othis.base.__instance = othis; };
		var res = f.apply(othis,arguments)
		if (othis.base) othis.base.__instance = oldBaseInstance;	
		othis.base = oldBase;
		return res;
	}
}
DeclareStaticMethod=function(o,n,f)
{
	if (o[n])
		return;
	o[n] = f;
}
decl_virtual = DeclareVirtualMethod;
decl_static = DeclareStaticMethod;
decl_public = DeclareMethod;

ProcessMemberDefault=function(cls, name, val)
{
	if (val instanceof Function)
		decl_public(cls, name, val);
	else
		val[0](cls, name, val[1]);	
}
ProcessMemberProfiling=function(cls, name, val)
{
	if (val instanceof Function)
		decl_public(cls, name, __FWK_PROFILING.RedeclareMethod(cls.__class__ + ":" + name, val) );
	else
		val[0](cls, name, __FWK_PROFILING.RedeclareMethod(cls.__class__ + ":" + name, val[1]));	
}

ProcessMember = __FWK_PROFILING.Enabled ? ProcessMemberProfiling : ProcessMemberDefault;

InitInheritance=function(o, baseTypeString)
{
	if (baseTypeString == null || baseTypeString.length == 0)
		return;
	if (o.inhInit)
	{
		var thisProto = o.prototype;
		o.__baseType = eval(baseTypeString);
		var baseProto = o.__baseType.prototype;
		o.base = function() 
		{
			this.base = o.__baseType.base;
			o.__baseType.apply(this, arguments);
			this.base = o.base;
		}	
		
		if (typeof(o.__baseType._dodecl) == 'function') {
			o.__baseType._dodecl();
		}
		
		for (var v in o.__baseType.__vtable)
			o.base[v] = o.__baseType.__vtable[v];
		o.base.__type__ = baseTypeString;
		for (var m in baseProto)
		{
			var isBaseVirtual = o.__baseType.__vtable && o.__baseType.__vtable[m] && !Object.prototype[m];
			if (!thisProto[m])
			{
				if (isBaseVirtual)
				{
					if (!o.__vtable)
						o.__vtable = {};	
					o.__vtable[m] = baseProto[m];
				}
				DeclareMethod(o,m,baseProto[m]);
			}
		}
		delete o.inhInit;
	}
}
DefaultConstructor = function FWK_DefaultConstructor()
{
	if (this.base)
		this.base.apply(this,arguments);
}
DeclareDefaultFunctions = function(cls)
{
	DeclareMethod(cls,"GetType", function GetType(){return cls.__class__;});
	DeclareMethod(cls,"GetParsedType", function GetType(){return cls;});
	DeclareMethod(cls,"IsInstanceOf", function IsInstanceOf(inst){return cls==inst;});
}
DeclareClass=function(className, base, decl)
{
	var cls;
	var cnstr = decl.constructor;
	if (cnstr == Object)
	{	
		// Sergey Chernov : that means that constructor is not declared and we try use default
		// Probably it will be better to use another keyword for constructor declaration
		cnstr = DefaultConstructor;
	}
	cls = function FWK_Constructor()
	{
		__FWKSTAT.createCount++;
		cls._dodecl(this);
		if (base != null)
		{
			this.base = cls.base; 
		}
		cnstr.apply(this, arguments);
	}
	cls._dodecl = function DeclareClass()
	{
		if (cls._deferdecl)
		{
			DeclareDefaultFunctions(cls);
			for(var m in decl)
			{
				if (decl[m][0] != decl_static)
					ProcessMember(cls, m, decl[m]);
			}
			delete cls._deferdecl;
		}
		if (base != null)
			InitInheritance(cls, base);
	}
	DeclareEntity(className,className,cls);
	if (base != null)
		cls.inhInit = true;
	cls._deferdecl = true;
	cls.__class__ = className;
	
	for(var m in decl)
		if (decl[m][0] == decl_static)
			ProcessMember(cls, m, decl[m]);
	__FWKSTAT.declaredCount++;
}

DeclareEnum=function(enumName, decl)
{
	DeclareEntity(enumName, enumName, decl);
}

Enum = {};
Enum.Parse = function Enum_Parse(type, val, dv)
{
	for(var n in type)	
		if (type.hasOwnProperty(n))	
			if (type[n].toString() == val.toString() || n == val.toString()) return type[n];
	return dv;
}

// UI part
__FWK_UI = {
	MainPane : null,
	HeaderPane : null,
	ActionsPane : null,
	ContentPane : null,
	Panels : [],
	CurrentPanel : -1,
	Init : function ()
	{
		var elem = document.createElement("div");
		elem.style.height = "300px";
		elem.style.border = "1px solid blue";
		if (document.body.firstChild)
			document.body.insertBefore(elem, document.body.firstChild);
		else
			alert("JSFWK: Failed to bind info panel.");
		this.MainPane = elem;
		this.HeaderPane = document.createElement("div");
		this.HeaderPane.style.height = "16px";
		this.HeaderPane.style.backgroundColor = "aliceblue";
		this.HeaderPane.style.borderBottom = "1px solid darkgray"; 
		this.MainPane.appendChild(this.HeaderPane);
		
		this.ActionsPane = document.createElement("div");
		this.ActionsPane.style.height = "16px";
		this.ActionsPane.style.display = "none";
		this.ActionsPane.style.backgroundColor = "cornsilk";
		this.ActionsPane.style.borderBottom = "1px solid darkgray"; 
		this.MainPane.appendChild(this.ActionsPane);
		
		this.ContentPane = document.createElement("div");
		this.ContentPane.style.height = "160px";
		this.ContentPane.style.overflow = "auto";
		this.ContentPane.style.backgroundColor = "snow";
		this.MainPane.appendChild(this.ContentPane);
		
		this.AddPanel("Profiling", __FWK_UI_PROFILINGPANEL);
		this.ActivatePanel(0);
	},
	GetPanel : function (idx)
	{
		if (idx < 0 || idx >= this.Panels.length)
			return null;
		return this.Panels[idx];
	},
	GetCurrentPanel : function (idx)
	{
		return this.GetPanel(this.CurrentPanel);
	},
	ProcessAction : function (action)
	{
		var info = this.GetCurrentPanel();
		if (info == null)
			return;
		info.Processor.Render(info, action);
	},
	ActivatePanel : function (idx)
	{
		if (idx == this.CurrentPanel)
			return;
		var oldInfo = this.GetCurrentPanel();
		var info = this.GetPanel(idx);
		if (info == null)	
			return;
		if (oldInfo != null)
			oldInfo.Deactivate();
		this.CurrentPanel = idx;
		info.Activate();
		this.ActionsPane.innerHTML = "";
		this.ActionsPane.style.display = info.Processor.RenderActions ? "" : "none";
		info.Processor.Render(info, "refresh");
		if (info.Processor.RenderActions)
		{
			info.Processor.RenderActions(this.ActionsPane);
			this.ContentPane.style.height="260px";
		}
		else
			this.ContentPane.style.height="280px";
	},
	AddPanel : function (name, processor)
	{
		var header = document.createElement("span");
		header.style.paddingLeft = "10px";
		header.style.cursor = "pointer";
		header.innerText = name;
		header.onclick = new Function("__FWK_UI.ActivatePanel(" + this.Panels.length + ")" );
		this.HeaderPane.appendChild(header);
		var content = document.createElement("div");
		content.style.height = "100%";
		this.ContentPane.appendChild(content);
		var info = 	{Processor: processor, Content: content, Header : header};
		info.Activate = function() {this.Content.style.display="";this.Header.style.fontWeight = "bold"; };
		info.Deactivate = function() {this.Content.style.display="none";this.Header.style.fontWeight = "normal"; };
		this.Panels.push(info);
		processor.Render(info, "init");
	},
	GetActionScript : function (action)
	{
		return "__FWK_UI.ProcessAction(\"" +action + "\"); return false;";
	},
	GetActionFunc : function (action)
	{
		return new Function(this.GetActionScript(action));
	},
	CreateActionLink : function (name, action)
	{
		var elem = document.createElement("a");
		elem.style.paddingLeft="10px";
		elem.innerText = name;
		elem.href= "#";
		elem.onclick = this.GetActionFunc(action);
		return elem;
	}
};

__FWK_UI_PROFILINGPANEL = {
	Render : function (info, action)
	{
		var html = '';
		switch(action)
		{
			case "clear":
				__FWK_PROFILING.Clear();
				break;
			case "tree":
				__FWK_PROFILING.ConvertResultsToTree();
				html = "<table width='100%' cellpadding=0 cellspacing=0 style='table-layout:fixed'><tr><td>" + this.RenderProfilingRecursive(__FWK_PROFILING.TreeResults) + "</td></tr></table>";
				break;
			case "raw":
				var html = "<table width='100%' cellpadding=0 cellspacing=0 border=1 style='table-layout:fixed'>";
				for (var i = 0; i < __FWK_PROFILING.RawResults.length; i++)
				{
					html+="<tr>";
					var item = __FWK_PROFILING.RawResults[__FWK_PROFILING.RawResults.length-i-1];
					html+= "<td>" + item.Name + "</td>";
					html+= "<td>" + item.CallLevel + "</td>";
					html+= "<td>" + item.ExecutionTime + "</td>";
					html+="</tr>";
				}
				html += "</table>";
				break;
		}
		info.Content.innerHTML = html;
	},
	RenderProfilingRecursive : function (info)
	{
		var level = info.CallLevel+1;
		var html = '';
		if (level != 0)
		{
			html += "<div style='height:16px";
			html += ";padding-left:" + level*5 + "px";
			if (level == 1)
				html += ";background-color:powderblue";
			html += "'>";
			html+= "<span style='padding-right:10px;float:right;width:100px'>" + info.ExecutionTime + "</span>";
			html+= "<span style='padding-right:10px;float:right;width:50px'>" + info.CallLevel + "</span>";
			html+= "<span style='padding-right:10px'>" + info.Name;
			html+= "(" + (info.Parameters ? info.Parameters.join(",").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;") : "") + ")";
			html+= "</span>";
			html += "</div>";
		}
		if (!info.childrenInfo || info.childrenInfo.length == 0)
			return html;
		for (var i = 0; i < info.childrenInfo.length; i++)
			html += this.RenderProfilingRecursive(info.childrenInfo[i]);
		return html;
	},	
	RenderActions : function (actionsPane)
	{
		actionsPane.appendChild(__FWK_UI.CreateActionLink("Raw", "raw"));
		actionsPane.appendChild(__FWK_UI.CreateActionLink("Tree view", "tree"));
		actionsPane.appendChild(__FWK_UI.CreateActionLink("Clear", "clear"));
	}
};

if (__FWK_PROFILING.Enabled)
{
	if (window.attachEvent)
		window.attachEvent("onload", CreateObjectCallback(__FWK_UI,__FWK_UI.Init));
	else
		window.addEventListener("load", CreateObjectCallback(__FWK_UI,__FWK_UI.Init), false);
}

// Version info
var TP_VERSION = '4.0.38.16300';
// Urls
var PID_UNDEFINED = "Undefined";
var U_UNDEFINED = "/default.aspx?page=Undefined";
var PID_FEEDS = "Feeds";
var U_FEEDS = "/default.aspx?page=Feeds";
var PID_HOME = "Home";
var U_HOME = "/default.aspx?page=Home";
var PID_FOLDERS = "Folders";
var U_FOLDERS = "/default.aspx?page=Folders";
var PID_CALENDARS = "Calendars";
var U_CALENDARS = "/default.aspx?page=Calendars";
var PID_BLOGS = "Blogs";
var U_BLOGS = "/default.aspx?page=Blogs";
var PID_MANAGESEARCHES = "ManageSearches";
var U_MANAGESEARCHES = "/default.aspx?page=ManageSearches";
var PID_MYACCOUNT = "MyAccount";
var U_MYACCOUNT = "/default.aspx?page=MyAccount";
var PID_ADDFEED = "AddFeed";
var U_ADDFEED = "/popup.aspx?page=AddFeed";
var PID_CHFEEDTYPE = "ChFeedType";
var U_CHFEEDTYPE = "/popup.aspx?page=ChFeedType";
var PID_CONTENTTAGGING = "ContentTagging";
var U_CONTENTTAGGING = "/popup.aspx?page=ContentTagging";
var PID_DOCUMENTVIEWER = "DocumentViewer";
var U_DOCUMENTVIEWER = "/popup.aspx?page=DocumentViewer";
var PID_CONTEXTSEARCHRESOLVER = "ContextSearchResolver";
var U_CONTEXTSEARCHRESOLVER = "/popup.aspx?page=ContextSearchResolver";
var PID_NEWSLETTERVIEWBODY = "NewsletterViewBody";
var U_NEWSLETTERVIEWBODY = "/popup.aspx?page=NewsletterViewBody";
var PID_NEWSLETTERVIEWRSS = "NewsletterViewRss";
var U_NEWSLETTERVIEWRSS = "/popup.aspx?page=NewsletterViewRss";
var PID_ADDBLOG = "AddBlog";
var U_ADDBLOG = "/popup.aspx?page=AddBlog";
var PID_ADDFOLDER = "AddFolder";
var U_ADDFOLDER = "/popup.aspx?page=AddFolder";
var PID_ADDCHANNEL = "AddChannel";
var U_ADDCHANNEL = "/popup.aspx?page=AddChannel";
var PID_ADDRSSFEED = "AddRSSFeed";
var U_ADDRSSFEED = "/popup.aspx?page=AddRSSFeed";
var PID_ADDCALENDAR = "AddCalendar";
var U_ADDCALENDAR = "/popup.aspx?page=AddCalendar";
var PID_CUSTOMMETASTRUCTURESLIST = "CustomMetaStructuresList";
var U_CUSTOMMETASTRUCTURESLIST = "/popup.aspx?page=CustomMetaStructuresList";
var PID_BLOGNEWPOST = "BlogNewPost";
var U_BLOGNEWPOST = "/popup.aspx?page=BlogNewPost";
var PID_SHOWBLOGPOST = "ShowBlogPost";
var U_SHOWBLOGPOST = "/popup.aspx?page=ShowBlogPost";
var PID_SHOWTRANSLATEDMESSAGE = "ShowTranslatedMessage";
var U_SHOWTRANSLATEDMESSAGE = "/popup.aspx?page=ShowTranslatedMessage";
var PID_SETENTITLEMENTS = "SetEntitlements";
var U_SETENTITLEMENTS = "/popup.aspx?page=SetEntitlements";
var PID_CREATECUSTOMMETASTRUCTURE = "CreateCustomMetaStructure";
var U_CREATECUSTOMMETASTRUCTURE = "/popup.aspx?page=CreateCustomMetaStructure";
var PID_PLADVANCEDSEARCH = "PLAdvancedSearch";
var U_PLADVANCEDSEARCH = "/default.aspx?page=PLAdvancedSearch";
var PID_PLSEARCHRESULTS = "PLSearchResults";
var U_PLSEARCHRESULTS = "/default.aspx?page=PLSearchResults";
var PID_PLMANAGEFEEDS = "PLManageFeeds";
var U_PLMANAGEFEEDS = "/default.aspx?page=PLManageFeeds";
var PID_PLMANAGECALENDARS = "PLManageCalendars";
var U_PLMANAGECALENDARS = "/default.aspx?page=PLManageCalendars";
var PID_PLMANAGEFOLDERS = "PLManageFolders";
var U_PLMANAGEFOLDERS = "/default.aspx?page=PLManageFolders";
var PID_PLMANAGEBLOGS = "PLManageBlogs";
var U_PLMANAGEBLOGS = "/default.aspx?page=PLManageBlogs";
var PID_PLMYBLOGGINGACTIVITY = "PLMyBloggingActivity";
var U_PLMYBLOGGINGACTIVITY = "/default.aspx?page=PLMyBloggingActivity";
var PID_PLMYACCOUNTCHANGEPASSWORD = "PLMyAccountChangePassword";
var U_PLMYACCOUNTCHANGEPASSWORD = "/default.aspx?page=PLMyAccountChangePassword";
var PID_PLMYACCOUNTPREFERENCESGENERAL = "PLMyAccountPreferencesGeneral";
var U_PLMYACCOUNTPREFERENCESGENERAL = "/default.aspx?page=PLMyAccountPreferencesGeneral";
var PID_PLMYACCOUNTPREFERENCESRESOLUTION = "PLMyAccountPreferencesResolution";
var U_PLMYACCOUNTPREFERENCESRESOLUTION = "/default.aspx?page=PLMyAccountPreferencesResolution";
var PID_PLMYACCOUNTPREFERENCESLANGUAGES = "PLMyAccountPreferencesLanguages";
var U_PLMYACCOUNTPREFERENCESLANGUAGES = "/default.aspx?page=PLMyAccountPreferencesLanguages";
var PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS = "PLMyAccountPreferencesMyPortfolios";
var U_PLMYACCOUNTPREFERENCESMYPORTFOLIOS = "/default.aspx?page=PLMyAccountPreferencesMyPortfolios";
var PID_PLMYACCOUNTPREFERENCESMYNEWSLETTERS = "PLMyAccountPreferencesMyNewsletters";
var U_PLMYACCOUNTPREFERENCESMYNEWSLETTERS = "/default.aspx?page=PLMyAccountPreferencesMyNewsletters";
var PID_PLMYACCOUNTPREFERENCESPRESENCE = "PLMyAccountPreferencesPresence";
var U_PLMYACCOUNTPREFERENCESPRESENCE = "/default.aspx?page=PLMyAccountPreferencesPresence";
var PID_PLMYACCOUNTPREFERENCESPERMISSIONS = "PLMyAccountPreferencesPermissions";
var U_PLMYACCOUNTPREFERENCESPERMISSIONS = "/default.aspx?page=PLMyAccountPreferencesPermissions";
var PID_PLMYACCOUNTPREFERENCESMYMEMBERGROUPS = "PLMyAccountPreferencesMyMemberGroups";
var U_PLMYACCOUNTPREFERENCESMYMEMBERGROUPS = "/default.aspx?page=PLMyAccountPreferencesMyMemberGroups";
var PID_PLMYACCOUNTADMINMEMBERS = "PLMyAccountAdminMembers";
var U_PLMYACCOUNTADMINMEMBERS = "/default.aspx?page=PLMyAccountAdminMembers";
var PID_PLMYACCOUNTEDITCOMPANY = "PLMyAccountEditCompany";
var U_PLMYACCOUNTEDITCOMPANY = "/default.aspx?page=PLMyAccountEditCompany";
var PID_PLMYACCOUNTADMINBRANDS = "PLMyAccountAdminBrands";
var U_PLMYACCOUNTADMINBRANDS = "/default.aspx?page=PLMyAccountAdminBrands";
var PID_PLMYACCOUNTADMINFEEDCATEGORIES = "PLMyAccountAdminFeedCategories";
var U_PLMYACCOUNTADMINFEEDCATEGORIES = "/default.aspx?page=PLMyAccountAdminFeedCategories";
var PID_PLMYACCOUNTADMINCHANGEPASSWORD = "PLMyAccountAdminChangePassword";
var U_PLMYACCOUNTADMINCHANGEPASSWORD = "/default.aspx?page=PLMyAccountAdminChangePassword";
var PID_PLMYACCOUNTADMINTOPICS = "PLMyAccountAdminTopics";
var U_PLMYACCOUNTADMINTOPICS = "/default.aspx?page=PLMyAccountAdminTopics";
var PID_PLMYACCOUNTUPGRADE = "PLMyAccountUpgrade";
var U_PLMYACCOUNTUPGRADE = "/default.aspx?page=PLMyAccountUpgrade";
var PID_UPLOADFILES = "UploadFiles";
var U_UPLOADFILES = "/popup.aspx?page=UploadFiles";
var PID_SAVEIT = "SaveIt";
var U_SAVEIT = "/popup.aspx?page=SaveIt";
var PID_MESSAGEPROPERTIES = "MessageProperties";
var U_MESSAGEPROPERTIES = "/popup.aspx?page=MessageProperties";
var PID_USERPROPERTIES = "UserProperties";
var U_USERPROPERTIES = "/popup.aspx?page=UserProperties";
var PID_USERGROUPFINDER = "UserGroupFinder";
var U_USERGROUPFINDER = "/popup.aspx?page=UserGroupFinder";
var PID_EMAILIT = "EmailIt";
var U_EMAILIT = "/popup.aspx?page=EmailIt";
var PID_SHAREDPROPERTIES = "SharedProperties";
var U_SHAREDPROPERTIES = "/popup.aspx?page=SharedProperties";
var PID_BLOGIT = "BlogIt";
var U_BLOGIT = "/popup.aspx?page=BlogIt";
var PID_SPELLCHECKERPOPUP = "SpellCheckerPopup";
var U_SPELLCHECKERPOPUP = "/popup.aspx?page=SpellCheckerPopup";
var PID_INSERTIMAGEPOPUP = "InsertImagePopup";
var U_INSERTIMAGEPOPUP = "/popup.aspx?page=InsertImagePopup";
var PID_ALERTDETAILS = "AlertDetails";
var U_ALERTDETAILS = "/popup.aspx?page=AlertDetails";
var PID_ALERTNEWADDRESS = "AlertNewAddress";
var U_ALERTNEWADDRESS = "/popup.aspx?page=AlertNewAddress";
var PID_NEWEVENT = "NewEvent";
var U_NEWEVENT = "/popup.aspx?page=NewEvent";
var PID_ITEMSEXPORT = "ItemsExport";
var U_ITEMSEXPORT = "/popup.aspx?page=ItemsExport";
var PID_CUSTOMMETASTRUCTURESELECT = "CustomMetaStructureSelect";
var U_CUSTOMMETASTRUCTURESELECT = "/popup.aspx?page=CustomMetaStructureSelect";
var PID_CMSCHECKBOX = "CMSCheckBox";
var U_CMSCHECKBOX = "/popup.aspx?page=CMSCheckBox";
var PID_CMSLISTBOX = "CMSListBox";
var U_CMSLISTBOX = "/popup.aspx?page=CMSListBox";
var PID_CMSCOMBOBOX = "CMSComboBox";
var U_CMSCOMBOBOX = "/popup.aspx?page=CMSComboBox";
var PID_CMSNUMBERBOX = "CMSNumberBox";
var U_CMSNUMBERBOX = "/popup.aspx?page=CMSNumberBox";
var PID_CMSTEXTBOX = "CMSTextBox";
var U_CMSTEXTBOX = "/popup.aspx?page=CMSTextBox";
var PID_CMSTREE = "CMSTree";
var U_CMSTREE = "/popup.aspx?page=CMSTree";
var PID_MYACCOUNTINITENVIRONMENT = "MyAccountInitEnvironment";
var U_MYACCOUNTINITENVIRONMENT = "/popup.aspx?page=MyAccountInitEnvironment";
var PID_SHOWMESSAGE = "ShowMessage";
var U_SHOWMESSAGE = "/default.aspx?page=ShowMessage";
var PID_HTML2RSS = "HTML2RSS";
var U_HTML2RSS = "/popup.aspx?page=HTML2RSS";
var PID_GOOGLENEWSTOFEED = "GoogleNewsToFeed";
var U_GOOGLENEWSTOFEED = "/popup.aspx?page=GoogleNewsToFeed";
var PID_MODIFYMONITORNEWSFEED = "ModifyMonitorNewsFeed";
var U_MODIFYMONITORNEWSFEED = "/popup.aspx?page=ModifyMonitorNewsFeed";
var PID_SCROLLABLEALERTS = "ScrollableAlerts";
var U_SCROLLABLEALERTS = "/popup.aspx?page=ScrollableAlerts";
var PID_SCROLLABLEALERTSOPTIONS = "ScrollableAlertsOptions";
var U_SCROLLABLEALERTSOPTIONS = "/popup.aspx?page=ScrollableAlertsOptions";
var PID_SCROLLABLEALERTSFONTS = "ScrollableAlertsFonts";
var U_SCROLLABLEALERTSFONTS = "/popup.aspx?page=ScrollableAlertsFonts";
var PID_SCROLLABLEALERTSCOLORS = "ScrollableAlertsColors";
var U_SCROLLABLEALERTSCOLORS = "/popup.aspx?page=ScrollableAlertsColors";
var PID_TRENDS = "Trends";
var U_TRENDS = "/default.aspx?page=Trends";
var PID_HTML2RSSREQUESTTOSUPPORT = "HTML2RSSRequestToSupport";
var U_HTML2RSSREQUESTTOSUPPORT = "/popup.aspx?page=HTML2RSSRequestToSupport";
var PID_NEWSLETTERSV2 = "NewslettersV2";
var U_NEWSLETTERSV2 = "http://v4.infongen.com;http://v4snp.infongen.com";

// Parameters 
var P_PAGELOCATION = "ploc";
var P_PAGEVIEW = "pview";
var P_CTLDATATYPE = "ctltype";
var P_PARENT_EL_ID = "prntid";
var P_SUPPORT_POSTBACK = "spost";
var P_SUPPORT_XML = "xml";
var P_XML_DATA = "xml_data";
var P_USER_LOGIN = "userLogin";
var P_USER_PASSWORD = "userPassword";
var P_CONTAINER_SCOPE = "cntscope";
var P_CONTAINER_IDS = "cntIDs";
var P_CONTAINER_TYPE = "cnttp";
var P_PARENTCONTAINER_ID = "parentcntid";
var P_LOCATION = "locname";
var P_PROMPTINGREQUEST = "prreq";
var P_ACTIONTYPE_ID = "actiontype";
var P_COMMAND = "command";
var P_MYSEARCHES = "mysearches";
var P_TYPE = "type";
var P_TOKEN = "token";
var P_RSSURL = "rssurl";
var P_MODULE_PREFERENCES = "mpref";
var P_MODULE_NAME = "mname";
var P_MODULES_STORAGE = "mstore";
var P_NAVCALENDAR_TYPE = "ncldtp";
var P_NAVCALENDAR_DATE = "nclddt";
var P_NAVCALENDAR_PERIOD = "ncldpr";
var P_NAVCALENDAR_MONTH = "ncldm";
var P_CALENDAR_FILTER_TYPE = "cldflt";
var P_COMMENT_TEXT = "commtxt";
var P_MYTAGS = "mytags";
var P_FEEDCATEGORY_ID = "feedcategory_id";
var P_FEEDCATEGORIES_XML = "feedcategories_xml";
var P_SEARCH_NAME = "srch_name";
var P_SEARCH_XML = "search_xml";
var P_SORTBY = "srtby";
var P_ISFAVORITE = "isfavorite";
var P_ISSUBSCRIBE = "issubscribe";
var P_CMS_TYPE = "cms_type";
var P_CMS_SELECTED_TYPE = "cms_seleted_type";
var P_CMS_ID = "cms_id";
var P_LOG_ON_CLIENT = "log_on_client";
var P_LOG_DATA = "log_data";
var P_LOG_DATA_LEVEL = "log_data_level";
var P_LOG_QUERY = "log";
var P_LOG_QUERY_LEVEL = "log_level";
var P_DATASOURCE_ID = "datasource";
var P_TITLE = "title";
var P_LANGUAGE = "lang";
var P_FILEUPLOAD_DLG_TYPE = "fileupload_dlg_type";
var P_GETTER_FUNCTION = "fngetter";
var P_SETTER_FUNCTION = "fnsetter";
var P_SYNOPSIS = "synopsis";
var P_PROVIDER_PRINCIPAL_ID = "pvpclid";
var P_PRINCIPAL_ID = "pclid";
var P_PRINCIPAL_IDS = "pclids";
var P_PRINCIPAL_TYPE = "pcltype";
var P_PRINCIPAL_NAME = "pclname";
var P_EMAIL = "eml";
var P_EMAILS = "emls";
var P_MATCH = "match";
var P_BEDATA_REFERENCE = "rfn";
var P_ADMIN_EDIT_MODE = "aem";
var P_ISADMIN = "isadmin";
var P_COMPANY_ID = "cmid";
var P_COMPANY_NAME = "cmname";
var P_TEAM_ID = "tmid";
var P_TEAM_NAME = "tmname";
var P_USER_ID = "usid";
var P_USER_IDS = "usids";
var P_FINDMODE = "findmode";
var P_FIND_MANAGEABLE = "fmng";
var P_FIND_SHOW_SELF = "fssf";
var P_TEXT = "text";
var P_MODE = "mode";
var P_ALERT_ID = "alertid";
var P_ALERT_IDS = "alertids";
var P_ALERT_SUBSCRIPTION = "alertrsubscription";
var P_ALERT_SOURCE_TYPE = "alertstype";
var P_SNP_CONTAINER = "snpcnt";
var P_TOUCHPOINTSETTINGS = "tpsettings";
var P_TIMESETTINGS = "tmsettings";
var P_MSG_OVERRIDE = "msg_override";
var P_EXT_FIX = "extf";
var P_CLIENT_DEBUGGING = "debug";
var P_BRAND_NAME = "brand_name";
var P_EXPORT_TYPE = "exptype";
var P_FIRST_NAME = "first_name";
var P_LAST_NAME = "last_name";
var P_FORCE_ACTION = "force_action";
var P_PREFERENCE_NAME = "preference_name";
var P_PREFERENCE_VALUE = "preference_value";
var P_USAGE_LOGGER_EVENT = "usage_logger_event";
var P_VIEW_SYNOPSIS = "view_synopsis";
var P_CLUSTER_ID = "clstr_id";
var P_CLUSTER_NAME = "clstr_nm";
var P_PREDEFINEDLOCATION = "predloc";
var P_PARENT_MODULE_NAME = "parent_mname";
var P_SEARCH_TAG_NAME = "srch_tag_name";
var P_ITEM_ID = "item_id";
var P_RESOLVERTYPE = "resolvertype";
var P_UNRESOLVEDGRID = "unresolvedgrid";
var P_ITEM_COUNT = "itemcount";
var P_LAYOUT_SECTION_XML = "layout_section_xml";
var P_LAYOUT_COLUMN_INDEX = "layout_column_number";
var P_LAYOUT_SECTION_ID = "layout_section_id";
var P_HOME_MODE = "homemode";
var P_LAYOUT_PARAMS_XML = "layout_params_xml";
var P_CUSTOM_ID = "custom_id";
var P_READ_ONLY = "read_only";
var P_GRID_LAYOUT_ELEMENTS = "grid_layout_elem";
var P_SEARCH_TAGS = "srch_tags";
var P_BRANDFILTER = "bfltr";
var P_PAGENUMBER = "pnmbr";
var P_TRANSACTIONID = "TID";
var P_MONITORINGACTION = "mAction";
var P_APPTYPE = "AppType";
var P_REMEMBER_ME = "remember_me";
var P_STAGE_NAME = "stage_name";
var P_SCRIPTHANDLER = "scrpt_hndlr";
var P_HISTORICALALERTTYPE = "historical_alert_type";
var P_URL = "url";
var P_LANGUAGE_PAIR = "lp";
var P_NEWSLETTERS_COMMENT_LENGTH = "150";
var P_NEWSLETTERS_HEADLINES_ID = "HEADLINES_ID";
var P_NEWSLETTERS_HEADLINE_COMMENT = "NewsletterHeadlineComment";
var P_NEWSLETTERS_ID = "ID";
var P_NEWSLETTERS_ARCHIVE_ID = "ARCHIVE_ID";
var P_NEWSLETTERS_ARCHIVE_EMAIL = "archive_email";
var P_NEWSLETTERS_ARCHIVE_BODY_ID = "BODY_ID";
var P_NEWSLETTERS_ARCHIVE_STATE_ID = "STATE_ID";
var P_NEWSLETTERS_TITLE = "TITLE";
var P_NEWSLETTERS_FREQUENCY = "FREQUENCY";
var P_NEWSLETTERS_COMMENT = "NCOMMENT";
var P_NEWSLETTERS_SEND_PREVIEW_TIME = "SEND_PREVIEW_DATE";
var P_NEWSLETTERS_EMAIL_ADDR = "EMAIL_ADDRESS";
var P_NEWSLETTERS_FEEDS = "FEEDS";
var P_NEWSLETTERS_PARAM_ITEM = "NewslettersItem";
var P_NEWSLETTERS_ARCHIVE_EMAIL_COLLECTION = "NewslettersArchiveEmailItemCollection";
var P_NEWSLETTERS_ARCHIVE_EMAIL_ITEM = "NewslettersArchiveEmailItem";
var P_NEWSLETTERS_ARCHIVE_EMAIL_ITEM_EMAIL = "Email";
var P_NEWSLETTERS_ARCHIVE_EMAIL_ITEM_ID = "EmailID";
var P_NEWSLETTERS_RSS_ID = "RSS_ID";
var P_NEWSLETTERS_RSS_IS_ENABLE = "IS_RSS_ENABLE";
var P_NEWSLETTERS_ITEM = "newsletters_item_xml";
var P_NEWSLETTERS_SEARCH_ID = "newsletters_search_id";
var P_NEWSLETTERS_SEARCH_COMMENT = "SavedSearchComment";
var P_NEWSLETTERS_SELECTED_SEARCH = "sels";
var P_NEWSLETTERS_ARCHIVE_GRID_PAGE = "PAGENUM";
var P_NEWSLETTERS_ARCHIVE_GRID_PAGE_COUNT = "PAGECOUNT";
var P_NEWSLETTERS_ARCHIVE_GRID_FILTER_BY_NAME = "FILTERBYNAME";
var P_NEWSLETTERS_ARCHIVE_GRID_FILTER_BY_DATE = "FILTERBYDATE";
var P_NEWSLETTERS_ARCHIVE_GRID_FILTER_SORT = "FILTERSORT";
var P_NEWSLETTERS_ARCHIVE_ITEMS_PER_PAGE = "10";
var P_TRENDS_PERIOD = "trends_period";
var P_TRENDS_INDUSTRY_ID = "trends_industry_id";
var P_TRENDS_MOVING_AVERAGE = "trends_moving_average";
var P_TRENDS_TREND_DATE = "trends_trand_date";
var P_TRENDS_MAP_REGION = "trends_map_region";
var P_TRENDS_MAP_INDUSTRY = "trends_map_industry";
var P_TRENDS_RELATED_COMPANY = "trends_related_company";
var P_TRENDS_RELATED_TOPIC = "trends_related_topic";
var P_TRENDS_RELATED_CUSTOM_TOPIC = "trends_related_custom_topic";
var P_TRENDS_SHOW_RELATED = "trends_show_related";
var P_TRENDS_CHART_WIDTH = "chartWidth";
var P_TRENDS_CHART_HEIGHT = "chartHeight";
var P_TRENDS_CHART_PLACE = "chartPlace";
var P_HEADLINES_SORT = "hsort";
var P_ROW_COUNT = "r";
var P_FILTEREXPRESSION = "fltrexpr";
var P_REGID = "RegId";
var P_CONFIG_OVERRIDE = "cfg_ovd";
var P_TARGET_URL = "targetURL";
var P_MESSAGE_ID = "msgid";
var P_MESSAGE_IDS = "msgids";
var P_PAGEID = "page";
var P_CONTAINER_ID = "cntid";
var P_SEARCH_ID = "srch_id";
var P_URL_REFERRER = "pageref";

// Commands 
var C_CHANGE_FAVORITE = "change_favorite";
var C_CHANGE_FAVORITES = "change_favorites";
var C_CHANGE_SUBSCRIPTION = "change_subscription";
var C_CHANGE_SUBSCRIPTIONS = "change_subscriptions";
var C_FEEDCAT_CHANGE_SUBSCRIPTION = "feedcat_change_subscription";
var C_FEEDCAT_CHANGE_SUBSCRIPTIONS = "feedcat_change_subscriptions";
var C_GET_FEEDCATEGORIES = "get_feedcategories";
var C_DELETE_CONTAINER = "delete_container";
var C_DELETE_CONTAINER_CONTENT = "delete_container_content";
var C_DELETE_MESSAGE = "delete_message";
var C_DELETE_SEARCH = "delete_search";
var C_DELETE_PAGE = "delete_page";
var C_LOG_ON_CLIENT = "LogOnClient";
var C_RESOLVE = "resolve";
var C_GET_DATASOURCE = "get_datasource";
var C_GET_SEARCHXML = "get_searchxml";
var C_SET_SEARCHXML = "set_searchxml";
var C_SAVESEARCH = "savesearch";
var C_IS_MESAGE_EXIST = "is_message_exist";
var C_FIND_USERGROUP = "find_usergroup";
var C_DELETE_RIGHTS = "delete_rights";
var C_ADD_RIGHTS = "add_rights";
var C_UPDATE_TRUSTED_SOURCE = "update_trusted_source";
var C_DELETE_SECURITY_PRINCIPAL = "delete_security_principal";
var C_REMOVE_TEAM_USER = "remove_team_user";
var C_ADD_TEAM_USERS = "add_team_users";
var C_SET_ADMIN = "set_admin";
var C_PORTFOLIO_GET = "get_portfolio";
var C_PORTFOLIO_ADD = "add_portfolio";
var C_PORTFOLIO_REMOVE = "remove_portfolio";
var C_PORTFOLIO_RENAME = "rename_portfolio";
var C_PORTFOLIO_ADD_ITEM = "add_item_portfolio";
var C_PORTFOLIO_REMOVE_ITEM = "remove_item_portfolio";
var C_COMMENT_ADD = "comment_add";
var C_SET_FAVORITE_AUTHOR = "set_favorite_author";
var C_ALERT_DELETE = "alert_delete";
var C_ALERT_SET = "alert_set";
var C_ALERT_GET = "alert_get";
var C_ALERTSUBSCRIPTIONS_GET = "alertsubscriptions_get";
var C_ALERT_EMAILUPDATE = "alert_emailupdate";
var C_REAUTHENTICATE = "re_auth";
var C_CHECKWHOAMI = "checkwai";
var C_GET_PREFERENCE_VALUE = "get_preference_value";
var C_SET_PREFERENCE_VALUE = "set_preference_value";
var C_OUTLOOK_EMAILIT = "outlook_emailit";
var C_LOG_USAGE = "log_usage";
var C_CHANGE_MODULE_SETTINGS = "change_module_settings";
var C_ADD_MYRECENTSEARCHES = "add_myrcntsrchs";
var C_ADD_RSS_FEED = "add_rss_feed";
var C_PROMPT_GET = "prompt_get";
var C_GET_RELATED = "get_related";
var C_GET_CONTAINER = "get_container";
var C_GET_USERDATA = "get_userdata";
var C_ADD_RECENT_ITEM = "add_recent_item";
var C_ADD_RECENT_ITEM_XML = "add_recent_item_xml";
var C_RESOLVE_RSS_LINK = "resolve_rss_link";
var C_GET_HOME_LAYOUT = "get_home_layout";
var C_ADD_HOME_LAYOUT_SECTION = "add_home_layout_section";
var C_REMOVE_HOME_LAYOUT_SECTION = "remove_home_layout_section";
var C_UPDATE_HOME_LAYOUT_SECTION = "update_home_layout_section";
var C_UPDATE_HOME_LAYOUT_PAGE = "update_home_layout_page";
var C_MOVE_HOME_LAYOUT_SECTION = "move_home_layout_section";
var C_LOGIN = "login";
var C_CHECK_CONTAINER_RIGHTS = "check_container_rights";
var C_CHECK_MESSAGE_RIGHTS = "check_message_rights";
var C_CHECK_PAGE_RIGHTS = "check_page_rights";
var C_GET_ITEM_METADATA = "get_item_metadata";
var C_GET_ITEM_CUSTOMMETADATA = "get_item_custommetadata";
var C_PREPARE_SEARCHXML_FORHOMESECTION = "prepsxforhome";
var C_BROKER_GET = "get_broker";
var C_FEED_CATEGORY_GET = "get_feed_category";
var C_IS_USER_REPLICATED = "is_user_replicated";
var C_EXECUTE_STAGE = "execute_stage";
var C_NEWSLETTER_ITEM_GET = "get_newsletters_item";
var C_NEWSLETTER_DELETE_HEADLINES_ITEMS = "delete_newsletters_items";
var C_NEWSLETTER_ADD_HEADLINES_ITEMS = "add_newsletters_items";
var C_NEWSLETTER_ITEM_UPDATE = "update_newsletters_item";
var C_NEWSLETTER_ITEM_DELETE = "delete_newsletters_item";
var C_NEWSLETTER_UPLOAD_LOGO = "upload_logo_newsletters";
var C_NEWSLETTER_GET_FIRST = "get_first_newsletters";
var C_NEWSLETTER_SEND = "send_newsletters";
var C_NEWSLETTER_GET_LIST = "get_list_newsletters";
var C_NEWSLETTER_CHECK_USER_RIGHTS = "newsletters_check_user_rights";
var C_NEWSLETTER_GET_ARCHIVE_EMAIL_LIST = "get_archive_email_list_newsletters";
var C_NEWSLETTER_GET_SAVEDSEARCH_COMMENT = "get_ss_comment";
var C_NEWSLETTER_UPDATE_SAVEDSEARCH_COMMENT = "update_ss_comment";
var C_NEWSLETTER_ARCHIVE_RESEND = "resend_archive_newsletters";
var C_NEWSLETTER_GET_ARCHIVE_ITEMS_COUNT = "get_archive_items_count_newsletters";
var C_NEWSLETTER_MSG_COMMENT_GET = "newsletters_msg_comment_get";
var C_NEWSLETTER_MSG_COMMENT_UPDATE = "newsletters_msg_comment_update";
var C_NEWSLETTER_RSS_SET = "newsletters_rss_out";
var C_EXPORT_FEEDS = "export_feeds";
var C_TRENDS_GRAPHIC = "thrends_graphic";
var C_TRENDS_RELATED_COMPANIES = "trends_related_companies";

// DataSet Commands 
var DSC_ADDFAVORITE = "AddFavorite";
var DSC_REMOVEFAVORITE = "RemoveFavorite";
var DSC_SUBSCRIBE = "Subscribe";
var DSC_UNSUBSCRIBE = "Unsubscribe";
var DSC_DELETECONTAINER = "DeleteContainer";
var DSC_DELETESEARCH = "DeleteSearch";
var DSC_ADD_TO_HOME = "AddToHome";

// Enum MessageType
var MT_NONE = "None";
var MT_BLOG = "Blog";
var MT_EVENT = "Event";
var MT_DOCUMENT = "Document";
var MT_IMCONVERSATION = "IMConversation";
var MT_FILE = "File";
var MT_USERBLOGPOST = "UserBlogPost";
var MT_COMMENT = "Comment";
var MT_CUSTOMMESSAGE = "CustomMessage";
var MT_ALL = "All";

// Enum ContainerType
var CT_ANY = "0";
var CT_BLOG = "1";
var CT_CALENDAR = "2";
var CT_CHANNEL = "3";
var CT_CATEGORY = "4";
var CT_FOLDER = "5";
var CT_SPECIALFOLDER = "8";
var CT_USERBLOG = "9";
var CT_MONITORNEWSFEED = "10";
var CT_NONE = "10000";

// Enum ContentAccessType
var CAT_PUBLIC = "1";
var CAT_REGISTRATION = "2";
var CAT_SUBSCRIPTION = "3";

// Enum TagTypeEnum
var SRCH_TT_STD = "std";
var SRCH_TT_CUSTOM = "custom";

// Enum TagScope
var SRCH_TS_ANY = "Any";
var SRCH_TS_ALL = "All";
var SRCH_TS_EXCLUDEANY = "ExcludeAny";

// Enum TagNames
var SRCH_TN_TEXT = "Text";
var SRCH_TN_KEYWORD = "Keyword";
var SRCH_TN_PERIOD = "Period";
var SRCH_TN_SYMBOL = "Symbol";
var SRCH_TN_PORTFOLIO = "Portfolio";
var SRCH_TN_INDUSTRY = "Industry";
var SRCH_TN_GEOGRAPHY = "Geography";
var SRCH_TN_FEED = "Feed";
var SRCH_TN_CATEGORY = "Category";
var SRCH_TN_BLOGCATEGORY = "BlogCategory";
var SRCH_TN_PROVIDER = "Provider";
var SRCH_TN_FOLDER = "Folder";
var SRCH_TN_SAVEDSEARCH = "SavedSearch";
var SRCH_TN_FILETYPE = "FileType";
var SRCH_TN_CONTAINERSEARCHSCOPE = "ContainerSearchScope";
var SRCH_TN_COMPANY = "Company";
var SRCH_TN_REGION = "Region";
var SRCH_TN_LANGUAGE = "Language";
var SRCH_TN_COUNTRY = "Country";
var SRCH_TN_FOCUS = "Focus";
var SRCH_TN_BLOG = "Blog";
var SRCH_TN_POSTACTIVITYTYPE = "PostActivityType";
var SRCH_TN_BLOGGERSEARCHCRITERIA = "BloggerSearchCriteria";
var SRCH_TN_USER = "User";
var SRCH_TN_ALERTTYPE = "AlertType";
var SRCH_TN_ALERTSOURCETYPE = "AlertSourceType";
var SRCH_TN_SOURCEALERTS = "SourceAlerts";
var SRCH_TN_CALENDAR = "Calendar";
var SRCH_TN_PAGESOURCE = "PageSource";
var SRCH_TN_FEEDCATEGORY = "FeedCategory";
var SRCH_TN_INDUSTRYSECTOR = "IndustrySector";
var SRCH_TN_BLOGGERNAME = "BloggerName";
var SRCH_TN_TOPIC = "Topic";
var SRCH_TN_EVENTTYPE = "EventType";
var SRCH_TN_EVENTSUBTYPE = "EventSubType";
var SRCH_TN_ALERTSUBSCRIPTIONID = "AlertSubscriptionID";
var SRCH_TN_BROKER = "Broker";
var SRCH_TN_ALERTTYPEFLAGS = "AlertTypeFlags";
var SRCH_TN_CUSTOMTOPIC = "CustomTopics";

// Enum TagParams
var SRCH_TP_TAGSGROUP = "TagsGroup";
var SRCH_TP_TAG = "Tag";
var SRCH_TP_NAME = "Name";
var SRCH_TP_VALUE = "Value";
var SRCH_TP_DISPLAYNAME = "DisplayName";
var SRCH_TP_DISPLAYVALUE = "DisplayValue";
var SRCH_TP_TAGTYPE = "TagType";
var SRCH_TP_TAGSCOPE = "TagScope";
var SRCH_TP_EXTRACTING = "Extracting";
var SRCH_TP_RIC = "Ric";
var SRCH_TP_CUSIP = "Cusip";
var SRCH_TP_SECOMPID = "SECompId";
var SRCH_TP_GVKEY = "GVKey";
var SRCH_TP_SYMBOL = "Symbol";
var SRCH_TP_ISCOMPLEX = "IsComplex";
var SRCH_TP_COMPANYNAME = "CompanyName";

// Enum AttributeNames
var SRCH_AN_SEARCHID = "AttributeNames";
var SRCH_AN_SEARCHNAME = "SearchName";
var SRCH_AN_TMCSEARCHNAME = "TMCSearchName";
var SRCH_AN_SEARCHALERT = "SearchAlert";
var SRCH_AN_TAGGROUPID = "TagGroupID";
var SRCH_AN_SYMBOLPRIMARYONLY = "SymbolPrimaryOnly";
var SRCH_AN_PERIODDISPLAYSTARTDATE = "PeriodDisplayStartDate";
var SRCH_AN_PERIODSTARTDATE = "PeriodStartDate";
var SRCH_AN_PERIODDISPLAYENDDATE = "PeriodDisplayEndDate";
var SRCH_AN_PERIODENDDATE = "PeriodEndDate";
var SRCH_AN_PAGEIDENTIFIER = "PageIdentifier";
var SRCH_AN_CONTAINERID = "ContainerID";
var SRCH_AN_CONTAINERNAME = "ContainerName";
var SRCH_AN_CONTAINERTYPE = "ContainerType";
var SRCH_AN_TEXTERROR = "TextError";
var SRCH_AN_COUNTERRORS = "CountErrors";
var SRCH_AN_CONTAINERSCOPE = "ContainerScope";
var SRCH_AN_CUSTOMERRORMESSAGE = "CustomErrorMessage";

//Default values for Period
var SRCH_PERIOD_DISPLAYNAME = "Period";
var SRCH_PERIOD_VALUE = "Last7Days";
var SRCH_PERIOD_DISPLAYVALUE = "Last 7 Days";
var Folders_SRCH_PERIOD_VALUE = "Last7Days";
var Folders_SRCH_PERIOD_DISPLAYVALUE = "Last 7 Days";

// Enum TagExtractingEnum
var SRCH_EX_YES = "Yes";
var SRCH_EX_NO = "No";

// Enum Keyword
var KEY_UNDEFINED = "undefined";
var KEY_SEARCHES = "searches";
var KEY_SEARCHABLE = "searchable";
var KEY_METADATA = "metadata";
var KEY_PREFERENCES = "Preferences";
var KEY_FEEDS = "feeds";
var KEY_BLOGPOSTS = "blogposts";
var KEY_BLOGS = "blogs";
var KEY_MESSAGES = "messages";
var KEY_FOLDERMESSAGES = "foldermessages";
var KEY_FOLDERS = "folders";
var KEY_USERS = "users";
var KEY_CMS = "cms";
var KEY_CMT = "cmt";
var KEY_PORTFOLIO = "portfolio";
var KEY_PORTFOLIOTAGS = "portfoliotags";
var KEY_COMMENTS = "comments";
var KEY_PAGE = "page";
var KEY_PAGESOURCE = "pagesource";
var KEY_PAGEGROUPS = "pagegroups";
var KEY_CONTAINERS = "containers";
var KEY_MODULES = "modules";
var KEY_RESOLVE = "resolve";
var KEY_UNRESOLVE = "unresolve";
var KEY_ALERTS = "alerts";
var KEY_SOURCEALERTS = "sourcealerts";
var KEY_INDUSTRY = "industry";
var KEY_CALENDARS = "calendars";
var KEY_EVENTS = "events";
var KEY_CUSTROMMETASTRUCTURE = "custrommetastructure";
var KEY_TAGCLOUD = "tagcloud";
var KEY_MAINCONTENTMODULE = "maincontentmodule";
var KEY_TOPIC = "topic";
var KEY_BROKER = "broker";
var KEY_FEEDCATEGORY = "feedcategory";
var KEY_NEWFEEDCATEGORY = "newfeedcategory";
var KEY_BLOGPOSTCATEGORY = "blogpostcategory";
var KEY_RECENTITEM = "recentitem";
var KEY_LANGUAGE = "language";
var KEY_HOMESECTION = "homesection";
var KEY_MAINGRID = "maingrid";
var KEY_NEWSLETTERS = "newsletters";
var KEY_MAINGRIDNS = "maingridns";
var KEY_NEWSLETTERSARCHIVE = "newslettersarchive";
var KEY_NEWSLETTERARCHIVEPAGER = "newsletterarchivepager";
var KEY_NEWSLETTERRSSOUT = "newsletterrssout";
var KEY_CUSTOMTOPIC = "customtopic";

// Enum AlertCategoryFlags
var AC_NONE = "None";
var AC_INFONGEN_NEWS = "InfoNGEN_News";
var AC_TMC_MODELS = "TMC_Models";
var AC_TMC_RESEARCH = "TMC_Research";
var AC_TMC_ESTIMATES = "TMC_Estimates";
var AC_TMC_FILINGS = "TMC_Filings";
var AC_TMC_EVENTS = "TMC_Events";

// Enum Event
var EVT_REFRESH_MODULES = "Refresh_Modules";
var EVT_CMS_CREATED = "CMS_Created";
var EVT_CMS_MODIFIED = "CMS_Modified";
var EVT_CMS_ADDED = "CMS_Added";
var EVT_PAGE_CREATED = "Page_Created";
var EVT_PAGE_MODIFIED = "Page_Modified";
var EVT_PAGE_ADDED = "Page_Added";
var EVT_PAGE_DELETED = "Page_Deleted";
var EVT_EMAILLIST_UPDATED = "EmailList_Updated";
var EVT_ALERTS_OPTIONS_UPDATED = "Alerts_Options_Updated";
var EVT_ALERTS_COLOR_UPDATED = "Alerts_Color_Updated";
var EVT_ALERTS_FONT_UPDATED = "Alerts_Font_Updated";
var EVT_APPLICATION_COMPONENTS_UPDATED = "Application_Components_Updated";
var EVT_PREFERENCES_UPDATED = "Preferences_Updated";

// Enum UsageLoggerEvents
var USG_EVT_NONE = "None";
var USG_EVT_LOGIN = "Login";
var USG_EVT_NAVFEEDS = "NavFeeds";
var USG_EVT_NAVCALENDARS = "NavCalendars";
var USG_EVT_NAVBLOGS = "NavBlogs";
var USG_EVT_NAVFOLDERS = "NavFolders";
var USG_EVT_NAVHOME = "NavHome";
var USG_EVT_NAVPAGES = "NavPages";
var USG_EVT_NAVFEED = "NavFeed";
var USG_EVT_NAVBLOG = "NavBlog";
var USG_EVT_NAVBLOGAUTHOR = "NavBlogAuthor";
var USG_EVT_NAVFOLDER = "NavFolder";
var USG_EVT_NAVMYACCOUNT = "NavMyAccount";
var USG_EVT_NAVADMINISTRATION = "NavAdministration";
var USG_EVT_ACTIONTAG = "ActionTag";
var USG_EVT_ACTIONITEMPROPERTIES = "ActionItemProperties";
var USG_EVT_ACTIONNEWFOLDER = "ActionNewFolder";
var USG_EVT_ACTIONNEWSEARCH = "ActionNewSearch";
var USG_EVT_ACTIONSAVESEARCH = "ActionSaveSearch";
var USG_EVT_ACTIONNEWSEARCHFILTER = "ActionNewSearchFilter";
var USG_EVT_ACTIONOPENBLOGPOST = "ActionOpenBlogPost";
var USG_EVT_ACTIONOPENEVENT = "ActionOpenEvent";
var USG_EVT_ACTIONOPENDOCUMENT = "ActionOpenDocument";
var USG_EVT_ACTIONSINGLECOMPANYCONTEXTSEARCH = "ActionSingleCompanyContextSearch";
var USG_EVT_ACTIONSEARCHSTRINGSEARCH = "ActionSearchStringSearch";

// Enum PredefinedSearchLocation
var PSL_UNDEFINED = "0";
var PSL_AVAILABLEFEEDS = "1";
var PSL_SUBSCRIBEDFEEDS = "2";
var PSL_UNSUBSCRIBEDFEEDS = "3";
var PSL_FAVORITEFEEDS = "4";
var PSL_WRITABLECHANNELS = "5";
var PSL_LISTOFFEEDS = "6";
var PSL_AVAILABLECALENDARS = "7";
var PSL_SUBSCRIBEDCALENDARS = "8";
var PSL_UNSUBSCRIBEDCALENDARS = "9";
var PSL_FAVORITECALENDARS = "10";
var PSL_WRITABLECALENDARS = "11";
var PSL_LISTOFCALENDARS = "12";
var PSL_MYCALENDARS = "13";
var PSL_AVAILABLEUSERBLOGS = "14";
var PSL_SUBSCRIBEDUSERBLOGS = "15";
var PSL_UNSUBSCRIBEDUSERBLOGS = "16";
var PSL_FAVORITEUSERBLOGS = "17";
var PSL_LISTOFUSERBLOGS = "18";
var PSL_WRITABLEUSERBLOGS = "19";
var PSL_MYUSERBLOGS = "20";
var PSL_AVAILABLEFOLDERS = "21";
var PSL_SUBSCRIBEDFOLDERS = "22";
var PSL_UNSUBSCRIBEDFOLDERS = "23";
var PSL_LISTOFFOLDERS = "24";
var PSL_WRITABLEFOLDERS = "25";
var PSL_ALERTSFOLDER = "26";

var SLIDToPIDMap = new Array();
SLIDToPIDMap["Undefined"]="Undefined";SLIDToPIDMap["Blogs"]="Blogs";SLIDToPIDMap["Calendars"]="Calendars";SLIDToPIDMap["Feeds"]="Feeds";SLIDToPIDMap["Folders"]="Folders";SLIDToPIDMap["Trends"]="Undefined";
// Enum RSSFeedResolvingStatus
var RSS_RSLV_UNDEFINED = "Undefined";
var RSS_RSLV_RESOLVING = "Resolving";
var RSS_RSLV_RESOLVED = "Resolved";
var RSS_RSLV_UNRESOLVED = "Unresolved";

// Enum HomeSectionType
var HOME_ST_UNDEFINED = "0";
var HOME_ST_CONTAINER = "1";
var HOME_ST_SEARCH = "2";
var HOME_ST_LINK = "3";
var HOME_ST_SEARCHTAGS = "4";

// Enum GridLayoutElement
var HOME_GRIDLAYOUT_NONE = "0";
var HOME_GRIDLAYOUT_TITLE = "1";
var HOME_GRIDLAYOUT_PROVIDER = "2";
var HOME_GRIDLAYOUT_DATETIME = "4";
var HOME_GRIDLAYOUT_TICKER = "8";
var HOME_GRIDLAYOUT_RELATEDITEMS = "16";

// Enum ApplicationSections
var APP_APPLICATIONSECTIONS = {Home:1, Feeds:2, Folders:4, Calendars:8, Blogs:16, Trends:32, NewslettersV2:64};

// MonitoringActions 
var MA_Undefined = "Undefined (*)";
var MA_Open = "Open (*)";
var MA_Resolve = "Resolve (*)";
var MA_Save = "Save (*)";
var MA_Navigate = "Navigate (*)";
var MA_InitialLoad = "InitialLoad";
var MA_Refresh = "Refresh";
var MA_Login = "Login";
var MA_Registration = "Registration";
var MA_ExecuteCommand = "ExecuteCommand (*)";
var MA_SwitchWideScreen = "SwitchWideScreen";
var MA_ContentViewSwitch = "ContentViewSwitch";
var MA_BrowseDirectory = "BrowseDirectory";
var MA_DeleteContainer = "DeleteContainer";
var MA_DeleteMessage = "DeleteMessage";
var MA_DeleteMessageNewsletters = "DeleteMessageNewsletters";
var MA_ShowContainerMessages = "ShowContainerMessages";
var MA_OpenMoreItems = "OpenMoreItems";
var MA_ClosePopupRefresh = "ClosePopupRefresh";
var MA_UploadOneFile = "UploadOneFile";
var MA_LookForPrincipals = "LookForPrincipals";
var MA_DeletePrincipal = "DeletePrincipal";
var MA_RemoveTeamUser = "RemoveTeamUser";
var MA_AddTeamUser = "AddTeamUser";
var MA_ChangeAdminRights = "ChangeAdminRights";
var MA_UserGroupFind = "UserGroupFind";
var MA_RemoveAssignment = "RemoveAssignment";
var MA_AddAssignment = "AddAssignment";
var MA_ToggleIncludeSubFolders = "ToggleIncludeSubFolders";
var MA_ExpandMessageView = "ExpandMessageView";
var MA_ChangeDataPage = "ChangeDataPage";
var MA_ChangeSubscription = "ChangeSubscription";
var MA_ChangeFavorite = "ChangeFavorite";
var MA_EmailIt = "EmailIt";
var MA_GetPrompt = "GetPrompt";
var MA_RunSavedSearch = "RunSavedSearch";
var MA_RunInputSearch = "RunInputSearch";
var MA_SaveInputSearch = "SaveInputSearch";
var MA_ClearSearchResults = "ClearSearchResults";
var MA_SaveSearch = "SaveSearch";
var MA_RenameSearch = "RenameSearch";
var MA_DeleteSearch = "DeleteSearch";
var MA_EditSearch = "EditSearch";
var MA_SaveAlert = "SaveAlert";
var MA_DeleteAlert = "DeleteAlert";
var MA_RefreshSection = "RefreshSection";
var MA_MoveHomeSection = "MoveHomeSection";
var MA_RemoveHomeSection = "RemoveHomeSection";
var MA_PreviewHomeSection = "PreviewHomeSection";
var MA_ToggleHomeSection = "ToggleHomeSection";
var MA_AddHomeSection = "AddHomeSection";
var MA_UpdateHomeLayout = "UpdateHomeLayout";
var MA_CreatePortfolio = "CreatePortfolio";
var MA_DeletePortfolio = "DeletePortfolio";
var MA_RenamePortfolio = "RenamePortfolio";
var MA_GetPortfolio = "GetPortfolio";
var MA_AddToPortfolio = "AddToPortfolio";
var MA_RemoveFromPortfolio = "RemoveFromPortfolio";
var MA_OpenAlertEditor = "OpenAlertEditor";
var MA_OpenAuthenticationEditor = "OpenAuthenticationEditor";
var MA_OpenCompanyEditor = "OpenCompanyEditor";
var MA_OpenCountryEditor = "OpenCountryEditor";
var MA_OpenCustomFeedBrandingEditor = "OpenCustomFeedBrandingEditor";
var MA_OpenEntitlementEditor = "OpenEntitlementEditor";
var MA_OpenIndustryEditor = "OpenIndustryEditor";
var MA_OpenKeywordEditor = "OpenKeywordEditor";
var MA_OpenMonitoringFeedEditor = "OpenMonitoringFeedEditor";
var MA_OpenPrimaryCompanyEditor = "OpenPrimaryCompanyEditor";
var MA_OpenRegionEditor = "OpenRegionEditor";
var MA_OpenTopicEditor = "OpenTopicEditor";

// MonitoringPages 
var MP_LoginPage = "Login Page";
var MP_UserCategoriesSetup = "UserCategoriesSetup";
var MP_UserLanguagesSetup = "UserLanguagesSetup";
var MP_FolderNew = "FolderNew (*)";
var MP_FolderProperties = "FolderProperties (*)";
var MP_BlogNew = "Blog New";
var MP_BlogProperties = "Blog Properties";
var MP_CalendarNew = "Calendar New";
var MP_CalendarProperties = "Calendar Properties";
var MP_ChannelNew = "Channel New";
var MP_ChannelProperties = "Channel Properties";
var MP_RSSFeedNew = "RSSFeed New";
var MP_RSSFeedProperties = "RSSFeed Properties";
var MP_FeedItemProperties = "FeedItem Properties";
var MP_FeedItemNew = "FeedItem New";
var MP_BlogPostProperties = "BlogPost Properties";
var MP_BlogPostNew = "BlogPost New";
var MP_EventProperties = "Event Properties";
var MP_EventNew = "Event New";
var MP_DocumentProperties = "Document Properties";
var MP_DocumentNew = "Document New";
var MP_FileProperties = "File Properties";
var MP_FileNew = "File New";
var MP_CommentProperties = "Comment Properties";
var MP_CommentNew = "Comment New";
var MP_EditUser = "EditUser";
var MP_CreateUser = "CreateUser";
var MP_EditTeam = "EditTeam";
var MP_CreateTeam = "CreateTeam";
var MP_EditCompany = "EditCompany";
var MP_CreateCompany = "CreateCompany";

//Brand names
// Enum BrandType
var BRANDNAME_STANDARD = "Standard";
var BRANDNAME_LITE = "Lite";
var BRANDNAME_SNP = "SnP";
var BRANDNAME_TMC = "Tmc";
var BRANDNAME_MERRILLLYNCH = "MerrillLynch";
var BRANDNAME_COBRANDED = "CoBranded";


var TPDateFilterValues = [{'name':"In the last 15 min", 'value':"Last15Minutes"},{'name':"In the last 30 min", 'value':"Last30Minutes"},{'name':"In the last hour", 'value':"Last1Hour"},{'name':"In the last 2 hours", 'value':"Last2Hours"},{'name':"In the last 24 hours", 'value':"Last24Hours"},{'name':"Today", 'value':"Today"},{'name':"This Week", 'value':"ThisWeek"},{'name':"Last 7 Days", 'value':"Last7Days"},{'name':"Last 30 Days", 'value':"Last30Days"},{'name':"Last 60 Days", 'value':"Last60Days"},{'name':"Last Year", 'value':"LastYear"},{'name':"All Time", 'value':"AllTime"}];
var TPTrendsDateFilterValues = [{'name':"Last 3 Days", 'value':"Last3Days"},{'name':"Last 5 Days", 'value':"Last5Days"},{'name':"Last 7 Days", 'value':"Last7Days"},{'name':"Last 14 Days", 'value':"Last14Days"},{'name':"Last 30 Days", 'value':"Last30Days"},{'name':"Last 60 Days", 'value':"Last60Days"},{'name':"Last 90 Days", 'value':"Last90Days"},{'name':"Last 120 Days", 'value':"Last120Days"},{'name':"Last 150 Days", 'value':"Last150Days"},{'name':"Last 180 Days", 'value':"Last180Days"}];
var TPTrendsMovingAverageDaysValues = [{'name':"None", 'value':"None"},{'name':"3 Days", 'value':"In3Days"},{'name':"5 Days", 'value':"In5Days"},{'name':"7 Days", 'value':"In7Days"},{'name':"14 Days", 'value':"In14Days"},{'name':"21 Days", 'value':"In21Days"},{'name':"30 Days", 'value':"In30Days"}];
var TPCalendarDateFilterValues = [{'name':"Last 30 Days", 'value':"Last30Days"},{'name':"Last 7 Days", 'value':"Last7Days"},{'name':"Today", 'value':"Today"},{'name':"Next 7 Days", 'value':"Next7Days"},{'name':"Next 14 Days", 'value':"Next14Days"},{'name':"Next 30 Days", 'value':"Next30Days"},{'name':"Next 60 Days", 'value':"Next60Days"}];
var TPFileTypeFilterValues = [{'name':"Unfiltered", 'value':"Undefined"},{'name':"Adobe Acrobat PDF (.pdf)", 'value':"pdf"},{'name':"Microsoft Word (.doc)", 'value':"doc"},{'name':"Microsoft Excel (.xls)", 'value':"xls"},{'name':"Microsoft Powerpoint (.ppt)", 'value':"ppt"}];
var TPSearchTagsOrderArray = new Array();TPSearchTagsOrderArray.push({"name":"Symbol","order":0});TPSearchTagsOrderArray.push({"name":"Portfolio","order":1});TPSearchTagsOrderArray.push({"name":"Topic","order":2});TPSearchTagsOrderArray.push({"name":"Keyword","order":3});TPSearchTagsOrderArray.push({"name":"FileType","order":4});TPSearchTagsOrderArray.push({"name":"Text","order":5});TPSearchTagsOrderArray.push({"name":"Period","order":6});TPSearchTagsOrderArray.push({"name":"FeedCategory","order":7});TPSearchTagsOrderArray.push({"name":"Provider","order":8});TPSearchTagsOrderArray.push({"name":"ContainerSearchScope","order":9});TPSearchTagsOrderArray.push({"name":"Feed","order":10});TPSearchTagsOrderArray.push({"name":"Folder","order":11});TPSearchTagsOrderArray.push({"name":"Calendar","order":12});TPSearchTagsOrderArray.push({"name":"Blog","order":13});TPSearchTagsOrderArray.push({"name":"BlogCategory","order":14});TPSearchTagsOrderArray.push({"name":"Industry","order":15});TPSearchTagsOrderArray.push({"name":"Broker","order":16});TPSearchTagsOrderArray.push({"name":"Region","order":17});TPSearchTagsOrderArray.push({"name":"Country","order":18});TPSearchTagsOrderArray.push({"name":"Language","order":19});TPSearchTagsOrderArray.push({"name":"SourceAlerts","order":20});TPSearchTagsOrderArray.push({"name":"AlertSubscriptionID","order":21});TPSearchTagsOrderArray.push({"name":"AlertTypeFlags","order":22});TPSearchTagsOrderArray.push({"name":"CustomTopics","order":23});
// Limits' constants
var ContainerLimits ={"NAME":32,"TITLE":1024,"SYNOPSIS":1024,"KEYWORDS":1024,"XML_DATA":2147483647,"FILTER_NAME":32,"META_STRUCT_NAME":1024,"META_TEMPLATE_NAME":32,"ACRONYM":32,"EMAIL_PREFIX":256};
var MessageLimits ={"SUBJECT":256,"BODY":2147483647};
var AttachmentLimits ={"NAME":256,"LENGTH":2147483647};
// Search Tags Collection
function tpvar_SearchTagInfo(id, type, hint, dispname, advdispname, description, longhint, availablefortagging){this.id = id;this.type = type;this.hint = hint;this.longhint = longhint;this.dispname = dispname;this.advdispname = advdispname;this.description = description;this.availablefortagging = availablefortagging;}
var SRCH_SEARCHTAGS = new Array(new tpvar_SearchTagInfo(SRCH_TN_INDUSTRY, 'metadata', 'in', 'industry', 'Industries', 'on industry codes ', 'industry', true),new tpvar_SearchTagInfo(SRCH_TN_KEYWORD, 'metadata', 'kw', 'keyword', 'Tags', 'on keyword tags', 'keyword', true),new tpvar_SearchTagInfo(SRCH_TN_PORTFOLIO, 'other', 'pf', 'portfolio', 'Portfolio', 'on a portfolio', 'portfolio', true),new tpvar_SearchTagInfo(SRCH_TN_TEXT, 'other', 'tx', 'text', 'Text', 'on full text (Use " " for exact text matches)', 'text', true),new tpvar_SearchTagInfo(SRCH_TN_PERIOD, 'other', 'dt', 'date', 'Period', 'on a date or date range', 'date', true),new tpvar_SearchTagInfo(SRCH_TN_SAVEDSEARCH, 'other', 'ss', 'savedsearch', '', 'runs a saved search', 'savedsearch', true),new tpvar_SearchTagInfo(SRCH_TN_FEED, 'container', 'fe', 'feed', 'In Feeds', 'on feed names', 'feed', true),new tpvar_SearchTagInfo(SRCH_TN_FOLDER, 'container', 'fd', 'folder', 'In Folders', 'on folder names', 'folder', true),new tpvar_SearchTagInfo(SRCH_TN_BLOG, 'container', 'bg', 'blog', 'In Blogs', 'on blog names or bloggers', 'blog', true),new tpvar_SearchTagInfo(SRCH_TN_CALENDAR, 'container', 'cd', 'calendar', 'Calendars', 'on calendar name', 'calendar', true),new tpvar_SearchTagInfo(SRCH_TN_BLOGGERNAME, 'other', 'bn', 'Blogger Name', '', 'Favorite Blogger Name', 'BloggerName', true),new tpvar_SearchTagInfo(SRCH_TN_TOPIC, 'metadata', 'top', 'Topic', 'Topics', 'on topic', 'topic', false),new tpvar_SearchTagInfo(SRCH_TN_PROVIDER, 'other', 'pr', 'provider', 'Providers', 'on provider names', 'provider', true),new tpvar_SearchTagInfo(SRCH_TN_CUSTOMTOPIC, 'metadata', 'ctop', 'Custom Topic', 'Custom Topics', 'on custom topic', 'ctopic', false),new tpvar_SearchTagInfo(SRCH_TN_BROKER, 'metadata', 'br', 'broker', 'Brokers', 'on broker names', 'broker', true),new tpvar_SearchTagInfo(SRCH_TN_SYMBOL, 'metadata', 'sy', 'symbol', 'Symbols', 'on ticker symbols', 'symbol', true),new tpvar_SearchTagInfo(SRCH_TN_REGION, 'metadata', 're', 'region', 'Region', 'on region names', 'region', true),new tpvar_SearchTagInfo(SRCH_TN_COUNTRY, 'metadata', 'cn', 'country', 'Country', 'on country names', 'country', true),new tpvar_SearchTagInfo(SRCH_TN_LANGUAGE, 'other', 'la', 'language', 'Languages', 'on language', 'language', true),new tpvar_SearchTagInfo(SRCH_TN_FEEDCATEGORY, 'other', 'ca', 'category', 'In Category', 'on category names', 'category', true),new tpvar_SearchTagInfo(SRCH_TN_BLOGCATEGORY, 'other', 'bc', 'blogcategory', 'In Category', 'on blog category names', 'blogcategory', true));
var SRCH_SEARCHTAGS_TMC = new Array(new tpvar_SearchTagInfo(SRCH_TN_INDUSTRY, 'metadata', 'in', 'industry', 'Industries', 'on industry codes ', 'industry', true),new tpvar_SearchTagInfo(SRCH_TN_KEYWORD, 'metadata', 'kw', 'keyword', 'Tags', 'on keyword tags', 'keyword', true),new tpvar_SearchTagInfo(SRCH_TN_PORTFOLIO, 'other', 'pf', 'portfolio', 'Portfolio', 'on a portfolio', 'portfolio', true),new tpvar_SearchTagInfo(SRCH_TN_TEXT, 'other', 'tx', 'text', 'Keywords', 'on full text (Use " " for exact text matches)', 'text', true),new tpvar_SearchTagInfo(SRCH_TN_PERIOD, 'other', 'dt', 'date', 'Period', 'on a date or date range', 'date', true),new tpvar_SearchTagInfo(SRCH_TN_SAVEDSEARCH, 'other', 'ss', 'savedsearch', '', 'runs a saved search', 'savedsearch', true),new tpvar_SearchTagInfo(SRCH_TN_FEED, 'container', 'fe', 'feed', 'In Feeds', 'on feed names', 'feed', true),new tpvar_SearchTagInfo(SRCH_TN_FOLDER, 'container', 'fd', 'folder', 'In Folders', 'on folder names', 'folder', true),new tpvar_SearchTagInfo(SRCH_TN_BLOG, 'container', 'bg', 'blog', 'In Blogs', 'on blog names or bloggers', 'blog', true),new tpvar_SearchTagInfo(SRCH_TN_CALENDAR, 'container', 'cd', 'calendar', 'Calendars', 'on calendar name', 'calendar', true),new tpvar_SearchTagInfo(SRCH_TN_BLOGGERNAME, 'other', 'bn', 'Blogger Name', '', 'Favorite Blogger Name', 'BloggerName', true),new tpvar_SearchTagInfo(SRCH_TN_TOPIC, 'metadata', 'top', 'Topic', 'Topics', 'on topic', 'topic', false),new tpvar_SearchTagInfo(SRCH_TN_PROVIDER, 'other', 'pr', 'provider', 'Providers', 'on provider names', 'provider', true),new tpvar_SearchTagInfo(SRCH_TN_CUSTOMTOPIC, 'metadata', 'ctop', 'Custom Topic', 'Custom Topics', 'on custom topic', 'ctopic', false),new tpvar_SearchTagInfo(SRCH_TN_BROKER, 'metadata', 'br', 'broker', 'Brokers', 'on broker names', 'broker', true),new tpvar_SearchTagInfo(SRCH_TN_SYMBOL, 'metadata', 'sy', 'symbol', 'Symbols', 'on ticker symbols', 'symbol', true),new tpvar_SearchTagInfo(SRCH_TN_REGION, 'metadata', 're', 'region', 'Region', 'on region names', 'region', true),new tpvar_SearchTagInfo(SRCH_TN_COUNTRY, 'metadata', 'cn', 'country', 'Country', 'on country names', 'country', true),new tpvar_SearchTagInfo(SRCH_TN_LANGUAGE, 'other', 'la', 'language', 'Languages', 'on language', 'language', true),new tpvar_SearchTagInfo(SRCH_TN_FEEDCATEGORY, 'other', 'ca', 'category', 'In Category', 'on category names', 'category', true),new tpvar_SearchTagInfo(SRCH_TN_BLOGCATEGORY, 'other', 'bc', 'blogcategory', 'In Category', 'on blog category names', 'blogcategory', true));
function GETSTIBYID(id){if (!IS_TMC_USER){for(var i=0, ic=SRCH_SEARCHTAGS.length; i<ic; ++i)if (SRCH_SEARCHTAGS[i].id == id)return SRCH_SEARCHTAGS[i];} else if (IS_TMC_USER) {for(var i=0, ic=SRCH_SEARCHTAGS_TMC.length; i<ic; ++i)if (SRCH_SEARCHTAGS_TMC[i].id == id)return SRCH_SEARCHTAGS_TMC[i];}return null;}
function GETSTIBYLONGHINT(longhint){var llh = longhint.toLowerCase();if (!IS_TMC_USER){for(var i=SRCH_SEARCHTAGS.length-1;i>=0;--i)if (SRCH_SEARCHTAGS[i].longhint.toLowerCase() == llh)return SRCH_SEARCHTAGS[i];} else if (IS_TMC_USER) {for(var i=SRCH_SEARCHTAGS_TMC.length-1;i>=0;--i)if (SRCH_SEARCHTAGS_TMC[i].longhint.toLowerCase() == llh)return SRCH_SEARCHTAGS_TMC[i];}return null;}
function GETSTIBYHINT(hint){var lh = hint.toLowerCase();if (!IS_TMC_USER){for(var i=SRCH_SEARCHTAGS.length-1; i>=0; --i)if (SRCH_SEARCHTAGS[i].hint.toLowerCase() == lh)return SRCH_SEARCHTAGS[i];} else if (IS_TMC_USER) {for(var i=SRCH_SEARCHTAGS_TMC.length-1; i>=0; --i)if (SRCH_SEARCHTAGS_TMC[i].hint.toLowerCase() == lh)return SRCH_SEARCHTAGS_TMC[i];}return null;}
// Location Searches
var LOCATIONSEARCH ={"Feeds":"In the News","Trends":"In the News"};
// NS sending time
var NS_SENDING_TIME_24 ={"00:00":"00:00","00:30":"00:30","01:00":"01:00","01:30":"01:30","02:00":"02:00","02:30":"02:30","03:00":"03:00","03:30":"03:30","04:00":"04:00","04:30":"04:30","05:00":"05:00","05:30":"05:30","06:00":"06:00","06:30":"06:30","07:00":"07:00","07:30":"07:30","08:00":"08:00","08:30":"08:30","09:00":"09:00","09:30":"09:30","10:00":"10:00","10:30":"10:30","11:00":"11:00","11:30":"11:30","12:00":"12:00","12:30":"12:30","13:00":"13:00","13:30":"13:30","14:00":"14:00","14:30":"14:30","15:00":"15:00","15:30":"15:30","16:00":"16:00","16:30":"16:30","17:00":"17:00","17:30":"17:30","18:00":"18:00","18:30":"18:30","19:00":"19:00","19:30":"19:30","20:00":"20:00","20:30":"20:30","21:00":"21:00","21:30":"21:30","22:00":"22:00","22:30":"22:30","23:00":"23:00","23:30":"23:30"};var NS_SENDING_TIME_12 ={"12:00 AM":"00:00","12:30 AM":"00:30","1:00 AM":"01:00","1:30 AM":"01:30","2:00 AM":"02:00","2:30 AM":"02:30","3:00 AM":"03:00","3:30 AM":"03:30","4:00 AM":"04:00","4:30 AM":"04:30","5:00 AM":"05:00","5:30 AM":"05:30","6:00 AM":"06:00","6:30 AM":"06:30","7:00 AM":"07:00","7:30 AM":"07:30","8:00 AM":"08:00","8:30 AM":"08:30","9:00 AM":"09:00","9:30 AM":"09:30","10:00 AM":"10:00","10:30 AM":"10:30","11:00 AM":"11:00","11:30 AM":"11:30","12:00 PM":"12:00","12:30 PM":"12:30","1:00 PM":"13:00","1:30 PM":"13:30","2:00 PM":"14:00","2:30 PM":"14:30","3:00 PM":"15:00","3:30 PM":"15:30","4:00 PM":"16:00","4:30 PM":"16:30","5:00 PM":"17:00","5:30 PM":"17:30","6:00 PM":"18:00","6:30 PM":"18:30","7:00 PM":"19:00","7:30 PM":"19:30","8:00 PM":"20:00","8:30 PM":"20:30","9:00 PM":"21:00","9:30 PM":"21:30","10:00 PM":"22:00","10:30 PM":"22:30","11:00 PM":"23:00","11:30 PM":"23:30"};
// NS event names
var NS_EVENTS ={"OnHeadlinesRefresh":"_OnHeadlinesRefresh","OnLoadDS":"_OnLoadDS","OnNewslettersGridRefresh":"_OnNewslettersGridRefresh","OnLoadArchiveEmailDS":"OnLoadArchiveEmailDS"};
// NS archive filter by date
var NS_ARCHIVE_FILTER_BY_DATE ={"Last7days":"Last7days","Last2weeks":"Last2weeks","Last30days":"Last30days","Last60days":"Last60days","Last180days":"Last180days","Lastyear":"Lastyear"};
var AlertItem ={"ItemName":"AlertItem","ItemIDName":"ID","PN_ID":"ID","PN_TYPE":"Type","PN_RECURRENCE":"Recur","PN_TYPE_INT":"IntType","PN_RECURRENCE_INT":"IntRecur","PN_SOURCE_TYPE":"SrcType","PN_SOURCE_TYPE_STRING":"sSrcType","PN_SEARCHID":"SrchId","PN_SOURCE_NAME":"SrcName","PN_CONTAINERTYPE":"CntType","PN_CONTAINERID":"CntId","PN_EMAIL":"Email"};
var MetadataItem ={"ItemName":"MetadataItem","ItemIDName":"ID"};
var AttachmentItem ={"ItemName":"AttachmentItem","ItemIDName":"ID","PN_ID":"ID","PN_PARENTID":"ParentID","PN_NAME":"Name","PN_CONTENTTYPE":"ContentType","PN_TYPE":"BodyType","PN_PRIMARYSYMBOLS":"PrmSmb","PN_SECONDARYSYMBOLS":"SecSmb"};
var BloggerItem ={"ItemName":"BloggerItem","ItemIDName":"ID","PN_ID":"ID","PN_TITLE":"Title","PN_ISFAVORITE":"IsFvt","PN_TOTALPOSTSNUMBER":"PostsCnt","PN_LAST30DAYSPOSTSNUMBER":"LPostsCnt","PN_AUTHORTYPE":"BlType"};
var BrokerItem ={"ItemName":"BrokerItem","ItemIDName":"ID","PN_NAME":"Name","PN_CODE":"Code","PN_ID":"ID"};
var CategoryItem ={"ItemName":"CategoryItem","ItemIDName":"ID","PN_ID":"ID","PN_CATEGORYNAME":"CatName"};
var CommentItem ={"ItemName":"CommentItem","ItemIDName":"ID","PN_SUBJECT":"Subject","PN_CREATEDATE":"CDate","PN_ISAUTHOR":"IsAuthor","PN_AUTHORID":"AuthorID","PN_AUTHORNAME":"From","PN_BODY":"Body","PN_ID":"ID","PN_PARENTID":"ParentID","PN_NAME":"Name","PN_CONTENTTYPE":"ContentType","PN_TYPE":"BodyType","PN_PRIMARYSYMBOLS":"PrmSmb","PN_SECONDARYSYMBOLS":"SecSmb"};
var ContainerItem ={"ItemName":"ContainerItem","ItemIDName":"ID","PN_ID":"ID","PN_PARENTID":"PARENTID","PN_TITLE":"Title","PN_OWNERDISPLAYNAME":"Owner","PN_OWNERID":"OwnerID","PN_TYPE":"Type","PN_FEEDSOURCE":"Src","PN_ISSUBSCRIBED":"IsSbscr","PN_ISFAVORITE":"IsFvt","PN_ISSHARED":"IsShared","PN_ISOWNER":"IsOwner","PN_ISREADER":"IsReader","PN_CATEGORYID":"CategoryID","PN_CATEGORYNAME":"Category","PN_METADATA":"MData","PN_ALERT_ID":"AlrId","PN_CREATORID":"CreatorID","PN_RSSLINK":"RSSLink","PN_SYNOPSIS":"Synopsis","PN_LANGUAGE":"Language","PN_PROVIDER":"Provider","PN_CONTENTACCESSTYPE":"AccessType","PN_ALLOWREMOVECONTAINER":"AllowRemCont"};
var CoverageItem ={"ItemName":"CoverageItem","ItemIDName":"ID","PN_NAME":"Name","PN_ID":"ID","PN_ALLOWCHANGEPROPERTIES":"allowCP","PN_ALLOWSETRIGHTS":"allowSR","PN_ISSHARED":"isShared","PN_ISNEW":"IsNew","PN_NEWCODES":"NewCodes"};
var CustomMetaStructItem ={"ItemName":"CustomMetaStructItem","ItemIDName":"ID","PN_ID":"ID","PN_TAG":"Tag","PN_CREATORID":"CrtID","PN_NAME":"Name","PN_TYPE":"Type","PN_DISPLAYTYPE":"DType"};
var FeedCategoryItem ={"ItemName":"FeedCategoryItem","ItemIDName":"ID","PN_RECENT_ITEM_ID":"RID","PN_ID":"ID","PN_GROUPID":"GROUPID","PN_DISPLAYVALUE":"DValue","PN_GROUP_NAME":"GNAME","PN_ISUNSUBSCRIBED":"ISUNS","PN_ISLASTINGROUP":"ILIG","PN_ISGROUP":"ISGROUP"};
var FileToUpload ={"ItemName":"FileToUpload","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_CONTENTTYPE":"ContentType","PN_SYNOPSIS":"Synopsis","PN_SELECTED":"Selected","PN_BODYTYPE":"BodyType","PN_ISINTERNAL":"IsInternal"};
var FilterItem ={"ItemName":"FilterItem","ItemIDName":"ID","PN_ID":"ID","PN_RECENT_ITEM_ID":"RID","PN_VALUE":"Value","PN_DISPLAY_VALUE":"DValue","PN_FILTER_TAG":"Tag"};
var GroupItem ={"ItemName":"GroupItem","ItemIDName":"ID","PN_ID":"ID","PN_GROUPNAME":"GName","PN_WEIGHT":"Weight"};
var MessageItemBase ={"ItemName":"MessageItemBase","ItemIDName":"ID","PN_ID":"ID","PN_TITLE":"Title","PN_SYNOPSIS":"Syn","PN_TITLEPREFIX":"tPrefix","PN_LANGUAGE":"Language","PN_CONTENTSERVER":"ContentServer"};
var HistoricalAlertItem ={"ItemName":"HistoricalAlertItem","ItemIDName":"ID","PN_MESSAGEID":"MID","PN_BODYID":"BID","PN_CLUSTERID":"CLID","PN_CREATETIME":"CTime","PN_CREATEDATE":"CDate","PN_TIMETICKS":"TT","PN_ELAPSEDTIME":"ElTime","PN_ITEMSOURCENAME":"Src","PN_ALERTSUBSCRIPTIONNAME":"Asname","PN_ALERTSUBSCRIPTIONID":"Asid","PN_CLUSTERCOUNT":"CLCNT","PN_CONTAINERID":"CONID","PN_CONTAINERTYPE":"CONTYPE","PN_PRIMARYCOMPANYID":"SbId","PN_PRIMARYCOMPANYSYMBOL":"SbSymbol","PN_PRIMARYCOMPANYNAME":"SbName","PN_CATEGORYNAME":"CATNAME","PN_DOCUMENTFORMAT":"DOCFORMAT","PN_ALERTTYPE":"Type","PN_ID":"ID","PN_TITLE":"Title","PN_SYNOPSIS":"Syn","PN_TITLEPREFIX":"tPrefix","PN_LANGUAGE":"Language","PN_CONTENTSERVER":"ContentServer"};
var HomeSectionItem ={"ItemName":"HomeSectionItem","ItemIDName":"ID","PN_ID":"ID","PN_TITLE":"Title","PN_IS_ADDED_TO_HOME":"ATH","PN_SECTION_TYPE":"SType"};
var HomeSectionSearchItem ={"ItemName":"HomeSectionSearchItem","ItemIDName":"ID","PN_SEARCH_ID":"SID","PN_ID":"ID","PN_TITLE":"Title","PN_IS_ADDED_TO_HOME":"ATH","PN_SECTION_TYPE":"SType"};
var HomeSectionContainerItem ={"ItemName":"HomeSectionContainerItem","ItemIDName":"ID","PN_CONTAINER_ID":"CID","PN_TYPE":"Type","PN_ID":"ID","PN_TITLE":"Title","PN_IS_ADDED_TO_HOME":"ATH","PN_SECTION_TYPE":"SType"};
var LookingForwardItem ={"ItemName":"LookingForwardItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"NAME","PN_VALUE":"VALUE"};
var MessageItem ={"ItemName":"MessageItem","ItemIDName":"ID","PN_IS_MANUALLY_ADDED":"IsManuallyAdded","PN_IS_COMMENT_PRESENT":"IsCommentPresent","PN_TYPE":"Type","PN_AUTHORNAME":"From","PN_AUTHORID":"AuthorID","PN_AUTHORTYPE":"AutType","PN_ISAUTHORSHIP":"IsAuthor","PN_CONTAINERNAME":"CntName","PN_ITEMSOURCENAME":"Src","PN_ITEMSOURCEID":"SrcID","PN_ITEMSOURCETYPE":"SrcType","PN_CONTAINERID":"CntID","PN_CONTAINERTYPE":"CntType","PN_ISTOPCONTAINER":"CntTop","PN_PARSED_BODY":"PBody","PN_CREATEDATE":"CDate","PN_CREATEDATETIME":"CDTime","PN_COMMENTSCOUNT":"CmtCnt","PN_LINK":"Link","PN_PROVIDER":"Provider","PN_ELAPSEDTIMESYNOPSIS":"ElTimeS","PN_ELAPSEDTIME":"ElTime","PN_ELAPSEDTIMEONLY":"ElTimeOnly","PN_REFID":"RefID","PN_REFTYPE":"RefType","PN_REFTITLE":"RefTitle","PN_STARTDATE":"SDate","PN_STARTDATE_FORMATTED":"SDateFt","PN_STARTTIME":"STime","PN_SELECTED_ITEM":"SelectedItem","PN_ENDDATE":"EDate","PN_OCCURANCE":"Occurance","PN_EVENTGROUP":"EvGroup","PN_EVENTSUBGROUP":"EvSbGroup","PN_WEIGHT":"Weight","PN_ALERTSOURCENAME":"ArtSrcName","PN_ALERTCONTAINERID":"ArtCntId","PN_ALERTCONTAINERTYPE":"ArtCntType","PN_ALERTSEARCHID":"ArtSrchID","PN_UNREAD":"Unread","PN_BODYTYPE":"BodyType","PN_METADATA":"MData","PN_ATTACHMENTSXML":"AtchXML","PN_USERBLOGPOSTCATEGORY":"BPCtg","PN_COMMENTTO":"CmtTo","PN_BLOGPOSTSUBJECT":"BPSubj","PN_ISEMAIL":"Email","PN_RELATEDCOUNT":"RelatedMessagesCount","PN_CLUSTERID":"ClusterID","PN_BODYID":"BodyID","PN_ID":"ID","PN_TITLE":"Title","PN_SYNOPSIS":"Syn","PN_TITLEPREFIX":"tPrefix","PN_LANGUAGE":"Language","PN_CONTENTSERVER":"ContentServer"};
var MetaNameValueItem ={"ItemName":"MetaNameValueItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_VALUE":"Value"};
var MetaTagItem ={"ItemName":"MetaTagItem","ItemIDName":"ID","PN_USERIDS":"UsrIDs","PN_ID":"ID","PN_NAME":"Name","PN_TITLE":"Title","PN_TAGNAME":"TagName","PN_CLIENTTAGNAME":"CTagName","PN_ISMY":"IsMy","PN_DISPLAYVALUE":"DValue"};
var CompanyTagItem ={"ItemName":"CompanyTagItem","ItemIDName":"ID","PN_SYMBOL":"Symbol","PN_DISPLAYVALUE":"DValue","PN_USERIDS":"UsrIDs","PN_ID":"ID","PN_NAME":"Name","PN_TITLE":"Title","PN_TAGNAME":"TagName","PN_CLIENTTAGNAME":"CTagName","PN_ISMY":"IsMy"};
var MetaTagInfoItem ={"ItemName":"MetaTagInfoItem","ItemIDName":"ID","PN_ID":"ID","PN_VALUE":"Value","PN_NAME":"Name","PN_TAGNAME":"TagName","PN_CLIENTTAGNAME":"CTagName","PN_DISPLAYVALUE":"DValue","PN_MESSAGECOUNT":"MsgCnt","PN_SIZE":"Size"};
var MyRecentSearchItem ={"ItemName":"MyRecentSearchItem","ItemIDName":"ID","PN_ID":"ID","PN_TITLE":"Title"};
var NewslettersArchiveEmailItem ={"ItemName":"NewslettersArchiveEmailItem","ItemIDName":"ID","PN_EMAIL_ID":"EmailID","PN_EMAIL":"Email"};
var NewslettersArchiveItem ={"ItemName":"NewslettersArchiveItem","ItemIDName":"ID","PN_ID":"ID","PN_NESWLETTER_ARCHIVE_ID":"ARCHIVE_ID","PN_FREQUENCY":"FREQUENCY","PN_LAST_PUBLISH":"LAST_PUBLISH","PN_IS_PUBLISH":"LAST_IS_PUBLISH","PN_BODY_ID":"BODY_ID","PN_STATE_ID":"STATE_ID","PN_BODY_LENGTH":"BODY_LENGTH","PN_IS_FORWARDING":"IS_FORWARDING","PN_TITLE":"TITLE","PN_COMMENT":"COMMENT"};
var NewslettersItem ={"ItemName":"NewslettersItem","ItemIDName":"ID","PN_ID":"ID","PN_USER_ID":"USER_ID","PN_TITLE":"TITLE","PN_FREQUENCY":"FREQUENCY","PN_SEND_PREVIEW_DATE":"SEND_PREVIEW_DATE","PN_EMAIL_ADDRESS":"EMAIL_ADDRESS","PN_FEEDS":"FEEDS","PN_RECIPIENT_COUNT":"RECIPIENT_COUNT","PN_LAST_PUBLISH":"LAST_PUBLISH","PN_ACTIVE_SEARCHES_COUNT":"ACTIVE_SEARCHES_COUNT","PN_COMMENT":"NCOMMENT","PN_RSS_ID":"RSS_ID","PN_IS_RSS_ENABLE":"IS_RSS_ENABLE"};
var PageGroupItem ={"ItemName":"PageGroupItem","ItemIDName":"ID","PN_TITLE":"Title","PN_ORDERNO":"OrderNo","PN_ID":"ID","PN_PAGES":"Pages"};
var PageItem ={"ItemName":"PageItem","ItemIDName":"ID","PN_NAME":"Name","PN_URL":"Url","PN_SOURCE":"Src","PN_CATEGORY":"Ctg","PN_INNEWWIN":"InNewWin","PN_ID":"ID","PN_INDEX":"Index","PN_CANDELETE":"CanDelete"};
var ResolverGeographyItem ={"ItemName":"GeographyItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_VALUE":"Value"};
var ResolverIndustryItem ={"ItemName":"IndustryItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_SHORTNAME":"SName","PN_CODE":"Code"};
var ResolverSymbolItem ={"ItemName":"SymbolItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_COUNTRY":"Country","PN_SYMBOL":"Symbol","PN_ISIN":"ISIN","PN_RIC":"Ric","PN_CUSIP":"Cusip","PN_SECOMPID":"SECompId","PN_GVKEY":"GVKey","PN_NEEDSETCOUNTRY":"NSCny"};
var ResolverUserItem ={"ItemName":"UserItem","ItemIDName":"ID","PN_EMAIL":"Email","PN_ID":"ID","PN_DISPLAYNAME":"DName"};
var RSSFeedItem ={"ItemName":"RSSFeedItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_TITLE":"Title","PN_SYNOPSIS":"Synopsis","PN_KEYWORDS":"Kwds","PN_CATEGORYID":"CtgID","PN_SOURCE":"Src","PN_INTERNAL":"Int","PN_METADATA":"MData","PN_RESOLVING_STATUS":"RslvSt"};
var SearchItem ={"ItemName":"SearchItem","ItemIDName":"ID","PN_ID":"ID","PN_TITLE":"Title","PN_ISMYSEARCH":"IsMySearch","PN_CONTAINERID":"CntID","PN_CONTAINERTYPE":"CntType","PN_CONTAINERNAME":"CntName","PN_FILTERKEY":"FKey","PN_SEARCHXML":"SXml","PN_LASTSAVED":"LSaved","PN_LASTSAVEDDATETIME":"LSavedDT","PN_LASTRUN":"LRun","PN_LASTRUNDATETIME":"LRunDT","PN_ALERT_ID":"AlrId","PN_ALERT_TYPE":"AlrType","PN_ALERT_RECURRENCE":"AlrRcr","PN_ISFORWARDED":"IsFwd","PN_SEARCHLOCATIONIDENTIFIER":"PageId"};
var SecurityPrincipalAssignmentsItem ={"ItemName":"SecurityPrincipalAssignmentsItem","ItemIDName":"ID","PN_ID":"ID","PN_DISPLAYNAME":"DName","PN_ISOWNER":"IsOwner","PN_TYPE":"Type","PN_ROLENAME":"Role","PN_PROVIDERID":"PvdID","PN_ISAUTHORSHIP":"IsAuthor","PN_COMPANY":"Comp","PN_ISSYSTEM":"IsSystem"};
var SecurityPrincipalItem ={"ItemName":"SecurityPrincipalItem","ItemIDName":"ID","PN_ID":"ID","PN_TYPE":"Type","PN_TYPE_EX":"TypeEx","PN_DISPLAYNAME":"DName","PN_COMPANY":"Comp","PN_COMPANY_ID":"CompID","PN_EMAIL":"Email","PN_VISIBLE_EMAIL":"VEmail","PN_CITY":"City","PN_ISADMIN":"IsAdmin","PN_ISSYSTEM":"IsSystem"};
var SymbologyItem ={"ItemName":"SymbologyItem","ItemIDName":"ID","PN_NAME":"Name","PN_ID":"ID","PN_ISNEW":"IsNew","PN_SYMBOL":"Symbol","PN_COUNTRY":"Country"};
var TeamItem ={"ItemName":"TeamItem","ItemIDName":"ID","PN_MEMBERS":"Members","PN_ID":"ID","PN_TYPE":"Type","PN_TYPE_EX":"TypeEx","PN_DISPLAYNAME":"DName","PN_COMPANY":"Comp","PN_COMPANY_ID":"CompID","PN_EMAIL":"Email","PN_VISIBLE_EMAIL":"VEmail","PN_CITY":"City","PN_ISADMIN":"IsAdmin","PN_ISSYSTEM":"IsSystem"};
var TopicItem ={"ItemName":"TopicItem","ItemIDName":"ID","PN_NAME":"Name","PN_CODE":"Code","PN_RECENT_ITEM_ID":"RID","PN_ID":"ID","PN_GROUPID":"GROUPID","PN_GROUP_CODE":"GROUPCODE","PN_GROUP_NAME":"GNAME","PN_ISLASTINGROUP":"ILIG","PN_ISGROUP":"ISGROUP","PN_ISSTANDALONEGROUP":"STALGROUP"};
var TrustedSourceItem ={"ItemName":"TrustedSourceItem","ItemIDName":"ID","PN_ID":"ID"};
var UserDataItem ={"ItemName":"UserDataItem","ItemIDName":"ID","PN_ID":"ID","PN_NAME":"Name","PN_FIRSTNAME":"FName","PN_LASTNAME":"LName","PN_EMAIL":"EMail","PN_LOGIN":"Login","PN_ISFAVORITEAUTHOR":"isFav"};
var BrandItem ={"ItemName":"BrandItem","ItemIDName":"ID","PN_NAME":"Name","PN_URL":"Url","PN_ID":"ID"};
var RelatedSymbologyItem ={"ItemName":"RelatedSymbologyItem","ItemIDName":"ID","PN_COUNT":"Count","PN_NAME":"Name","PN_ID":"ID","PN_ISNEW":"IsNew","PN_SYMBOL":"Symbol","PN_COUNTRY":"Country"};
var RelatedTopicItem ={"ItemName":"RelatedTopicItem","ItemIDName":"ID","PN_COUNT":"Count","PN_NAME":"Name","PN_CODE":"Code","PN_RECENT_ITEM_ID":"RID","PN_ID":"ID","PN_GROUPID":"GROUPID","PN_GROUP_CODE":"GROUPCODE","PN_GROUP_NAME":"GNAME","PN_ISLASTINGROUP":"ILIG","PN_ISGROUP":"ISGROUP","PN_ISSTANDALONEGROUP":"STALGROUP"};

var UserRole ={"User":"User","Admin":"Admin","CompanyAdmin":"CompanyAdmin","SuperAdmin":"SuperAdmin"};var UserType ={"SuperAdmin":"SuperAdmin","RegularUser":"RegularUser","LiteUser":"LiteUser"};var SpecialFolderType ={"Alerts":"Alerts"};
var TouchPointConfig ={"BaseRssUrl":"http://rss.infongen.com","SplashScreenDelay":5000,"PortfolioLimit":300,"PortfolioLimitForLite":50};
var WebFrameworkConfig ={"ApplicationShortTitle":"InfoNgen","XmlPath":"/xml/","DefaultPageUrl":"/default.aspx","PopupPageUrl":"/popup.aspx","RootUrl":"/","LoginUrl":"/login.aspx","LoginSmallUrl":"/loginsm.aspx","CssPath":"/css","ImagesPath":"/images","JavaScriptPath":"/js","JavaScriptPathMaster":"/js/master","CssPathMaster":"/css/master","UseCssDebugFiles":false,"UseJavaScriptDebugFiles":false};
var BrandsConfig ={"SnPTrialFormEmail":"trial@infongen.com"};
var TouchPointHomeConfig ={"SectionsColorBox":{"1":"#0066cc","2":"#6666cc","3":"#339999","4":"#ff0000","5":"#339933","6":"#999966","7":"#9900cc"},"CustomColors":["#0066cc","#6666cc","#339999","#ff0000","#339933","#999966","#9900cc"]};
var IncompleteRequestErrorGuid = "c9622735629349ec8cfb90851eeb0097";
var AuthenticationErrorGuid = "18fa53a074934c938c49e35dbcf62324";
var NoDataSnpContentGuid = "4fe8bcfc71a24db099c754923a62b83c";


DeclareClass("dom_DOMObject", null, 
{
	constructor: function(id)
	{
		if (id == null)
			return;
		if (id.constructor == String)
		{
			this.id = id;
			this.obj = null;
		}
		else
		{
			this.id = null;
			this.obj = id;
		}
	}
	,GetID : function()
	{
		return this.Obj().id;
	}
	,Obj : function()
	{
		if (this.obj != null)
			return this.obj;
		this.obj = document.getElementById(this.id);
		return this.obj;
	}
	,IsVisibleEx : function()
	{
		if (!this.IsVisible())
			return false;
		var prnt = this.getParent();
		if (prnt == null)
			return true;
		return new dom_DOMObject(prnt).IsVisibleEx();
	}
	,IsVisible : function()
	{
		if (this.Obj() == null)
			return false;
		return this.Obj().style.display != 'none'
	}
	,ChangeDisplay : function(vis)
	{
		if (this.Obj() == null)
			return;
		this.Obj().style.display = (vis == true) ? '' : 'none';
	}
	,getAttribute : function(attr)
	{
		return this.Obj().getAttribute(attr.toLowerCase());
	}
	,setAttribute : function(attr, val)
	{
		return this.Obj().setAttribute(attr, val);
	}
	,getInnerText : function()
	{
		if (this.Obj().textContent != null)
			return this.Obj().textContent;
		else
			return this.Obj().innerText;
	}
	,setInnerText : function(txt)
	{
		if (this.Obj().textContent != null)
			this.Obj().textContent = txt;
		else
			this.Obj().innerText = txt;
	}
	,setInnerHTML : function(html)
	{
		this.Obj().innerHTML = html;
	}
	,getInnerHTML : function()
	{
		return this.Obj().innerHTML;
	}
	,getOuterHTML : function()
	{
		if (this.Obj().outerHTML != null)	
			return this.Obj().outerHTML;
		if (this.Obj().xml != null)
			return this.Obj().xml;
		var	temp = this.Obj().cloneNode(true);
		var tempDiv = DOMObjectFactory.CreateTempElement("div");
		tempDiv.appendChild(temp);
		return tempDiv.innerHTML;
	}
	,getParent : function()
	{
		if (this.Obj() == null)
			return null;
		if (this.Obj().tagName.toLowerCase() == "body")
			return null;
		return this.Obj().parentNode;
	}
	,getParentByClassName : function(className) {
		var rxClass = new RegExp("\\b~0\\b".format(className));		
		var node = this.Obj();
		while (node.parentNode) {
			if (node.className && node.className.match(rxClass)) {
				return node;
			}
			node = node.parentNode;
		}
		return null;
	}	
	,getElementsByTagNameNS : function(ns, name)
	{
		if (BrowserInfo.IsIE6Up())	
			return this.Obj().getElementsByTagName(dom_GetCustomElementName(ns,name));

		var items = this.Obj().getElementsByTagName("*");
		var count = items.length - 1;
		var newname = dom_GetCustomElementName(ns,name).toLowerCase();
		var newItems = new Array();
		while (count >= 0)
		{
			if (newname == items[count].tagName.toLowerCase())
				newItems[newItems.length] = items[count];
			count--;
		}
		return newItems;
	}
	,setStyleAttribute: function(property, value, unit) {
		var obj = this.Obj();
		if (obj && property) {
			obj.style[property] = value + (unit ? unit : "");
		}
	}
	,applyClass : function(newcls)
	{
		if (this.Obj() != null) {			
			var classes = this.Obj().className.split(' ');
			if (classes.indexOf(newcls) == -1) {
				this.Obj().className = (this.Obj().className + " " + newcls).trim();
			}
		}	
	}
	,removeClass : function(oldcls)
	{
		if (this.Obj() == null)
			return;
		var pattern = "\\b~0\\b".format(oldcls)
		this.Obj().className = str_Trim(this.Obj().className.replace(new RegExp(pattern,"ig"), ""));
	}
	,removeNode : function(remChild)
	{
		var obj = this.Obj();
		if (remChild){
			if(obj.tagName.toLowerCase() == "tr")
				obj.parentElement.deleteRow(obj.sectionRowIndex);
			this.removeAllChildrens();
		}
		obj.removeNode();
	}
	,removeAllChildrens : function()
	{		
		try
		{
			this.Obj().innerHTML = "";
		}
		catch(e)
		{
		if (this.Obj())
			while(this.Obj().childNodes.length>0)
					this.Obj().childNodes[0].removeNode();	
		}
	}
});

// dom factory	
function dom_DOMObjectFactory()
{
	this.objects = [];
}
dom_DOMObjectFactory.prototype.CreateElement=function(name, isTemp, container, attrName)
{
	var obj = null;
	if (isTemp == true)
	{
		obj = this.objects[name];
		if (obj != null)
		{
			obj.clearAttributes();
			if (!str_IsStringEmpty(obj.innerHTML))
				obj.innerHTML = '';
		}
	}
	if (obj == null)
	{
		if (!isTemp && attrName && BrowserInfo.IsIE6Up())
			obj = document.createElement("<"+name+" name="+attrName+" >");
		else
		{
			obj = document.createElement(name);
			if (attrName)
				obj.name = attrName;
		}
		if (isTemp == true)
			this.objects[name] = obj;
	}
	// add created element to DOM hierarchy
	if (!isTemp && container) {
		container = $(container);
		container.appendChild(obj);
	}
	return obj;
};
dom_DOMObjectFactory.prototype.CreateDOMObject=function(name, isTemp, container) {
	/// <param name="container">parent DOM element to add created element to</param>
	return new dom_DOMObject(this.CreateElement(name, isTemp, container));
};
dom_DOMObjectFactory.prototype.CreateTempElement=function(name)
{
	return this.CreateElement(name, true);
}
dom_DOMObjectFactory.prototype.CreateTempDOMObject=function(name)
{
	return this.CreateDOMObject(name, true);
}
var DOMObjectFactory = new dom_DOMObjectFactory();


//garbage collector
function dom_DOMGarbageCollectorItem(domObj)
{
	this.domObj = domObj;
	this.events = new Array();
	this.properties = new Array();
}
dom_DOMGarbageCollectorItem.prototype.AddEvent=function(evtname, func)
{
	var eventarr = this.events[evtname];
	if (!eventarr)
	{
		eventarr = new Array();
		this.events[evtname] = eventarr;
	}
	eventarr.push(func);
}
dom_DOMGarbageCollectorItem.prototype.DeleteEvent=function(evtname, func)
{
	var eventarr = this.events[evtname];
	if (eventarr)
	{
		for(var i=eventarr.length-1; i >=0 ; i--)
			if (eventarr[i] == func)
			{
				eventarr.splice(i,1);
				return;
			}
	}
}
dom_DOMGarbageCollectorItem.prototype.AddProperty=function(objname)
{
	for (var i=0; i < this.properties.length; i++)
		if (this.properties[i] == objname)
			return;
	this.properties[this.properties.length] = objname;
}
dom_DOMGarbageCollectorItem.prototype.DeleteProperty=function(objname)
{
	for(var i=this.properties.length-1; i >=0 ; i--)
		if (this.properties[i] == objname)
		{
			this.properties[i].splice(i,1);
			return;
		}
}

function dom_DOMGarbageCollector()
{
	this.collection = new Array();
	this.uidcount = 0;
	var thisVar = this;
	this.releasefunc = function(){thisVar.ReleaseAllObjects(thisVar);}
	this.registerObjects = [];
	dom_attachEventForObject(window, "unload", this.releasefunc, false);
}
dom_DOMGarbageCollector.prototype.RegisterObject=function(obj)
{
	if (obj != null && obj.Dispose != null)
		this.registerObjects.push(obj);
}
dom_DOMGarbageCollector.prototype.AddEvent=function(domObj, evtname, func)
{
	var item = this.createItem(domObj);
	item.AddEvent(evtname, func);
}
dom_DOMGarbageCollector.prototype.DeleteEvent=function(domObj, evtname, func)
{
	var item = this.getItem(domObj);
	if (item  != null)
		item.DeleteEvent(evtname, func);
}
dom_DOMGarbageCollector.prototype.AddProperty=function(domObj, objname)
{
	var item = this.createItem(domObj);
	item.AddProperty(objname);
}
dom_DOMGarbageCollector.prototype.DeleteProperty=function(domObj, objname)
{
	var item = this.getItem(domObj);
	if (item  != null)
		item.DeleteEvent(objname);
}
dom_DOMGarbageCollector.prototype.ReleaseAllObjects=function(thisVar)
{
	thisVar.ReleaseAllRegisterObjects(thisVar);
	thisVar.ReleaseAllDOMObjects(thisVar);
}
dom_DOMGarbageCollector.prototype.ReleaseAllRegisterObjects=function(thisVar)
{
	if (thisVar.registerObjects != null)
	{
		for(var i=0; i < thisVar.registerObjects.length; i++)
			thisVar.registerObjects[i].Dispose();
		thisVar.registerObjects = null;
	}
}
dom_DOMGarbageCollector.prototype.ReleaseAllDOMObjects=function(thisVar)
{
	for(var itemname in thisVar.collection)
	{	
		var item = thisVar.collection[itemname];
		if (item.domObj)
		{
			for (var eventname in item.events)
			{
				for(var i=0; i < item.events[eventname].length; i++)
				{
					if (typeof(item.events[eventname][i]) == "function")
					{
						try
						{
							dom_detachEventForObject(item.domObj, eventname, item.events[eventname][i], false);
						}
						catch(e){};
					}
				}
			}
					
			for(var i=0; i< item.properties.length; i++)
			{
				try
				{
					var tmp = item.domObj[item.properties[i]];
					item.domObj[item.properties[i]] = null;
					if (typeof(tmp) == "object" && typeof(tmp.Dispose) == "function")
						tmp.Dispose();
					tmp = null;
				}
				catch(e){}
			}
		}
	}
	dom_detachEventForObject(window, "unload", thisVar.releasefunc, false);
}
dom_DOMGarbageCollector.prototype.createItem=function(domObj)
{
	var item = this.getItem(domObj);
	if (item == null)
	{
		item = new dom_DOMGarbageCollectorItem(domObj);
		this.collection[this.getUID(domObj, true)] = item;
	}
	return item;
}
dom_DOMGarbageCollector.prototype.getItem=function(domObj)
{
	var uid = this.getUID(domObj);
	if (uid)
		return this.collection[uid];
	return null;
}
dom_DOMGarbageCollector.prototype.getUID=function(domObj, create)
{
	if (!domObj.uid && create == true)
	{
		var uid = "uid_" + this.uidcount;
		this.uidcount ++;
		domObj.uid = uid;
	}
	return domObj.uid;
}

var DOMGarbageCollector = new dom_DOMGarbageCollector();

function dom_attachEventForObject(obj, evtname, func, gcol)
{			
	var handler = null;
	if (obj.addEventListener != null)
	{
		// get listeners cache
		var cache = obj.__eventsCache || (obj.__eventsCache = {});
		
		// get listeners for the given event type
		var eventHandlers = cache[evtname] || (cache[evtname] = []);
		
		// create intermediate function to save DOM Event object into global variable window.event
		handler = function dom_attachEvent_Handler(e) {
			window.event = e;
			return func.call(obj, e);
		}
		
		// bind created handler 
		obj.addEventListener(evtname, handler, false);			
		
		// save event handler to remove it later
		eventHandlers[eventHandlers.length] = { listener: func, handler: handler };	
	}
	else if (obj.attachEvent != null) {
		obj.attachEvent("on" + evtname, func);
	}

	if (gcol != false) {
		DOMGarbageCollector.AddEvent(obj, evtname, handler || func);
	}			
}

function dom_detachEventForObject(obj, evtname, func, gcol)
{
	var handler = null;
	
	if (obj.removeEventListener  != null)
	{
		var cache = obj.__eventsCache;
		
		if (cache) {
			// get handlers for the given event type
			var eventHandlers = cache[evtname];
			if (eventHandlers) {
				// locate listener to remove respective handler
				for (var i=0, length = eventHandlers.length; i<length; i++) {					
					if (eventHandlers[i].listener === func) {
						handler = eventHandlers[i].handler;
						break;
					}
				}
			}			
			// detach event handler and remove it from cache
			if (handler && typeof(handler) == 'function') {
				obj.removeEventListener(evtname, handler, false);	
				eventHandlers.splice(i, 1);
			}
		}		
	}
	else if (obj.detachEvent != null) {
		obj.detachEvent("on" + evtname, func);
	}
	
	if (gcol != false) {
		DOMGarbageCollector.DeleteEvent(obj, evtname, handler || func);
	}		
}

function dom_setProperty(obj, name, value, gcol)
{
	if (gcol != false)
	{
		if (value != null)
			DOMGarbageCollector.AddProperty(obj, name);	
		else
			DOMGarbageCollector.DeleteProperty(obj, name);	
	}
	obj[name] = value;
}

function dom_getProperty(obj, name)
{
	return obj[name];
}

function dom_getTagContent(tag, text)
{
	var reStart = new RegExp("<" + tag + "[^<>]*>", "igm");
	var reEnd = new RegExp("<\/" + tag + ">", "igm");
	var tagStart = reStart.exec(text);//  text.match(reStart);
	var tagEnd = reEnd.exec(text); //text.match(reEnd);
	if (tagStart != null && tagEnd != null)
		return text.substring(reStart.lastIndex, tagEnd.index );
	return text;
}

function dom_getTagAttributes(text)
{
	var attributes = text.match(new RegExp("[^=\\s]+=['\"][^'\"]+['\"]", "ig"));
	var res = new Array();
	if (attributes == null)
		return res;
	for (var i=0; i<attributes.length;i++)
	{
		attr = attributes[i].split("=");
		attr[1] = attr[1].substring(1, attr[1].length-1);
		res.push(attr);
	}
	return res;
}

function dom_IsObjectVisible(id)
{ 
	return new dom_DOMObject(id).IsVisible();
}

function dom_IsObjectVisibleEx(id)
{ 
	return new dom_DOMObject(id).IsVisibleEx();
}

function dom_SetObjectDisplay(id,vis)
{
	new dom_DOMObject(id).ChangeDisplay(vis);
}

function dom_RemoveNode(obj, remChild)
{
	new dom_DOMObject(obj).removeNode(remChild);
}

function dom_GetCustomElementName(ns, name)
{
	if (BrowserInfo.IsIE6Up())
		return name;
	return ns + ":" + name;
}

function dom_getElementsByTagNameNS(obj, ns, name)
{
	var dobj = new dom_DOMObject(obj);
	return dobj.getElementsByTagNameNS(ns, name);
}

function dom_BrowserInfo()
{
	this.agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
	this.minor = parseFloat(navigator.appVersion);
}
dom_BrowserInfo.prototype.IsIE=function() {
	if (typeof(this.isIE) == 'undefined') {
		this.isIE = ((this.agent.indexOf("msie") != -1) && (this.agent.indexOf("opera") == -1));
	}
	return this.isIE;
}
dom_BrowserInfo.prototype.IsIE3=function()
{
	return (this.IsIE() && (this.major < 4));
}
dom_BrowserInfo.prototype.IsIE4=function()
{
	return (this.IsIE() && (this.major == 4) && (this.agent.indexOf("msie 4")!=-1) );
}
dom_BrowserInfo.prototype.IsIE4Up=function()
{
	return (this.IsIE() && (this.major >= 4));
}
dom_BrowserInfo.prototype.IsIE5=function()
{
	return (this.IsIE() && (this.major == 4) && (this.agent.indexOf("msie 5.0")!=-1) );
}
dom_BrowserInfo.prototype.IsIE5_5=function()
{
	return (this.IsIE() && (this.major == 4) && (this.agent.indexOf("msie 5.5") !=-1));
}
dom_BrowserInfo.prototype.IsIE5Up=function()
{
	return (this.IsIE() && !this.IsIE3() && !this.IsIE4());
}
dom_BrowserInfo.prototype.IsIE5_5Up=function()
{
	return (this.IsIE() && !this.IsIE3() && !this.IsIE4() && !this.IsIE5());
}
dom_BrowserInfo.prototype.IsIE6=function()
{
	return (this.IsIE() && (this.major == 4) && (this.agent.indexOf("msie 6.")!=-1) );
}
dom_BrowserInfo.prototype.IsIE6Up=function()
{
	return (this.IsIE() && !this.IsIE3() && !this.IsIE4() && !this.IsIE5() && !this.IsIE5_5());
}
dom_BrowserInfo.prototype.IsFF=function() {	
	if (typeof(this.isFF) == 'undefined') {
		this.isFF = this.agent.indexOf("firefox") != -1;
	}
	return this.isFF;
}
dom_BrowserInfo.prototype.IsSafari=function() {
	if (typeof(this.isSafari) == 'undefined') {
		this.isSafari = this.agent.indexOf("safari") != -1;
	}
	return this.isSafari;
}


dom_BrowserInfo.prototype.GetVersion=function() {	
	if (typeof(this.version) == 'undefined') {
		var iePattern = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
		var firefoxPattern = /Firefox\/(\d+\.\d+)/;
		var re = this.IsIE() ? iePattern : firefoxPattern;
		if (re.exec(navigator.userAgent)){
			this.version = parseFloat(RegExp.$1);
		}
	}
	return this.version;
}
dom_BrowserInfo.prototype.IsFF3Up=function() {
	return this.IsFF() && this.GetVersion() >=3
}

var BrowserInfo = new dom_BrowserInfo();

function dom_DisableElementInObject( elemId )
{	
	try
	{
		var	obj = document.getElementById(elemId);
		for (var i = 0; i < obj.all.length; i++)
			switch(obj.all[i].tagName.toLowerCase())
			{
				case "input":
				if (obj.all[i].type.toLowerCase() == "text")
					obj.all[i].readOnly = true;
				else
					obj.all[i].disabled = true;
				break;
				case "textarea":
				obj.all[i].readOnly = true;
				break;
				case "select":
					obj.all[i].disabled = true;
				break;
			}
	}
	catch(e)
	{
	}
}

function dom_FindAbsElement(objStart)
{
	if(objStart==null) return null;
	var element = objStart;
	if(objStart.style.position=='absolute') element  = objStart.parentElement;

	while(element!=null){
		if(element.style.position=='absolute'){
			return element;
		}else{
			element = element.parentElement;
		}
	}
	
	return null;
}
// obj - object to set position
// return struct
// Pos
// {
//	bool IsFound
//  int x
//  int y
// }
function dom_findAbsXY(objToSet,startX,startY){
	var Pos  = dom_createPosObj();
	Pos.x = startX;
	Pos.y = startY;
	if(objToSet==null) return Pos;

	var obj = dom_FindAbsElement(objToSet);
	var pos = null;
	if(obj!=null){
		Pos.IsFound = true;
		Pos.x = Pos.x - obj.offsetLeft;
		Pos.y = Pos.y - obj.offsetTop;
		obj = dom_FindAbsElement(obj);
		while(obj!=null)
		{
			Pos.x = Pos.x - obj.offsetLeft;
			Pos.y = Pos.y - obj.offsetTop;
			obj = dom_FindAbsElement(obj);			
		}
	}

	return Pos;
}
// obj - object to set position
// return struct
// Pos
// {
//	bool IsFound
//  int x
//  int y
// }
function dom_findXY(objStart)
{
	var Pos = dom_createPosObj();
	if(objStart==null) return Pos;
	
	var element = objStart;
	
	while (element !=null ) {
		if(element.offsetLeft != null) Pos.x += element.offsetLeft;
		if(element.offsetTop != null) Pos.y += element.offsetTop;
		element = element.offsetParent;
	}
	Pos.IsFound = true;
	return Pos;
}

function dom_findScrollXY(objStart)
{
	var Pos = dom_createPosObj();
	if(objStart==null) return Pos;
	
	Pos.x = objStart.offsetLeft?objStart.offsetLeft:0;
	Pos.y = objStart.offsetTop?objStart.offsetTop:0;
	var element = objStart.offsetParent;
	while (element !=null ){
		if(element.offsetLeft != null) Pos.x += element.offsetLeft - element.scrollLeft;
		if(element.offsetTop != null) Pos.y += element.offsetTop - element.scrollTop;
		element = element.offsetParent;
	}
	Pos.IsFound = true;
	return Pos;
}

function dom_createPosObj()
{
	var Pos = new Array();
	Pos.IsFound = false;
	Pos.x = 0;
	Pos.y = 0;
	return Pos;
}

function dom_findMendOnScroll(objStart){
	var Mend  = dom_createPosObj();

	var element = objStart;	
	if (objStart == null) return Mend;
	while(element!=null)
	{
			if(element.offsetLeft != 0 || element.offsetTop != 0)
			{
				Mend.IsFound = true;
					Mend.x = Mend.x + element.scrollLeft;
					Mend.y = Mend.y + element.scrollTop;
			}
			element = element.parentElement;
	}
	
	if (!Mend.IsFound)	if(Mend.x != 0 || Mend.y != 0) Mend.IsFound = true;
	
	Mend.x = Mend.x + window.document.body.scrollLeft;
	Mend.y = Mend.y + window.document.body.scrollTop;

	return Mend;
}

function dom_getScroller(obj)
{
	var elem = obj;
	while(elem != null && elem.scrollHeight == elem.offsetHeight) 
		elem = elem.parentElement;
	return elem;
}
function dom_isObjectInVisibleContent(obj)
{
	var top = 0;
	var height = document.body.clientHeight;
	var tmp = dom_findXY(obj);
	var elem = dom_getScroller(obj);
	if (elem != null)
	{
		top = elem.scrollTop;
		height = elem.clientHeight;
	}
	return (tmp.y > top && tmp.y < top+height);
}

function dom_scrollIntoView(obj, alignToTop)
{
	if (!dom_isObjectInVisibleContent(obj))
		obj.scrollIntoView(alignToTop);
}
function dom_scrollTop(obj, num)
{
	var elem = dom_getScroller(obj);
	if (elem != null)
	{
		elem.scrollTop = num;
	}
}

var PopupOrParent = false;
function dom_GetTopLevelWindow(){
	if ((( window.parent!=null) && (window != window.parent)) || window.opener !=null)
	{
		PopupOrParent = true;
		var winObj = (window.opener != null ? window.opener : window.parent)
		while (winObj.opener != null ||  ((winObj.parent != null) && (winObj != winObj.parent) && (window.opener == null)))
		{
			var winObj = (winObj.opener != null ? winObj.opener : winObj.parent)
		}
		if (winObj == null) {
			return window;
		}else return winObj;
	}
	PopupOrParent = false;	
	return window;
}


function dom_disposeObject(obj)
{
	if (obj == null)
		return;
	if (obj.disposing == true)	
		return;
	for(var item in obj)
	{
		if( typeof(obj[item])=="undefined" || obj[item]==null || obj[item].disposing == true)
			continue;
		if (typeof(obj[item])=="function")
		{
			obj[item] = null; 
			continue;
		}
		if (typeof(obj[item])!="object")
			continue;
		if (obj[item].tagName)
			continue;
		if (obj.tagName)
		{
			switch (item)
			{
				case "all":
				case "childNodes":
				case "children":
				case "style":
				case "currentStyle":
				case "runtimeStyle":
				case "filters":
				case "document":
				case "ownerDocument":
				case "nextSibling":
				case "previousSibling":
				case "parentElement":
				case "offsetParent":
				case "parentNode":
				case "firstChild":
				case "lastChild":
				case "behaviorUrns":
				case "attributes":
				case "styleSheet":
				case "parentTextEdit":
				case "elements":
				case "cells":
				case "rows":
				case "tBodies":
					continue;
			}
		}
		obj[item].disposing=true;
		if ( typeof(obj[item].Dispose)!= "undefined" && (obj[item].Dispose != null) )
			obj[item].Dispose();
		if(!obj[item].disposing)
		{
			try {
				disposeObject(obj[item]);
				} catch(e1) {;}
			}
			obj[item] = null;
			//try{delete obj[item]; }catch(e2){;}
		}
}

function dom_findParent(obj, tagName)
{
	if(obj==null) return null;
	return obj.tagName.toLowerCase() == tagName.toLowerCase()? obj: dom_findParent(obj.parentElement, tagName);
}

DeclareClass("dom_RectangleObject", null,
{
	constructor : function(left, top, right, bottom){
		this.top = top;
		this.left = left;
		this.bottom = bottom;
		this.right = right;
	}	
	,getHeight: function(){return this.bottom - this.top; }
	,getWidth: function(){return this.right - this.left; }
	,containPoint: function(screenX, screenY){
		return (screenX >= this.left && screenX <= this.right && 
					screenY >= this.top && screenY<=this.bottom); 
	}
	,overlap: function(rect){
		return rect.left < this.right && rect.right > this.left &&
					rect.top < this.bottom &&  rect.right > this.top;
		
	}
	,getRelativeDomRect: [decl_static, function(obj, /*optional*/relativeObj){
		var pos = dom_findScrollXY(obj);
		if(!relativeObj)
			relativeObj = dom_RectangleObject.findRelativeObj(obj);
		if(relativeObj!=null){
			var par_pos = dom_findScrollXY(relativeObj);
			pos.x-= par_pos.x - relativeObj.scrollLeft;
			pos.y-= par_pos.y - relativeObj.scrollTop;
		}		
		return new dom_RectangleObject(pos.x, pos.y, pos.x+obj.offsetWidth, pos.y+obj.offsetHeight);
	}]	
	,getScreenRect: [decl_static, function(obj, onlyClientArea)	{
		var boxObj = null;
		try{ boxObj = obj.getBoundingClientRect(); } catch(e){}
		if(boxObj == null || (boxObj.left==0 && boxObj.top == 0 && boxObj.right==0 && boxObj.bottom == 0))
			return null;
		var rect = new dom_RectangleObject(boxObj.left, boxObj.top, boxObj.right, boxObj.bottom);
		if(onlyClientArea){
			rect.right -= obj.offsetWidth - obj.clientWidth;
			rect.bottom -= obj.offsetHeight - obj.clientHeight;
		}
		return rect;
	}]
	,findRelativeObj: [decl_static, function(obj){
		var relativeObj = obj.parentElement;		
		while (relativeObj && relativeObj.currentStyle && relativeObj != document.body &&
						relativeObj.currentStyle.position.toLowerCase() != "absolute" &&
						relativeObj.currentStyle.position.toLowerCase() != "relative" &&						
						(!BrowserInfo.IsIE6Up() || (relativeObj.currentStyle.overflow.toLowerCase() != "auto" && relativeObj.currentStyle.overflow.toLowerCase() != "scroll")))
			relativeObj = relativeObj.parentElement;
		return relativeObj;		
	}]
	,hasElementPoint: [decl_static, function(element, screenX, screenY){
		var screenRect = dom_RectangleObject.getScreenRect(element);
		return screenRect.containPoint(screenX, screenY);
	}]
});
function date_setInterval(id, format, offsetHours){
	
	if (GeneralPreferences.detectedOffset != null) //New offset has been detected
		offsetHours = GeneralPreferences.detectedOffset;
		
	GeneralPreferences.offsetHours = offsetHours;// save preferences	
	date_setFormatedDateTime(id, format, offsetHours);
	if (this.timerId) window.clearInterval(this.timerId);
	this.timerId = window.setInterval(["date_setFormatedDateTime('",id,"','",format,"',",offsetHours,");"].join(''),date_getTimeout(format));
}

function date_setFormatedDateTime(id, format, offsetHours){
	var obj = document.getElementById(id), date = new Date(), offsetLocal = date.getTimezoneOffset();
	if (typeof(offsetHours)!="number")offsetHours = offsetLocal;
	date.setMinutes(date.getMinutes()-offsetHours+offsetLocal);
	var text = date.ToString(format);	
	if (obj) obj.innerText = text;
	return text;	
}

function date_getTimeout(format){
	if (format.indexOf("s")!=-1)return 1000;
	if (format.indexOf("m")!=-1)return 60000;//1000*60;
	if (format.toLowerCase().indexOf("h")!=-1)return 3600000;//1000*60*60;
	return -1;
}


function date_getTimeZone() {
   var rightNow = new Date();
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
   var dst = (hoursDiffDaylightTime != hoursDiffStdTime)? "true" : "false";
    
   var sres = "";
   if ( hoursDiffStdTime != 0 )
   {
		sres = hoursDiffStdTime > 0 ? "+" : "-";
		var s = "" + Math.abs(hoursDiffStdTime);
		  
		var tmp = s.split(/[.,]/ig);
		   
		if ( tmp.length == 1 )
		{
				if ( tmp[0].length == 1 )
					sres += "0" + tmp[0] + ":00";
				else	
					sres += tmp[0] + ":00";
		}
			
		if ( tmp.length > 1 )
		{
				if ( tmp[0].length == 1 )
					sres += "0" + tmp[0] + ":";
				else	
					sres += tmp[0] + ":";
				if ( tmp[1].length == 1 )
					sres = sres + "0" + tmp[1];
				else	
					sres = sres + tmp[1];
		}
   }
   
   GeneralPreferences.offsetHours = GeneralPreferences.detectedOffset = new Date().getTimezoneOffset();
   return "gmt:" + sres + ";" + dst;
}

function setWindowHourGlass(isShow){	
	if(isShow!=false){		
		var table=document.createElement("table"), tableb=document.createElement("TBODY"), 
			td=document.createElement("td"), tr=document.createElement("tr");
		table.id ="HourGlassLayer";
		table.style.zIndex = 110;
		table.style.left = "0px";
		table.style.top = "0px";
		table.style.height = "100%";
		table.style.width = "100%";
		table.style.cursor = "wait";
		table.style.position = "absolute";	
		document.body.appendChild(table);
		table.appendChild(tableb);					
		tableb.appendChild(tr);				
		tr.appendChild(td);		
	}
	else {
		var hgLayer = document.getElementById("HourGlassLayer");
		if(hgLayer!=null)document.body.removeChild(hgLayer);	
	}
}

function tpl_GetCookieDomain()
{
	var host = window.location.host;
	var domainExtractor = /(^|\.)(\w+\.\w+)$/;
	domain = host.match(domainExtractor);
	if (domain != null) return domain[2];
	else return null;
}

function tpl_DropCookie(name, domain, path)
{
	document.cookie = name + "=" +
	";path=" + ( ( path != null ) ?  path : "/") + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function tpl_SetLoginCookie(name, value)
{
	var domain = tpl_GetCookieDomain();
	document.cookie = name + "=" + value +
	";path=/" + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-2015 00:00:01 GMT";
}

function tpl_DropLoginCookie(saveSettings)
{
	tpl_DropCookie("iiAuth");
	tpl_DropCookie("iiRAuth");
	if (!saveSettings)
	{
		tpl_DropCookie("tpsettings");
		tpl_DropCookie("tmsettings");
	}
	
	var domain = tpl_GetCookieDomain();
	if (domain)
	{
		tpl_DropCookie("iiAuth", domain);
		tpl_DropCookie("iiRAuth", domain);		
	}
}

function tpl_SetCookie(sName, sValue, global, skipEncode){
	date = new Date();
	date = new Date(date.getFullYear()+1,date.getMonth(),date.getDate())
	var path=(global==true)?"path=/;":"";
	document.cookie = [sName,"=",(skipEncode == true ? sValue : encodeURIComponent(sValue)),"; ",path,"expires=",date.toGMTString(),";"].join('');
}

function tpl_GetCookie(sName){
	var aCookie = document.cookie.split("; ");
	for (var i=0,iLen=aCookie.length;i<iLen;++i){
		var idx = aCookie[i].indexOf("=");
		if (idx == -1)continue;
		if (sName == aCookie[i].substr(0, idx))
			return decodeURIComponent(aCookie[i].slice(idx+1).replace(/\+/g, " "));
	}
}

function ToTimeString(objDate){
	if (objDate==null)return "00:00:00";
	return [objDate.getHours(),':',objDate.getMinutes(),':',objDate.getSeconds(),'::',objDate.getMilliseconds()].join('');
}

//**************************** Sorting ****************************************//
function tpl_SortChildren(obj, compare){
	if (!obj)return;
	var clone = obj.cloneNode(true);
	tpl_quickSortR(clone.children,0,clone.children.length-1, compare, tpl_htmlSwaper);
	obj.swapNode(clone);
}

function tpl_quickSortR(arr, m, n, compare, swaper, getter){
	if (typeof(compare) == "undefined")compare = tpl_CompareString;
	if (typeof(swaper) == "undefined")swaper = tpl_arraySwaper;
	if (typeof(getter) == "undefined")getter = tpl_arrayGetter;

	var j=n, i=m, pind = Math.round((i + j)/2), p = getter(pind, arr);
	swaper(pind, i, arr);
	do {
		while (compare(getter(i, arr),p) < 0) ++i;
		while (compare(getter(j, arr),p) > 0) --j;
		if (i<=j){
			swaper(i, j, arr);
			++i; --j;
		}
	} while (i<=j);

	if (j > m) tpl_quickSortR(arr, m, j, compare, swaper, getter);
	if (n > i) tpl_quickSortR(arr, i, n, compare, swaper, getter);
}

function tpl_CompareInt(x,y){
	return x-y;
}

function tpl_CompareString(x,y){
	if (x>y) return 1; else if (x<y) return -1; else return 0;
}

function tpl_CompareDate(x,y){
	if (x>y) return 1; else if (x<y) return -1; else return 0;
}

function tpl_CompareInnerText(x,y){
	return tpl_CompareString(x.innerText,y.innerText);
}

function tpl_CompareFontSize(x,y){
	var res = tpl_CompareString(x.className,y.className);
	if (res == 0)res = tpl_CompareInnerText(x,y);
	return res;
}

function tpl_htmlSwaper(idx1, idx2, arr){
	arr[idx1].swapNode(arr[idx2]);
}

function tpl_arraySwaper(idx1, idx2, arr){
	var tmp = arr[idx1];
	arr[idx1] = arr[idx2];
	arr[idx2] = tmp;
}

function tpl_arrayGetter(idx, arr){
	return arr[idx];
}

//**************************** Sorting ****************************************//

function cmn_GetImageUrl(img){
	return WebFrameworkConfig.ImagesPath + "/" + img; 
}

function cmn_GetCountryNameBySymbol(symbol){	
	if (!str_IsStringEmpty(symbol)){
		var lcSymbol=symbol.toLowerCase();
		for(var i=TPCountryCache.length-1;i>=0;--i)
			if (TPCountryCache[i].value.toLowerCase() == lcSymbol) 
				return TPCountryCache[i].text;
	}
	return null;
}

function cmn_GetSymbolByCountryName(name){	
	if (!str_IsStringEmpty(name)){
		var lcName=name.toLowerCase();
		for(var i=TPCountryCache.length-1;i>=0;--i)
			if (TPCountryCache[i].text.toLowerCase() == lcName)
				return TPCountryCache[i].value;
	}
	return null;
}

function cmn_GetRegionNameBySymbol(symbol){	
	if (!str_IsStringEmpty(symbol)){
		var lcSymbol=symbol.toLowerCase();
		for(var i=TPRegionCache.length-1;i>=0;--i)
			if (TPRegionCache[i].value.toLowerCase() == lcSymbol)
				return TPRegionCache[i].text;
	}
	return null;
}

function cmn_GetSymbolByRegionName(name){	
	if (!str_IsStringEmpty(name)){
		var lcName=name.toLowerCase();
		for(var i=TPRegionCache.length-1;i>=0;--i)
			if (TPRegionCache[i].text.toLowerCase() == lcName)
				return TPRegionCache[i].value;
	}
	return null;
}

function cmn_GetLanguageNameByCode(code){	
	if (!str_IsStringEmpty(code)){
		var lcCode=code.toLowerCase();
		for(var i=TPLanguageCache.length-1;i>=0;--i)
			if (TPLanguageCache[i].value.toLowerCase() == lcCode)
				return TPLanguageCache[i].text;
	}
	return null;
}

function cmn_GetCodeByLanguageName(name){	
	if (!str_IsStringEmpty(name)){
		var lcName=name.toLowerCase();
		for(var i=TPLanguageCache.length-1;i>=0;--i)
			if (TPLanguageCache[i].text.toLowerCase() == lcName)
				return TPLanguageCache[i].value;
	}
	return null;
}

function vld_unallowedChars( ex ){
	return ex ? "%*'\"/\\<>`;&+.,!@#$^&" : "%*'\"/\\<>`;";
}

function vld_IsValid (strToValidate, ex){
	var strUnallowedChars = vld_unallowedChars(ex);
	if (strToValidate == null || strToValidate.toString() == "")return true; // empty string is valid
	for (var i=0,iLen=strUnallowedChars.length;i<iLen;++i)
		if (strToValidate.toString().indexOf(strUnallowedChars.charAt(i)) != -1) 
			return false;
	return true;
}

function vld_IsEmailValid(email,showerror){
	if (typeof(email) == 'undefined' || email == null || email.length == 0)return true;
	if (email.match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/) == null){
		if (showerror == true)alert("\""+email+"\" is not a valid e-mail address!")
		return false;
	}
	return true;
}

function vld_IsEmailValidWithWildCard(email,showerror){
	var s = email.split("*");
	if(s.length < 3)
		if (vld_IsEmailValid(email.replace("*","X.X"),false))return true;
	if (showerror == true)alert("\""+email+"\" is not a valid e-mail address!");
	return false;
}

function vld_CheckFullEmailWithWildCard(email,showerror){
	if (typeof(email) == 'undefined' || email == null || email.length == 0)return true;
	var emailspieces = email.split("*");
	if (emailspieces.length == 1)return vld_IsEmailValid(email,showerror);
	if (emailspieces.length > 2){
		if (showerror == true)alert("Email address should contain only one wildcard symbol!");
		return false;
	}
	var emailtemplate = "a@a.a", lengthtemplate = emailtemplate.length, testemail = "", iscorrect = false;
	for (var i=0; i<lengthtemplate && !iscorrect; i++)
		for (var j=1; j<=lengthtemplate-i && !iscorrect; j++){
			testemail = emailspieces[0] + emailtemplate.substr(i,j) + emailspieces[1];
			if (vld_IsEmailValid(testemail,false))
				iscorrect = true;
			else
			{
				testemail = emailspieces[0] + emailtemplate.substr(emailtemplate.length-i-j,j) + emailspieces[1];
				if (vld_IsEmailValid(testemail,false))
					iscorrect = true;
			}
		}
	if (!iscorrect)return vld_IsEmailValid(email,showerror);
	return true;
}

function vld_ValidatePage(){
	var isValid = true;
	if (typeof(Page_ClientValidate) == 'function')isValid = Page_ClientValidate();
	return isValid;
}

function floorDate(date){
    if (date != null){
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0); 
    }
    return date; 
}

// input control
var cmsv_OK = 0;
var cmsv_Required = 1;
var cmsv_Error = 2;

function input_ValidateTextInputControl(tbxId, isMandatory) {
  var errCode = cmsv_OK, tbx = document.getElementById(tbxId);
  if (isMandatory && str_Trim(tbx.value).length == 0) errCode = cmsv_Required;
  return errCode;
}

function input_HtmlDecode(str){
	var convertor = document.createElement("span");
	convertor.innerHTML=str;
	return convertor.innerText;
}

function input_validate(){
	var errCode = cmsv_OK;
	return errCode;
}

function input_SetInputControlErrorMode(tblLayoutId, labelId, validatorId, noErrors){
	var tblLayout = document.getElementById(tblLayoutId), vlr = document.getElementById(validatorId), idxRow = 0, 
		idxCell = vlr.getAttribute("RIV"), isHorzLayout = tblLayout.getAttribute(vlr.getAttribute("LA")) == "0", 
		isLabeled =	tblLayout.getAttribute(vlr.getAttribute("LAt")) == "1", 
		cell = tblLayout.rows[idxRow].cells[idxCell];
	if(cell!=null) cell.className = noErrors ? vlr.getAttribute("CLCC") : vlr.getAttribute("CLCC") + " " + vlr.getAttribute("ECC");
	if (isHorzLayout && isLabeled){
		cell = tblLayout.rows[idxRow].cells[idxCell+1];
		if (cell != null) cell.className = noErrors ? '' : vlr.getAttribute("ECC");
	}
	vlr.runtimeStyle.color = noErrors ? '' : vlr.getAttribute("EMC");
	vlr.runtimeStyle.display = noErrors ? "none" : "block";
}

function input_ValidateClient(src, args){
	if (typeof(src.getAttribute("FEV")) != 'string' || typeof(src.getAttribute("EM")) != 'string' 
		|| typeof(src.getAttribute("RIM")) != 'string' || typeof(src.getAttribute("CLTI")) != 'string' 
		|| typeof(src.getAttribute("LI")) != 'string' || typeof(src.getAttribute("FE")) != 'string') return;
	var errCode = eval(src.getAttribute("FE") + '('+src.getAttribute("FEV")+');');
	args.IsValid = (errCode == 0);
	if (errCode == 1) 
		src.innerText = input_HtmlDecode(src.getAttribute("RIM"));
	else if (errCode == 2) 
		src.innerText = src.getAttribute("EM");
	input_SetInputControlErrorMode(src.getAttribute("CLTI"), src.getAttribute("LI"), src.id, (errCode == 0));
}

function submit_with_validation(){
	if (!validate_MandatoryFields() && typeof(TPMandatoryFieldsMessage) != "undefined" && TPMandatoryFieldsMessage != null ) 
	{
		alert(TPMandatoryFieldsMessage);
		return false;
	}
	return true;
}

function validate_MandatoryFields(){
	if (typeof(TPMandatoryFields) == "undefined" || TPMandatoryFields == null || TPMandatoryFields.length == 0)return true;
	for(var i=0; i< TPMandatoryFields.length; i++){
		var obj = document.getElementById( TPMandatoryFields[i].id );
		if (obj == null) continue;
		if (obj.value != null)obj.value = str_Trim(obj.value);
		if ( str_IsStringEmpty(obj.value) ) return false;
	}	
	return true;
}

function $(elementId) { 
	return (typeof(elementId) == "string") ? document.getElementById(elementId) : elementId;
}

function CreateInheritance(parent, child){
	child.prototype = new parent;
	child.prototype.constructor = child;
}

Object.prototype.Inherits = function(parent){
    if(arguments.length > 1)
        parent.apply( this, Array.prototype.slice.call(arguments, 1));
    else
        parent.call( this );
}

Function.prototype.Inherits = function(parent){
    this.prototype = new parent();
    this.prototype.constructor = this;
}

function script_buildFunction(/*function name, params...*/){
	if(arguments.length<1)return null;
	var result = [arguments[0],"("];
	for(var i=1,iLen=arguments.length;i<iLen;++i){
		if(i>1)result[result.length]=", ";
		if(arguments[i]==null)
			result[result.length]="null";
		else{
			result[result.length]="'";
			result[result.length]=arguments[i];
			result[result.length]="'";		
		}
	}
	result[result.length]=");";
	return result.join('');
}

function UpdateIframeSize(){
	try{
	this.window.frameElement.runtimeStyle.height = window.document.body.scrollHeight + 50 + "px";
	}catch(e){};
}

function vld_IsGuidValid(guid,strFormat){
	if (str_IsStringEmpty(guid))return false;
	var res = null;
	switch(strFormat)
	{
		case "N":
			res = guid.match(/(^[a-fA-F\d]{8}([a-fA-F\d]{4}){3}[a-fA-F\d]{12}$)/);
			break;
		default:
			res = guid.match(/(^[a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12}$)/);
			break;
	}
	if (res == null)return false;
	return true;
}


function vld_IsGuidEmpty(guid){
	if (guid == "00000000000000000000000000000000" || guid == "00000000-0000-0000-0000-000000000000")return true;
	return false;
}

function vld_EqualGuids(guid1, guid2){
	if (!guid1 || !guid2)return false;
	return guid1.replace(/-/ig,"") == guid2.replace(/-/ig,"");
}

function wnd_IsFrameDetached(){
	if (window.frameElement != null && window.frameElement.parentElement == null ) 
		return true;
	return false;
}

function wnd_IsWindowClosed(wnd){
	try { if (wnd.eval("wnd_IsFrameDetached()")==true) return true; }catch(e){}
	try{ return wnd==null || wnd.closed; }catch(e){}
	return null;
}

function cmd_getCssFileName(fileName){
	var css_dir = WebFrameworkConfig.CssPath;
	if(WebFrameworkConfig.UseCssDebugFiles)css_dir+= "/master";
	var cssfileName = fileName;	
	if (!WebFrameworkConfig.UseCssDebugFiles){
		var pos = fileName.lastIndexOf(".");
		if (pos>=0)cssfileName = fileName.substring(0,pos) + "_" + TP_VERSION + ".CSS";
	}	
	return css_dir + "/" + cssfileName;	
}

function cmd_getJSFileName(fileName){
	if(WebFrameworkConfig.UseJavaScriptDebugFiles)
		return WebFrameworkConfig.JavaScriptPathMaster + '/' + fileName;
	else {
		var index = fileName.indexOf("/") == -1 ? fileName.indexOf( "\\" ) : fileName.indexOf("/"),
			path=(index>=0)?fileName.substring(0, index):fileName.replace(".js", "");
		return WebFrameworkConfig.JavaScriptPath + "/" + path + "_" + TP_VERSION + ".js";		
	}
}

function cmd_getJSFileNamesWithoutDublicats(/*fileNames*/){
	var array = [];
	for(var i=0; i<arguments.length; i++){
		var jsName = cmd_getJSFileName(arguments[i]);
		var dublicated = false;
		for(var j=0; j<array.length; j++)
			if(array[j] == jsName){
				dublicated = true;
				break;
			}
		if(!dublicated)array.push(jsName);
	}
	return array;
}

Array.getFrom = function(src){
    if (!src) return [];
    var result = [];    
    for (var i = 0; i < src.length; i++) 
        result.push(src[i]);
    return result;    
}

Array.getHash = function Array_getHash(array) {
	var result = {};
	if (array) {
		for (var i=0; i < array.length; i++) {
			var key = array[i];
			if (typeof(key) == "string") {
				key = key.trim();
			}
			result[key] = key;
		}
	}
	return result;
}

Function.prototype.bind = function() {
    var method = this;
    var args = Array.getFrom(arguments);
    var obj = args.shift();
    return function() {
        return method.apply(obj, args.concat(Array.getFrom(arguments)));
    }
}

function PrepareSubmitEvents(){
	for (var i = 0; i < editorsTabOrder.length; i++){
		var current = document.getElementById(editorsTabOrder[i]);
		if (i == editorsTabOrder.length - 1)
			dom_attachEventForObject(current,'keyup', function () { if( window.event.keyCode == 13) CheckAndSubmitForm(); } );
		else
			dom_attachEventForObject(current,'keyup', 
				function () 
				{ 
					var myId = window.event.srcElement.id;
					if( window.event.keyCode == 13) 
						for (var i = 0; i < editorsTabOrder.length - 1; i++)
							if (editorsTabOrder[i] == myId)
								document.getElementById(editorsTabOrder[i + 1]).focus(); 
				} 
			);
	}
}

Array.prototype.map = function(callback, thisObj){
	var result = [];	
	for (var i=0,iLen=this.length;i<iLen;++i)
		result.push((thisObj)?callback.call(thisObj, this[i], i, this):callback(this[i], i, this));
	return result;
};

Array.prototype.filter = function(callback, thisObj){
	var result = [];	
	for (var i=0; i< this.length; i++){
		var matches = (thisObj)?callback.call(thisObj, this[i], i, this):callback(this[i], i, this);
		if (matches) result.push(this[i]);
	}
	return result;
};

//return new array with inserted element
Array.prototype.insert = function(item, idx){
	if (typeof(idx) != "number" || idx > this.length) idx = this.length;
	var res = this.slice(0);
	switch(idx){
		case 0:
			res.unshift(item);
			break;
		case this.length:
			res.push(item);
			break;
		default:
			var tempar = res.splice(idx,res.length-1);
			res.push(item);
			res = res.concat(tempar);
			break;
	}
	return res;
};

//return new array with moved element
Array.prototype.move = function(oldidx, newidx){
	if (newidx >= this.length)newidx = this.length-1;
	if (this.length > oldidx && typeof(oldidx) == "number" && typeof(newidx) == "number"){
		if (oldidx == newidx)return this;
		var res = this.slice(0);
		return res.insert(res.splice(oldidx, 1)[0], newidx);		
	}
	throw "Index out of range";
};

Array.prototype.indexOf = function(element){
	var result = -1;
	if (typeof(element) != "undefined"){
		for (var i=0; i<this.length; i++){
			if (typeof(this[i] != "undefined") && this[i] === element){
				result = i;
				break;
			}
		}
	}
	return result;
};

Array.prototype.remove = function(idx){
	this.splice(idx, 1);
}

Array.prototype.removeItem = function(obj){
	for (var i=0; i< this.length; i++)
		if(this[i]==obj){
			this.splice(i, 1);
			break;
		}		
}

function cnv_ContTypeToSrchTag(type){
	switch(type){
		case CT_CHANNEL:
		case CT_BLOG:
		case CT_MONITORNEWSFEED:
			return SRCH_TN_FEED
		case CT_CALENDAR:
			return SRCH_TN_CALENDAR
		case CT_FOLDER:
			return SRCH_TN_FOLDER
		case CT_USERBLOG:
			return SRCH_TN_BLOG
		default:
			return null;
	}
}

function cmn_getCursorPosition(input){
	if (!input) return;
	if (input.createTextRange){
		var r = document.selection.createRange().duplicate();
		r.moveEnd('character', input.value.length);
		if (r.text == '')return input.value.length;
		return input.value.lastIndexOf(r.text);		
	} 
	else 
		return input.selectionStart;
}

function cmn_ReplaceInputValue(input,value,start,end){
	if (!input) return;
	if (input.createTextRange){
		var r = input.createTextRange()
		r.moveStart('character', start);
		r.moveEnd('character', end - input.value.length)
		r.text = value;
	} else {
		var val = input.value;
		input.value = val.substring(0, start) + value + val.substr(end);
	}
}

function cmn_clicklink(ev)
{
	if (!ev || !ev.srcElement) return;
	var anchor = ev.srcElement;
	var href = anchor.getAttribute("HREF");
	if (href)
		window.open(href,anchor.getAttribute("TARGET"), 
		["channelmode=no",
		"directories=yes",
		"fullscreen=no",
		"location=yes",
		"menubar=yes",
		"resizable=yes",
		"scrollbars=yes",
		"status=yes", 
		"titlebar=yes", 
		"toolbar=yes"].join(","));
	ev.returnValue = false;
	return false;
}

function cmn_cancelEvent(e)
{
	e.cancelBubble = true;
	e.returnValue = false;
	return false;
}

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function cmn_getFeedPrefix(type,parameters)
{
	var pref = "";
	switch (parameters[0])
	{
		case CAT_SUBSCRIPTION:
			pref = "$";
			break;
		case CAT_REGISTRATION:
			pref = "R";
			break;
	}
	return pref ? ("[" + pref + "] ") : pref
}

function cmn_getContainerPrefix(type,parameters)
{
	var pref = "";
	switch (type)
	{
		case CT_CHANNEL:
		case CT_BLOG:
		case CT_MONITORNEWSFEED:
			pref = cmn_getFeedPrefix(type,parameters);
			break;
	}
	return pref;
}
// string helper
function str_IsStringEmpty(s){return (s == null || String(s).replace(/(^[ \t]+)|([ \t]+$)/g, '') == '')?true:false;}

function str_Trim(s){ return s.replace(/(^[ \t]+)|([ \t]+$)/g, ''); }

String.prototype.trim = function() {
    var m = this.match(/^\s*(\S+(\s+\S+)*)\s*$/);
	return(m == null)?"":m[1];
}

// ------------------------ Override Date Class --------------------------
date_dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
date_monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
Date.MonthesAbbreviations = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

Date.dayNames = date_dayNames;
Date.monthNames = date_monthNames;

Date.prototype.isLeapYear = function() {
    var year = this.getFullYear();
    return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
}

Date.prototype.getDaysInMonth = function() {
    Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
  return Date.daysInMonth[this.getMonth()];
}

Date.prototype.getDayName = function() {
    return Date.dayNames[this.getDay()];
}

Date.prototype.getShortDayName = function() {
    return this.getDayName().substr(0,3);
}

Date.prototype.getMonthName = function() {
    return Date.monthNames[this.getMonth()];
}

Date.prototype.getShortMonthName = function() {
    return this.getMonthName().substr(0,3);
}

Date.prototype.getNoonState = function()
{   
	return (this.getHours() >= 12) ? "PM" : "AM"
}

Date.prototype.getShortYear = function()
{  
	var year = this.getFullYear().toString();
	return (year.length >2) ? year.substr(year.length-2,2) : year;
}

Date.prototype.ParseToken = function(token,reArray,keysArray){
    var s=token, sa=[];     
    for(var i=0,iLen=keysArray.length;i<iLen;++i){
        var key=keysArray[i];
		while(key.charAt(0)==s.charAt(0) && key.length<=s.length){
			sa[sa.length]=reArray[key];
			s=s.replace(key,"");
		}
    }
	sa[sa.length]=s;
	return sa.join('');
}
Date.prototype.IsFormatChar = function(ch) { return "Mdyhmt".indexOf(ch) > -1 ? true : false; }
Date.prototype.PartByToken = function(token) {
	if (token == "MM" || token == "M" || token == "MMM") return 0;
	else if (token == "dd" || token == "d") return 1;
	else if (token == "yy" || token == "yyyy") return 2;
	else return 3;
}
Date.prototype.Parse = function(sDate, format) {
	var s = format, res=[null, null, null], strDate = sDate;
	if (!s && s.length==0) s="MM/dd/yyyy";
	
	var pos = 0;
	while (pos < s.length)
	{
		var token = ""; // format token
		while (pos < s.length && this.IsFormatChar(s.charAt(pos)))
		{
			token += s.charAt(pos).toString();
			pos++;
		}
		var div = ""; // divider
		while (pos < s.length && !this.IsFormatChar(s.charAt(pos)))
		{
			div += s.charAt(pos).toString();
			pos++;
		}
		if (div != "") {
			var index = strDate.indexOf(div);
			if (index > -1)
			{
				var partDate = strDate.substr(0, index);
				res[this.PartByToken(token)] = partDate;
				strDate = strDate.substr(index + div.length);				
			}
		}
		else
		{
			var partDate = strDate;
			res[this.PartByToken(token)] = partDate;
		}
	}
	
	var toDay = new Date();
	
	if (res[0] == null) res[0] = toDay.getMonth()+1;
	if (res[1] == null) res[1] = toDay.getDate();
	if (res[2] == null) res[2] = toDay.getFullYear();
	
	var monthes = Date.MonthesAbbreviations;
	for (var i=0; i<12; ++i)
		if (monthes[i].toLowerCase() == (res[0]+'').toLowerCase()) {
			res[0] = i+1;
			break;
		}
	if ((''+res[2]).length==2) {
		var fy = toDay.getFullYear(), sfy = (fy+'').substr(0,2);	
		res[2]=sfy+res[2];
	}
	
	var date = new Date(Date.parse(res.join('/')));
	if (date == 'NaN' || date == 'Invalid Date')
		return 'NaN';
	else
		if (date.Format(format).toLowerCase() != sDate.toLowerCase())
			return 'NaN';
			
	return date;
}

Date.prototype.Format = function(format){    
    var s = format;
    if (!s && s.length==0) s="MM/dd/yyyy h:mm tt";

    var reArray = {
            "dddd"	: this.getDayName(),
			"ddd"	: this.getShortDayName(),
            "dd"    : this.CheckZero(this.getDate()),
            "d"     : this.getDate(),
            
            "MMMM"	: this.getMonthName(),
            "MMM"	: this.getShortMonthName(),
            "MM"    : this.CheckZero(this.getMonth() + 1),
            "M"     : (this.getMonth() + 1),            
            
            "yyyy"  : this.getFullYear(),
            "yy"    : this.getShortYear(),
                        
            "hh"    : (this.getHours()==0||this.getHours()==12?12:(this.CheckZero(this.getHours() % 12))),
            "h"     : (this.getHours()==0||this.getHours()==12?12:(this.getHours() % 12)),
            
            "HH"    : this.CheckZero(this.getHours()),
            "H"     : this.getHours(),
                        
            "mm"    : this.CheckZero(this.getMinutes()),
            "m"     : this.getMinutes(),
            
            "ss"    : this.CheckZero(this.getSeconds()),            
            "s"     : this.getSeconds(),
            
            "tt"	: this.getNoonState(),
            "t"		: this.getNoonState()
        };
        
    var keysArray = [], token = s.charAt(0).toString(), sa = [];
    for(var reStr in reArray) keysArray.push(reStr);
    for(var i=1,iLen=s.length+1;i<iLen;++i){
		if (s.charAt(i) == token.charAt(0))
			token+=s.charAt(i).toString();
		else {
			sa[sa.length]=this.ParseToken(token,reArray,keysArray);
			token = s.charAt(i).toString();
		}
    }
    return sa.join('');
}

Date.prototype.ToString = function(format){
	return(str_IsStringEmpty(format))?this.Format("MM/dd/yyyy h:mm tt"):this.Format(format);
}

Date.prototype.CheckZero = function(number){
    return(number<10?"0":"")+number;
}

Date.prototype.ToPostParam = function(){
	return this.getFullYear() + "-" + (this.getMonth()+1) + "-" + this.getDate();
}

Date.prototype.FromPostParam = function(s){
	var temp = s.split("-");
	return(temp.length == 3)?new Date(temp[0], parseInt(temp[1])-1, temp[2]):null;
}

// Url helper
function url_MakeParam(name, value, useempty){
	if (str_IsStringEmpty(name))return '';
	if (str_IsStringEmpty(value) && !useempty)return '';
	return [name,'=',encodeURIComponent(value)].join('');
}

function url_CombineParams(p1, p2){
	if (str_IsStringEmpty(p1))return p2;
	if (str_IsStringEmpty(p2))return p1;
	return [p1,'&',p2].join('');
}

function url_GetPath(u){
	if (str_IsStringEmpty(u))return null;
	return u.split('?')[0];
}

function url_GetQueryString(u){
	if (str_IsStringEmpty(u))return '';
	var parts = u.split('?');
	return (parts.length < 2)?'': parts[1].split('#')[0];
}

function url_AddParameters(u, params){
	if (str_IsStringEmpty(u)||str_IsStringEmpty(params))return u;
	return [u,(u.indexOf('?')==-1)?'?':'&',params].join('');
}

function url_AddParam(u, name, value){
	return url_AddParameters(u, url_MakeParam(name, value));
}

function url_GetParam(u, name){
	return url_GetQueryStringParam(url_GetQueryString(u), name);
}

function url_ReplaceParam(u, name, value){
	return url_AddParameters(url_GetPath(u), url_ReplaceQueryStringParam(url_GetQueryString(u), name, value));
}

function url_RemoveParam(u, name){
	return url_ReplaceParam(u, name, null);
}

function url_ReplaceQueryStringParam(query, name, value){
	if (str_IsStringEmpty(query) || str_IsStringEmpty(name))return null;
	var valpairs = query.split('&'), resquery = "";
	for (var i=0,iLen=valpairs.length;i<iLen;++i){
		var val = valpairs[i].split('=');
		if (val.length != 2 || name == val[0])continue;
		resquery = url_CombineParams(resquery, valpairs[i]);
	}
	return url_CombineParams(resquery, url_MakeParam(name, value));
}

function url_GetQueryStringParam(query, name){
	if (str_IsStringEmpty(query))return null;
	var valpairs = query.split('&');
	for (var i=0,iLen=valpairs.length;i<iLen;++i){
		var value = valpairs[i].split('=');
		if (value.length != 2)continue;
		if (name == value[0])return value[1];
	}
	return null;
}

function url_CombineUrlWithQuery(u, query){
	return url_AddParameters(url_GetPath(u), url_CombineQueryStrings(url_GetQueryString(u), query));
}

function url_CombineQueryStrings(query1, query2){
	if (str_IsStringEmpty(query1))return query2;
	if (str_IsStringEmpty(query2))return query1;
	var result = query1, valpairs = query2.split('&');
	for (var i=0,iLen=valpairs.length;i<iLen;++i){
		var value = valpairs[i].split('=');
		if (value.length != 2)continue;
		result = url_ReplaceQueryStringParam(result, value[0], null);
	}
	return url_CombineParams(result, query2);
}

function url_GetCurWndParam(name){
	return url_GetParam(window.location.href, name);
}


function cmn_htmlEncode(s){
	return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
} 

function cmn_htmlDecode(s){
	return String(s).replace(/&quot;/g, "\"").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
} 

function cmn_htmlAttrEncode(s){
	return String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
} 

function cmn_htmlAttrDecode(s){
	return String(s).replace(/&quot;/g, "\"").replace(/&amp;/g, "&");
} 

function cmn_scriptEncodeString(s){
	return s.replace(/\\/gi, "\\\\").replace(/\"/gi, "\\\"").replace(/\n/gi, "\\n");
}

String.prototype.isEmpty = function() {
    return (this.trim().length == 0);
}

// Replaces each format item in a specified string with the text equivalent of a corresponding object's value
// Form of the format item is ~n where n is a zero-based integer
String.prototype.format = function() {
	var result = this.valueOf();
	if (typeof(arguments[0]) != 'undefined') {
		reParam = new RegExp("~(\\d+)","igm");
		var paramsMatches = result.match(reParam);		
		if(paramsMatches)
			for (var i=0; i < paramsMatches.length; i++) {
				var paramIndex = parseInt(paramsMatches[i].substring(1));
				result = result.replace(paramsMatches[i], arguments[paramIndex]);
			}
	}
	return result;
}

/*****************************************************************/
function cmn_EventCollection(){
	this.collection = new dm_KeyedCollection();
	this.idcount = 0;
}

cmn_EventCollection.prototype.AddEvent=function(func){
	this.collection.Add(++this.idcount, func);
	return this.idcount;
}

cmn_EventCollection.prototype.DeleteEvent=function(id){
	this.collection.Delete(id);
}
cmn_EventCollection.prototype.GetCount=function(){
	return this.collection.getCount();
}

cmn_EventCollection.prototype.GetByIndex=function(idx){
	return this.collection.GetByIndex(idx);
}

function cmn_EventContainer(eventsMapping){
	this.events = new dm_KeyedCollection();
	var thisObj = this;
	
	this.attachEvent = function(evtname, func){
		var evts = thisObj.events.Get(evtname);
		if (evts == null){
			evts = new cmn_EventCollection();
			thisObj.events.Add(evtname, evts);
		}
		return evts.AddEvent(func);
	}
	
	this.detachEvent=function(evtname, id){
		var evts = thisObj.events.Get(evtname);
		if (evts != null)evts.DeleteEvent(id);
	}
	
	this.fireEvent=function(evtname /*params[] called params*/){	
		var evts = thisObj.events.Get(evtname);
		if (evts == null)return;
		var params = [];
		for(var i=1,iLen=arguments.length;i<iLen;++i)
			params.push(arguments[i]);
		for (var i=0;	i<evts.GetCount();++i){
			if (evts.GetByIndex(i).constructor != String)
				evts.GetByIndex(i).apply(window, params);		
			else {
				try {var fn = eval(evts.GetByIndex(i)); fn.apply(window, params); } catch(e){}
			}
		}
	}
	
	this.loadEvents=function(str){
		if (!str_IsStringEmpty(str)){
			var evts = str.split(";");
			for(var i=0; i<evts.length; ++i){
				var tmp = evts[i].split(":");
				if (tmp.length > 1){
					var evtlist = tmp[1].split(",");
					for(var j=0; j<evtlist.length; ++j)
						this.attachEvent(tmp[0], evtlist[j]);
				}
			}
		}
	}
	
	this.getEventsCount=function(evtname){
		var evts = thisObj.events.Get(evtname);
		if (evts == null)return 0;
		return evts.GetCount();
	}

	if (typeof(eventsMapping) != 'undefined') {
		this.loadEvents(eventsMapping);
	}
}
DeclareNamespace("Xml");
	
DeclareClass("Xml.Attribute", null,
{
	constructor : function(n,v)
	{
		this.name = n;
		this.value = v;
	}
});

DeclareClass("Xml.Helper", null,
{
	SetNodeAttributes : [ decl_static, function(nd, attr)
	{	
		if (attr)
			for(var i = 0; i< attr.length; i++)
				nd.setAttribute(attr[i].name, attr[i].value);
	}]
	,GetNodeAttribute : [ decl_static, function(nd, name)
	{	
		return nd.getAttribute(name);
	}]
	,SetNodeAttribute : [ decl_static, function(nd, nm, val)
	{	
		nd.setAttribute(nm, val);
	}]
	,PrepareXPathLiteral : [ decl_static, function(val)
	{	
		if (val.indexOf("\"") != -1)
		{
			var v = val.split("\"");
			if (v.length > 0)
				return "concat(\"" + v.join("\",'\"\',\"") + "\")";
		}
		return "\"" + val + "\"";
	}]
});

DeclareClass("Xml.Document", null, 
{
	constructor : function(xml)
	{
		this.xmlDoc = null;
		this.LoadXml(xml);
	}
	,GetXml : function()
	{
		if (this.xmlDoc == null)
			return null;
		return this.xmlDoc.xml;
	}
	,GetXmlDocument : function()
	{
		return this.xmlDoc;
	}
	,HasErrors : function()
	{
		// SCH: implement it
	}
	,LoadXml : function(x)
	{
		if (x == null)
		{
			this.xmlDoc = null;
			return;
		}
		
		// 'unknown' type verification is needed in case we have to instantiate  IE DOMDocument
		// using responseBody property of XMLHttpRequest object (text/xml UTF-16 response workaround)
		if ((BrowserInfo.IsIE() && typeof(x) === 'unknown') || x.constructor == String)
		{
			if (typeof(window.ActiveXObject) != 'undefined') 
			{
				var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
				xmlDoc.async = false;
				xmlDoc.resolveExternals = false;
				xmlDoc.validateOnParse = false;
				xmlDoc.loadXML(x);
				this.xmlDoc = xmlDoc;
				this.xmlDoc.setProperty("SelectionLanguage", "XPath");
			}
			else
			{
				if(x != "")
				{
					var dParser = new DOMParser();
					this.xmlDoc = dParser.parseFromString(x, "text/xml");
				}else
					this.xmlDoc = document.implementation.createDocument("", "", null);
			}
		}
		else
			this.xmlDoc = x;
	}
	,TryToAdoptNode : [decl_static, function (node, child)
	{
		try
		{
			if (node && child)
			{
				var doc = node.nodeType == 9 ? node : node.ownerDocument;
				if (doc != child.ownerDocument && doc.adoptNode)
				{
					child = doc.adoptNode(child);
				}
			}
		}
		catch(e)
		{}
		return child;
	}]
	,AppendChild : [decl_static, function (parent, child)
	{
		if (parent && child)
		{
			this.TryToAdoptNode(parent, child);
			return parent.appendChild(child);
		}
		return null;
	}]
	,ReplaceChild : [decl_static, function (parent, newNode, oldNode)
	{
		if (parent && newNode && oldNode)
		{
			newNode = this.TryToAdoptNode(oldNode, newNode);
			parent.replaceChild(newNode, oldNode);
		}
		return newNode;
	}]
	,InsertBefore : [decl_static, function (parent, newNode, oldNode)
	{
		if (parent && newNode && oldNode)
		{
			newNode = this.TryToAdoptNode(oldNode, newNode);
			parent.insertBefore(newNode, oldNode);
		}
		return newNode;
	}]
});


DeclareClass("Xml.NodeAccessor", "Xml.Document", 
{
	constructor : function(xml)
	{
		this.base(xml);
		this.lookupNamespaceURI = null;
	}
	// nsMapping parameter is object literal of following format: 
	// { prefix_1 : 'namespaceURI_1', ...,  prefix_N: 'namespaceURI_N' }
	,SetNSResolver : function(nsMapping) {
		if (this.xmlDoc) {			
			// IE
			if (BrowserInfo.IsIE()) {
				var ns = [];			
				for (var prefix in nsMapping) {
					if (nsMapping.hasOwnProperty(prefix)) {
						ns[ns.length] = "xmlns:~0='~1'".format(prefix, nsMapping[prefix]);
					}
				}
				if (ns.length) {
					this.xmlDoc.setProperty("SelectionNamespaces", ns.join(' '));
				}
			} // Firefox
			else {
				this.lookupNamespaceURI = function(prefix) {	
					return nsMapping ? nsMapping[prefix] : "";
				}	
			}
		}
	}
	,IsDocumentNode : function ()
	{
		if (this.xmlDoc == null)
			return false;
		return this.xmlDoc.nodeType == 9;
	}
	,GetRootNode : function()
	{
		return this.IsDocumentNode() ? this.xmlDoc.firstChild : this.xmlDoc;
	}
	,SetXml : function(xml)
	{
		if (this.IsDocumentNode())
			this.LoadXml(xml);
		else
		{
			var newNode = new Xml.Document(xml).xmlDoc.documentElement;

			this.xmlDoc = Xml.Document.ReplaceChild(this.xmlDoc.parentNode, newNode, this.xmlDoc);
		}
	}
	,SelectSingleNode : function(cXPathString)
	{
		if (this.xmlDoc == null) return null;		
		if (BrowserInfo.IsIE()) {
			return this.xmlDoc.selectSingleNode(cXPathString);
		} 
		else
		{
			return this.xmlDoc.selectSingleNode(cXPathString, null, this.lookupNamespaceURI);
		}
	}
	,SelectNodes : function(cXPathString)
	{
		if (this.xmlDoc == null) return null;		
		if (BrowserInfo.IsIE()) {
			return this.xmlDoc.selectNodes(cXPathString);
		}
		else {
			return this.xmlDoc.selectNodes(cXPathString, null, this.lookupNamespaceURI);
		}
	}
	,RemoveNode: function(cXPathString)
	{
		if (this.xmlDoc != null)
		{
			var node = this.SelectSingleNode(cXPathString);
			if (node)
			{
				var parent = node.parentNode;
				if (parent) 
				{
					parent.removeChild(node);
				}
			}			
		}		
	}
	,GetFirstChild : function()
	{
		if (this.xmlDoc == null)
			return null;
		return this.xmlDoc.firstChild;
	}
	,GetChildNodes : function()
	{
		if (this.xmlDoc == null)
			return null;
		return this.xmlDoc.childNodes;
	}
	,AddNode : function(parent, node)
	{
		// SCH: I think it is better to swap parameters
		if (!node ) return;
		if (!parent ) parent = this.GetRootNode();

		return Xml.Document.AppendChild(parent, node);
	}
	,CreateElement : function(nm)
	{
		var d = this.xmlDoc;
		if (this.xmlDoc.ownerDocument != null)
			d = this.xmlDoc.ownerDocument;
		return d.createElement(nm); 
	}
	,CreateNode : function(nodename, nodevalue, attr)
	{
		if (str_IsStringEmpty(nodename))
			return;
		var node = this.CreateElement(nodename);
		if (!str_IsStringEmpty(nodevalue))
			node.text = nodevalue;
		if (attr)
			Xml.Helper.SetNodeAttributes(node, attr);
		return node;
	}
	,GetNodeByName : function(name)
	{
		if (str_IsStringEmpty(name))
			return null;
		return this.GetRootNode().selectSingleNode(name);
	}
	,GetNodeValue : function(name)
	{
		var xNode = this.GetNodeByName(name);
		if (xNode != null)
			return xNode.text;
		return null;
	}
	,GetNodeXmlValue : function(name)
	{
		var xNode = this.GetNodeByName(name);
		if (xNode != null)
			return xNode.xml;
		return null;
	}
	,SetNodeValue : function(name, val, attr)
	{
		var isAttributeNode = name.indexOf("@") == 0;		
		
		var xNode = this.GetNodeByName(name);
		
		if (xNode == null) {
			if (isAttributeNode) {
				this.SetAttribute(name.substr(1), val);
			} else {
				xNode = this.CreateSubNode(name, val);
			}			
		} else {
			xNode.text = val;
		}
		
		if (!isAttributeNode && attr) {
			Xml.Helper.SetNodeAttributes(xNode, attr);
		}
	}
	,SetNodeXmlValue : function(name, val)
	{
		var xNode = this.GetNodeByName(name);
		if (xNode == null)
			xNode = this.CreateSubNode(name, "");
		new Xml.NodeAccessor(xNode).SetXml( val );
	}
	,SetNodeAttributes : function(name, attr)
	{
		var xNode =  this.GetNodeByName(name);
		if (xNode == null) {
			xNode = this.CreateSubNode(name, '');
		}
		Xml.Helper.SetNodeAttributes(xNode, attr);
	}
	,GetNodeAttribute : function(name, att)
	{
		var xNode = this.GetNodeByName(name);
		if (xNode == null)
			return null;
		return Xml.Helper.GetNodeAttribute(xNode, att);
	}
	,CreateSubNode : function(name, text, p)
	{	
		var xNode = this.CreateElement(name);
		if (xNode != null)
		{		
			if (text != null)
				xNode.text = text;
			if (p == null)
				p = this.GetRootNode();
			p.appendChild(xNode);
		}
		return xNode;
	}
	,SetAttribute : function(attr, value, nd)
	{
		if (nd == null)
			nd = this.GetRootNode();
		Xml.Helper.SetNodeAttribute(nd, attr, value);
	}
	,GetAttribute : function(attr, nd)
	{
		if (nd == null)
			nd = this.GetRootNode();
		return Xml.Helper.GetNodeAttribute(nd, attr);
	}
});


DeclareClass("Xml.XslTransformer", null, 
{
	constructor : function(xsl)
	{
		this.xsltProcessor = null;
		this.Init(xsl);
	}
	,Init : function(xsl) 
	{
		if (xsl == null)
			return;
		if (typeof(window.ActiveXObject) != 'undefined') 
		{
			this.xsltProcessor = new Xml.Document(xsl).GetXmlDocument();
			//VK: This code cause memory leak problem
			/*var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
			xslDoc.async=false;
			xslDoc.loadXML(xsl);
			
			var xslt = new ActiveXObject("Msxml2.XSLTemplate");
			xslt.stylesheet = xslDoc;
			this.xsltProcessor = xslt.createProcessor();*/
		}
		else
		{
			var dParser = new DOMParser();
			var xslDoc = dParser.parseFromString(xsl, "text/xml");
			this.xsltProcessor = new XSLTProcessor();
			this.xsltProcessor.importStylesheet(xslDoc);
		}	
	}
	,Transform : function(xmlDoc) 
	{
		if (typeof(xmlDoc) != "object" || this.xsltProcessor == null)
			return "";
			
		var res = "";
		xmlDoc = new Xml.Document(xmlDoc.xml).GetXmlDocument();
		if (typeof(window.ActiveXObject) != 'undefined') 
		{
			//VK: This code cause memory leak problem
			/*this.xsltProcessor.input = xmlDoc;
			this.xsltProcessor.transform();
			res = this.xsltProcessor.output;*/
			res = xmlDoc.transformNode(this.xsltProcessor);
		}	
		else
		{
			var resDoc = this.xsltProcessor.transformToFragment?
					this.xsltProcessor.transformToFragment(xmlDoc, document):this.xsltProcessor.transformToDocument(xmlDoc);

			if (this.xmlSerializer == null) 
			{
				this.xmlSerializer = new XMLSerializer();
			}
			
			res = this.xmlSerializer.serializeToString(resDoc).replace(/<\/?transformiix:result[^>]*>/ig, "");
		}
		return res;
	}
});


DeclareClass("Xml.DataIsland", "Xml.NodeAccessor",
{
	constructor : function(xml) {
		this.base(xml);
	},	
	
	Register: [decl_static, function Xml_DataIsland_Register(name, clientID) {
		
		// instantiate data object
		if (!this.data) {
			this.data = [];
		}		
		var element = $(clientID);
		if (element) {
			var xml = "";
			if (BrowserInfo.IsIE()) {
				xml = element.XMLDocument;
			}
			else {
				xml = element.innerHTML.trim();
				xml = xml.substr(4, xml.length-7); // extract commented xml fragment
			}
			this.data[name] = new Xml.DataIsland(xml);
		
			// remove temporary data container
			var xmlContainer = element.parentNode || element.parentElement;
			if (xmlContainer) {
				xmlContainer.removeChild(element);
			}
		}
	}],
	
	// get data object by name
	Get : [decl_static, function Xml_DataIsland_Get(itemName) {
		return (this.data && this.data[itemName]) || null;
	}]	
});

DeclareNamespace("Utils");

DeclareEnum("Utils.TaskStatus",
{	
	COMPLETED:	0,
	INPROGRESS: 1,
	CANCELED:	2
});

DeclareClass("Utils.SchedulerTask", null,
{
	constructor : function()
	{
		this.__startTime = null;
		this.__taskStatus = Utils.TaskStatus.INPROGRESS;
		this.__isDetached = true;
	}
	,IsExpired : [decl_virtual, function()
	{
		if (new Date().getTime() - this.__startTime < 200)
			return false;
		return true;
	}]	
	,IsDetached : function ()
	{
		return this.__isDetached;
	}
	,ExecuteTask : function()
	{
	}
	,Complete : function()
	{
		this.SetStatus(Utils.TaskStatus.COMPLETED);
	}
	,Cancel : function()
	{
		this.SetStatus(Utils.TaskStatus.CANCELED);
	}
	,GetStatus : function()
	{
		return this.__taskStatus;
	}
	,SetStatus : function(v)
	{
		this.__taskStatus = v;
	}
	,IsCompleted : function()
	{
		return this.__taskStatus == Utils.TaskStatus.COMPLETED;
	}
	,Dispose :[decl_virtual, function()	{ }]
});

DeclareClass("Utils.HandlerTask", "Utils.SchedulerTask",
{
	constructor : function(handler, params)
	{
		this.base();
		this.__handler = handler;
		this.__params = params;
	}
	,ExecuteTask : function()
	{
		this.__handler(this.__params);
		this.Complete();
	}
	,Dispose :[decl_virtual, function()	
	{
		this.base.Dispose(); 
		this.__handler = null;
		this.__params = null;
	}]
});


DeclareClass("Utils.Scheduler", null,
{
	AddTask : [decl_static, function Utils_Scheduler_AddTask(task)
	{
		if (!this.__tasks)
			this.__tasks = [];
		this.__tasks.push(task);
		task.__isDetached = false;
		task.__taskStatus = Utils.TaskStatus.INPROGRESS;
		if (this.__tasks.length == 1 && (this.__execInProgress != true))		// first task 
		{
			this.__counter = 0;
			this.RestartTimer();
		}
	}]	
	,AddHandlerTask : [decl_static, function(handler, params)
	{
		this.AddTask(new Utils.HandlerTask(handler, params));
	}]
	,ExecuteTasks : [decl_static, function Utils_Scheduler_ExecuteTasks()
	{
		this.__counter ++;
		if (this.__timerId)
		{
			window.clearTimeout(this.__timerId);
			this.__timerId = null;
		}
		var curTask = this.__tasks.shift();
		curTask.__startTime = new Date().getTime();
		this.__execInProgress = true;
		if (curTask.GetStatus() == Utils.TaskStatus.INPROGRESS)
			curTask.ExecuteTask();
		switch( curTask.GetStatus())
		{
			case Utils.TaskStatus.INPROGRESS:
				this.__tasks.push(curTask);
				break;
			default:
				curTask.__isDetached = true;
				curTask.Dispose();	
				break;
		}
		this.__execInProgress = false;
		if (this.__tasks.length == 0)
		{
		//	alert(this.__counter);
			return;
		}
		this.RestartTimer();
	}]	
	,RestartTimer : [decl_static, function Utils_Scheduler_RestartTimer()
	{
		this.__timerId = window.setTimeout(this.CreateCallback(this.ExecuteTasks), 1);		
	}]	
	,Dispose : [decl_static, function Utils_Scheduler_Dispose()
	{
		if (this.__timerId)
		{
			window.clearTimeout(this.__timerId);
			this.__timerId = null;
		}
		if (this.__tasks != null)
			for(var i=0; i < this.__tasks.length; i++)
				this.__tasks[i].Dispose();
		this.__tasks = null;
	}] 	
});

DOMGarbageCollector.RegisterObject(Utils.Scheduler);

DeclareClass("Utils.EventListenerBase", null,
{
	constructor : function(obj, evtName, handler)
	{
		this.Target = null;
		this.Source = obj;
		this.EventName = evtName;
		this.Handler = handler;
	}
	,Attach : function()
	{
	}	
	,Detach : function()
	{
	}	
	,Init : function(obj)
	{
		this.Target = obj;
		this.Handler = this.GetHandler(this.Handler);
		this.Attach();
	}
	,GetHandler : function(h)
	{
		if (this.Target && h)
			return this.Target.CreateCallback(h);
		return h;
	}
	,Dispose : [decl_virtual, function()
	{
		this.Detach();
	}]
});


DeclareClass("Utils.DOMEventListener", "Utils.EventListenerBase",
{
	Attach : function()
	{
		dom_attachEventForObject(this.Source, this.EventName, this.Handler);
	}	
	,Detach : function()
	{
		dom_detachEventForObject(this.Source, this.EventName, this.Handler);
	}	
});

DeclareClass("Utils.ObjectEventListener", "Utils.EventListenerBase",
{
	constructor : function(obj, evtName, handler)
	{
		this.base(obj, evtName, handler);
		this.EventID = null;
	}
	,Attach : function()
	{
		if (this.Source.AttachEvent)
			this.EventID = this.Source.AttachEvent(this.EventName, this.Handler);
		else
			this.EventID = this.Source.attachEvent(this.EventName, this.Handler);
	}	
	,Detach : function()
	{
		if (this.Source.DetachEvent)
			this.Source.DetachEvent(this.EventName, this.EventID);
		else
			this.Source.detachEvent(this.EventName, this.EventID);
		this.EventID = null;
	}	
});


// SCH: TODO: Implement detach events manager.
DeclareClass("Utils.EventListenersManager", null,
{
	constructor : function(o)
	{
		this.__targetObject = o;
		this.__listeners = {};
		this.__counter = 0;
	}
	,Dispose : function()
	{
		this.DetachAllListener();
		 this.__listeners = null;
	}
	,AddObjectListener : function(obj, evtName, handler)
	{
		return this.AddCustomListener(new Utils.ObjectEventListener(obj, evtName, handler));
	}
	,AddDOMListener : function(obj, evtName, handler)
	{
		return this.AddCustomListener(new Utils.DOMEventListener(obj, evtName, handler));
	}
	,AddCustomListener : function(lst)
	{
		var key = "__ListenerKey" + this.__counter.toString();
		lst.Init(this.__targetObject);
		this.__listeners[key] = lst;
		this.__counter++;
		return key;
	}
	,DetachAllListener : function()
	{
		for(var key in this.__listeners)
			this.DetachListener(key);
		this.__listeners = {};
		this.__counter = 0;
	}
	,DetachListener : function(key)
	{
		if (this.__listeners[key] != null && key.indexOf("__ListenerKey") != -1)
		{
			this.__listeners[key].Dispose();
			delete(this.__listeners[key]);
		}
	}
});

//----------------
DeclareClass("Utils.CustomEventListener", "Utils.EventListenerBase",
{
	constructor: function(obj, evtsmap)
	{
		this.evtsmap = evtsmap == null ? [] : evtsmap;
		this.handlers = {};
		this.Listeners = new Utils.EventListenersManager(this);
		this.base(obj, null, null);
	}
	,Attach : function()
	{
		if (this.Source != null)
		{
			var thisVar = this;
			for(var i=0; i < this.evtsmap.length; i++)
			{
				if (typeof(this.evtsmap[i][1]) == "function")
				{
					var eventname = this.evtsmap[i][0];
					var handler = this.GetHandler(this.evtsmap[i][1]);
					this.handlers[eventname] = handler;
					this.Listeners.AddObjectListener(this.Source, eventname, new Function ("this.EventFired(\"~0\", arguments);".format(eventname)));
				}
			}
		}
	}	
	,Detach : function()
	{
		this.Listeners.DetachAllListener();
	}
	,Dispose : [decl_virtual, function()
	{
		this.base.Dispose();
		this.evtsmap = null;
		this.handlers = null;
		this.Listeners.Dispose();
		this.Listeners = null;
	}]
	,EventFired : function(eventname, args)
	{
		if (!str_IsStringEmpty(eventname) && this.IsApplicableEvent(eventname, args) 
			&& typeof(this.handlers[eventname]) == "function")
			this.handlers[eventname].apply(null, args);
		
	}
	,IsApplicableEvent : [decl_virtual, function(eventname, args)
	{
		return true;
	}]
});

DeclareClass("Utils.DataSourceEventListener", "Utils.CustomEventListener",
{
	constructor: function(dataSourceName, groupId, onStatusChange, onItemChange, onItemDelete, onItemAdd, onBeforeItemSelect, onBeforeItemDeselect, onAfterItemSelect, onAfterItemDeselect)
	{
		this.customData = null;
		this.dataset = null;
		this.dataSourceName = dataSourceName;
		this.dataSourceItem = null;
		this.groupId = groupId;
		if (!str_IsStringEmpty(dataSourceName) && dataSourceName.indexOf("@") != -1)
		{
			var dsParts = dataSourceName.split("@");
			this.dataSourceName = dsParts[0];
			this.dataSourceItem = dsParts[1];	
		}
		this.base(this.GetCollection(), [["onstatuschange", onStatusChange], 
										 ["onitemchange", onItemChange], 
										 ["onitemdelete", onItemDelete],
										 ["onitemadd", onItemAdd],
										 ["onbeforeitemselect", onBeforeItemSelect],
										 ["onbeforeitemdeselect", onBeforeItemDeselect],
										 ["onafteritemselect", onAfterItemSelect],
										 ["onafteritemdeselect", onAfterItemDeselect]]);
		if (this.Source == null && !str_IsStringEmpty(this.dataSourceName))
			this.ondatasetregisteredhandle = data_attachEvent("ondatasetregistered", this.CreateCallback(this.OnDataSetRegistered) );
	}
	,Dispose : [decl_virtual, function()
	{
		this.customData = null;
		this.dataset = null;
		this.base.Dispose();
	}]
	,IsApplicableEvent : [decl_virtual, function(eventname, args)
	{
		if (!str_IsStringEmpty(this.dataSourceItem) && eventname != "onstatuschange" && args[0].GetItemID() != this.dataSourceItem)
			return false;
		return true;
	}]
	,OnDataSetRegistered : function(xDs)
	{
		if (this.dataSourceName != xDs.name)
			return;
		this.Source = this.GetCollection();
		this.Attach();
		this.EventFired("onstatuschange", [xDs]);
		data_detachEvent("ondatasetregistered",  this.ondatasetregisteredhandle);
	}
	,SetCustomData : function(data)
	{
		this.customData = data;
	}
	,GetCollection : function()
	{
		if (this.dataset == null)
		{
			this.dataset = data_GetDataset(this.dataSourceName);
			if (this.dataset != null && !str_IsStringEmpty(this.groupId))
				this.dataset = this.dataset.GetGroupingItemsCopy(this.groupId);
		}
		return this.dataset;
	}
	,GetDataSource : function()
	{
		if (this.customData != null)
			return this.customData;
		var ds = this.GetCollection();
		if (ds != null)
		{
			if (ds.status.status != DE_STATUS_COMPLETE)
				ds = null;
			else if (!str_IsStringEmpty(this.dataSourceItem))
				return ds.GetItemCopy(this.dataSourceItem);
		}
		return ds;
	}
	,GetStatusText : function()
	{
		var ds = this.GetCollection();
		if (ds != null)
			return ds.status.statusText;
		return "";
	}
});

DeclareClass("Utils.Conveyer", null, {
	Run : [decl_static, function Utils_Conveyer_Run() {
		var result = null;
		for (var i = 0, length = arguments.length; i < length; i++) {
		  var f = arguments[i];
			if (result = f()) {
				break;
			}
		}
		return result;
	}]
	,Try : [decl_static, function Utils_Conveyer_Try() {
		var result = null;
		for (var i = 0, length = arguments.length; i < length; i++) {
			var f = arguments[i];
			try {
				result = f();
				break;
			} catch(e) {}
		}
		return result;
	}]
});


//************************************************ GlobalKeywordsManager ********************************************//
var CNST_ROOT = "Root";
var CNST_TYPE = "Type";
var CNST_SAVECOMMAND = "SaveCommand";
var CNST_TYPENAME = "TypeName";
var CNST_METHODS = "Methods";
var CNST_METHOD = "Method";
var CNST_OBJECTREFS = "ObjectRefs";
var CNST_OBJECTREF = "ObjectRef";
var CNST_KEYWORDS = "Keywords";
var CNST_KEYWORD = "Keyword";
var CNST_KEY = "Key";

DeclareClass("Utils.KeywordsHelper", null, 
{
	Convert : [ decl_static, function(keywords)
	{	
		if (typeof(keywords) == "string")
			return keywords.split(Utils.KeywordsHelper.Delimiter);
		return keywords;
	}]
	
	,GenerateXPath : [ decl_static, function(methodName, phrase)
	{	
		var resPath = "";
		var resTmpl = "//"+CNST_OBJECTREF+"~0";
		var mnTmpl = str_IsStringEmpty(methodName) ? "" : "[../../~0/~1='~2']".format(CNST_METHODS, CNST_METHOD, methodName);
		if (str_IsStringEmpty(phrase))
			resPath = resTmpl.format(mnTmpl);
		else
		{
			var phTmpl = "";
			var tokens = Utils.KeywordsHelper.Convert(phrase);
			for(var i = 0; i < tokens.length; i++)
			{
				var subtoken = tokens[i].split(Utils.KeywordsHelper.Operators.AND);
				var tkTmpl = "";
				for(var j = 0; j < subtoken.length; j++)
				{
					var subtk = str_Trim(subtoken[j]);
					var keywordTmpl = "";
					if (subtk == Utils.KeywordsHelper.ANY)
						keywordTmpl = "[~0/~1]";
					else if (subtk.indexOf("!") == 0)
					{
						keywordTmpl = "[not(~0/~1 = '~2')]";
						subtk = subtk.substr(1);
					}
					else
						keywordTmpl = "[~0/~1 = '~2']";
						
					tkTmpl += keywordTmpl.format(CNST_KEYWORDS, CNST_KEYWORD, subtk);
				}
				if ( !str_IsStringEmpty(resPath) )
					resPath += "|";
				resPath += resTmpl.format( mnTmpl + tkTmpl );
			}
		}
		return resPath;
	}]
	
	,GenerateSCXPath : [ decl_static, function(methodName, keywords)
	{	
		var resPath = "";
		var mnTmpl = "";
		var resTmpl = "//"+CNST_SAVECOMMAND+"~0";
		if (!str_IsStringEmpty(methodName))
			mnTmpl += "[~0 = '~1']".format(CNST_METHOD, str_Trim(methodName));
		
		resTmpl = resTmpl.format(mnTmpl);
		
		var tokens = Utils.KeywordsHelper.Convert(keywords);
		if (tokens != null)
			for (var i=0; i < tokens.length; i++)
			{
				if (!str_IsStringEmpty(resPath))
					resPath +="|";
				resPath += resTmpl+"[~0 = '~1']".format(CNST_KEYWORD, str_Trim(tokens[i]));
			}
		return resPath;
	}]
	
	,Delimiter : [decl_static, ","]
	
	,Operators : [decl_static, { "AND" : "&&" , "NOT" : "!"}]
	
	,ANY : [decl_static, "*" ]
});

DeclareClass("Utils.XMLSaveCommand", null,
{
	constructor: function(xml, methodName, keyword, key)
	{
		if (xml == null)
			xml = this.__GetXml(methodName, keyword, key)
		this.__savecommandXML = new Xml.NodeAccessor(xml);
	}
	
	,__GetXml : function(methodName, keyword, key)
	{
		return "<~0><~1>~4</~1><~2>~5</~2><~3>~6</~3></~0>".format(CNST_SAVECOMMAND, CNST_METHOD, CNST_KEYWORD, CNST_KEY, str_Trim(methodName), str_Trim(keyword), key);
	}
	
	,GetNode : function()
	{
		return this.__savecommandXML.GetRootNode();
	}
	
	,Create : [ decl_static, function( methodName, keyword, key)
	{	
		return new Utils.XMLSaveCommand(null, methodName, keyword, key);
	}]
});


DeclareClass("Utils.XMLTypeSerializer", null,
{
	constructor: function(xml)
	{
		if (xml == null)
			xml = this.__GetEmptyXml()
		this.__Init(xml)
	}
	
	,__Init : function(xml)
	{
		this.__typeXML = new Xml.NodeAccessor(xml);
		this.__methodsNode = new Xml.NodeAccessor(this.__typeXML.GetRootNode().childNodes[0]);
		this.__objectRefsNode = new Xml.NodeAccessor(this.__typeXML.GetRootNode().childNodes[1]);
	}
	
	,__GetEmptyXml : function()
	{
		return "<~0><~1/><~2/></~0>".format(CNST_TYPE, CNST_METHODS, CNST_OBJECTREFS);
	}
	
	,__AddMethod : function(methodName)
	{
		if (!str_IsStringEmpty(methodName) && this.__methodsNode != null)
			this.__methodsNode.AddNode(null, this.__typeXML.CreateNode(CNST_METHOD, methodName) );
	}
	
	,Clear : function()
	{
		this.__Init(this.__GetEmptyXml());
	}
	
	,LoadFromObject : function(obj)
	{
		if (obj != null)
		{
			if (typeof(obj.KWRefresh) != "function")
				throw "The object must have KWRefresh method";
				
			this.Clear();
			if (typeof(obj.GetType) == "function")
				this.__typeXML.SetAttribute(CNST_TYPENAME, obj.GetType());
				
			for(var itm in obj)
				if (typeof(obj[itm]) == "function")
					this.__AddMethod(itm.toString());
		}
	}
	
	,AddReference : function(key, keywords)
	{
		if (!str_IsStringEmpty(key) && keywords != null && keywords.length > 0 && this.__objectRefsNode != null)
		{
			var node = this.__typeXML.CreateNode(CNST_OBJECTREF);
			this.__objectRefsNode.AddNode(null, node);	
			var ref = new Xml.NodeAccessor(node)
			ref.AddNode(null, ref.CreateNode(CNST_KEY, key));
			var keywordsNode = ref.CreateNode(CNST_KEYWORDS);
			ref.AddNode(null, keywordsNode);
			var kwrds = new Xml.NodeAccessor(keywordsNode);
			for(var i = 0; i < keywords.length ; i++)	
				kwrds.AddNode(null, kwrds.CreateNode(CNST_KEYWORD, str_Trim(keywords[i])));
		}
	}
	
	,GetNode : function()
	{
		return this.__typeXML.GetRootNode();
	}
	
	,Create : [ decl_static, function(obj)
	{	
		var res = new Utils.XMLTypeSerializer();
		res.LoadFromObject(obj);
		return res;
	}]
});

DeclareClass("Utils.ReferencesCollection", null,
{
	constructor: function()
	{
		this.__typesXML = new Xml.NodeAccessor("<~0/>".format(CNST_ROOT));
	}
	
	,__GetTypedObject : function(obj)
	{
		var res = null;
		if (typeof(obj.GetType) == "function")
		{
			var node = this.__typesXML.SelectSingleNode("//~0[@~1='~2']".format(CNST_TYPE, CNST_TYPENAME, obj.GetType()));
			if (node != null)
				res = new Utils.XMLTypeSerializer(node);
		}
		if (res == null)
		{
			res = Utils.XMLTypeSerializer.Create(obj);
			this.__typesXML.AddNode(null, res.GetNode());
		}
		return res;
	}
	
	,AddObjectReference : function(obj, key, keywords)
	{
		var typeXML = this.__GetTypedObject(obj);
		typeXML.AddReference(key, Utils.KeywordsHelper.Convert(keywords));
	}
	
	,DeleteObjectReference : function(key)
	{
		var node = this.__typesXML.SelectSingleNode("//~0[~1='~2']".format(CNST_OBJECTREF, CNST_KEY, key) );
		if (node != null)
			node.parentNode.removeChild(node);
	}
	
	,GetObjectReferences : function(methosName, phrase)
	{
		var res = [];
		var nodes = this.__typesXML.SelectNodes(Utils.KeywordsHelper.GenerateXPath(methosName, phrase));
		if (nodes != null)
			for(var i = 0;  i < nodes.length; i++)
				res.push(new Xml.NodeAccessor(nodes[i]).GetNodeValue(CNST_KEY));
		return res;
	}
	
	,AddSaveCommandReference : function(methodName, key, keyword)
	{
		var savecommandXML = Utils.XMLSaveCommand.Create(methodName, keyword, key)
		this.__typesXML.AddNode(null, savecommandXML.GetNode());
	}
	
	,GetSavedCommandReference : function(methodName, keyword)
	{
		var res = null;
		var node = this.__typesXML.SelectSingleNode(Utils.KeywordsHelper.GenerateSCXPath(methodName, keyword));
		if (node != null)
			res = new Xml.NodeAccessor(node).GetNodeValue(CNST_KEY);
		return res;
	}
	
	,GetSavedCommandsReference : function(keywords)
	{
		var res = [];
		var nodes = this.__typesXML.SelectNodes(Utils.KeywordsHelper.GenerateSCXPath(null, keywords));
		if (nodes != null)
		{
			for(var i=0; i < nodes.length; i++)
			{
				var node = new Xml.NodeAccessor(nodes[i]);
				var tmp = {}
				tmp[CNST_KEY] = node.GetNodeValue(CNST_KEY);
				tmp[CNST_METHOD] = node.GetNodeValue(CNST_METHOD);
				res.push( tmp );
			}
		}
		return res;
	}
	,HasKeyword : function(key, keyword)
	{
		return this.__typesXML.SelectSingleNode("//~0[~1='~2'][~3/~4='~5']".format(CNST_OBJECTREF, CNST_KEY, key, CNST_KEYWORDS, CNST_KEYWORD, keyword)) != null;
	}
});

DeclareClass("Utils.GlobalKeywordsManager", null,
{
	constructor: function()
	{
		this.__refCollection = new Utils.ReferencesCollection();
		this.__objectCollections = {};
		this.__savedCommnads = {};
		this.__key = 0;
		this.__commandKey = 0;
	}	
	,Add : function(obj, keywords)
	{
		if (typeof(obj) == "object" && keywords && !str_IsStringEmpty(keywords))
		{
			var key = this.__key.toString();
			this.__key++;
			this.__refCollection.AddObjectReference(obj, key, keywords);
			this.__objectCollections[key] = obj;
			this.RunSavedCommands(obj, keywords);
			return key;
		}
		return null;
	}
	
	,SaveCommand : function(methodName, keywords, args)
	{
		var kwrs = Utils.KeywordsHelper.Convert(keywords);
		if (kwrs != null && kwrs.length == 1)
		{
			var key = this.__refCollection.GetSavedCommandReference(methodName, kwrs[0]);
			if (key == null)
			{
				key = this.__commandKey.toString();
				this.__commandKey++;
				this.__refCollection.AddSaveCommandReference(methodName, key, kwrs[0]);
			}
			this.__savedCommnads[key] = args;
		}
		else
			throw "Keyword must be only one for saved command."
	}
	
	,RunSavedCommands : function(obj, keywords)
	{
		var scommands = this.__refCollection.GetSavedCommandsReference(keywords);
		for(var i = 0; i < scommands.length; i++)
		{
			var func = obj[scommands[i][CNST_METHOD]];
			if ( func != null)
			{
				var args = this.__savedCommnads[scommands[i][CNST_KEY]];
				func.apply(obj, args != null ? args : [] );
			}
		}
	}
	,Delete : function(key)
	{
		if (!str_IsStringEmpty(key))
		{
			this.__refCollection.DeleteObjectReference(key);
			this.__objectCollections[key] = null;
			delete this.__objectCollections[key];
		}
	}
	
	,HasKeyword : function(key, keyword)
	{
		if (key != null)
			return this.__refCollection.HasKeyword(key, keyword);
		return false;
	}
	
	,ExecuteMethod : function (methodName, keywords, saveCommand, args)
	{
		if (! keywords || str_IsStringEmpty(keywords))
			return;
		var keys = this.__refCollection.GetObjectReferences(methodName, keywords);
		for(var i = 0; i < keys.length; i++)
		{
			if (this.__objectCollections[keys[i]] != null)
				this.__objectCollections[keys[i]][methodName].apply(this.__objectCollections[keys[i]], args != null ? args : [])
		}
		if (saveCommand == true)
			this.SaveCommand(methodName, keywords, args);
	}
	,KWRefresh : function(keywords, args)
	{
		this.ExecuteMethod("KWRefresh", keywords, false, args);
	}
});

GlobalKeywordsManager = new Utils.GlobalKeywordsManager();

DeclareClass("Utils.UIControlActivityManager", null,
{
	constructor: function(ctrl, exObj)
	{
		this.ctrl = ctrl;
		this.deferArgs = null;
		this.evtAttached = false;
		this.Listeners = new Utils.EventListenersManager(this);
		this.navhand = this.CreateCallback(this.OnNavChange);
		this.navattached = false;
		this.chctrl = exObj == null ? ctrl : exObj;
	}
	,IsActive : function()
	{
		return this.chctrl.IsVisible() && !(nav_currentNavInfo != null && nav_currentNavInfo.IsNavigationInProgress());
	}
	,SetDefer : function(args)
{
		this.deferArgs = args != null ? args : [];
		if (!this.evtAttached)
	{
			if (nav_currentNavInfo != null && nav_currentNavInfo.IsNavigationInProgress())
				this.NavAttach();
			this.Listeners.AddObjectListener(this.chctrl, "onvisiblechange", this.OnActiveChange);
			this.evtAttached = true;
	}	
	}
	,NavAttach : function()
	{
		if (!this.navattached)
		{
			nav_postAction.Add(this.navhand);
			this.navattached = true;
		}
	}
	,OnNavChange : function()
	{
		this.navattached = false;
		this.OnActiveChange();
	}
	,OnActiveChange : function()
	{
		if (this.IsActive() && this.deferArgs != null)
	{
			this.Listeners.DetachAllListener();
			this.evtAttached = false;
			this.ctrl.AMLoad.apply(this.ctrl, this.deferArgs);
			this.deferArgs = null;
	}
		else if (nav_currentNavInfo != null && nav_currentNavInfo.IsNavigationInProgress())
			this.NavAttach();
	}
	,KWRefresh :[decl_virtual, function(txt, params)
	{
		var res = [txt, params];
		if (this.IsActive())
			this.ctrl.AMLoad.apply(this.ctrl, res);
		else
			this.SetDefer(res);
	}]
	,Dispose : function()
	{
		nav_postAction.Delete(this.navhand);
		this.navattached = false;
		this.navhand = null;
		this.Listeners.Dispose();
		this.Listeners = null;
		this.deferArgs = null;
		this.ctrl = null;
	}
});

DeclareClass("Utils.UIControlActivityManagerEx", "Utils.UIControlActivityManager",
	{
	constructor: function(ctrl, exObj)
	{
		this.isExec = true;
		this.base(ctrl, exObj);
	}
	,ExecuteCommand : function (name, params, txt, skipExecution)
	{
		var arr = {};
		arr["pname"] = name;
		arr["pvalue"] = params;
		arr["skipExecution"] = skipExecution;

		var res = [];
		res.push(txt);
		res.push(arr);
		
		if (this.IsActive())
			this.ctrl.AMLoad.apply(this.ctrl, res);
		else
		{
			this.SetDefer(res);
			this.isExec = true;
		}
	}
	,KWRefresh :[decl_virtual, function(txt, params)
	{
		if (this.isExec && this.deferArgs != null)
			return;
		this.isExec = false;
		var res = [txt, params];
		if (this.IsActive())
			this.ctrl.AMLoad.apply(this.ctrl, res);
		else
			this.SetDefer(res);
	}]
});

DeclareClass("Utils.StringBuilder", null, 
{
	constructor: function()
	{
		this.data = [];
	}
	,Append : function(s/*,s1,s2...*/)
	{
		for(var i=0; i<arguments.length; i++)
			this.data.push(arguments[i]);
	}
	,ToString : function()
	{
		return this.data.join("");
	}
});
//--------------------- SpecialTime ------------------------
DeclareEnum("Utils.SpecialTime",
{	
	BeforeMarketOpen: "BMO",
	AfterMarketClose: "AMC",
	NoTimeSpecified: "NTS"
});
//--------------------- PeriodManager ------------------------
DeclareClass("Utils.PeriodManager", null, {
	constructor : function() {
		var today = new Date();
		
		this.StartDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0);
		this.EndDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0);
		
		this.StartTime = new Date(0, 0, 0, today.getHours(), today.getMinutes());
		this.EndTime = new Date(0, 0, 0, today.getHours(), today.getMinutes());
		
		this.isSpecialTime = false;
		this.specialTime = null;
	}
	,InitPeriod : function(startDateTime, endDateTime) {
		this.isSpecialTime = false;
		this.specialTime = null;

		if (startDateTime != null)
		{
			var date = new Date(Date.parse(startDateTime));
			this.StartDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0);
			this.StartTime = new Date(0, 0, 0, date.getHours(), date.getMinutes());
		}
		if (endDateTime != null)
		{
			var date = new Date(Date.parse(endDateTime));
			this.EndDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0);
			this.EndTime = new Date(0, 0, 0, date.getHours(), date.getMinutes());
		}
	}
	,TimeParse : [decl_static, function(timeString) {
		if(!new RegExp("^\\s*(((0?\\d|1[0-2]):[0-5]\\d\\s*[AP]M)|(([0-1]?\\d|2[0-3]):[0-5]\\d))\\s*$", "ig").test(timeString))
			return null;
		var array = timeString.match(new RegExp("(\\d+)|([AP]M)", "ig"));
		var hours = Number(array[0]);
		if(array.length > 2)
		{
			if (hours == 12)
				hours = 0;			
			if (array[2].toLowerCase() == 'pm')
				hours += 12;
		}
		var munutes = Number(array[1]);
		return new Date(0,0,0,hours, munutes);
	}]
	,IsSpecialTime : [decl_static, function(value) {
		var v = value.toUpperCase();
		return (v == Utils.SpecialTime.BeforeMarketOpen || 
				v == Utils.SpecialTime.AfterMarketClose || 
				v == Utils.SpecialTime.NoTimeSpecified) ? true : false;
	}]
	,GetSpecialTimeValues : [decl_static, function() {
		return [Utils.SpecialTime.BeforeMarketOpen,
				Utils.SpecialTime.AfterMarketClose,
				Utils.SpecialTime.NoTimeSpecified];
	}]
	,GetDisplayValueForSpecialTime : [decl_static, function(value) {
		switch(value.toUpperCase())
		{
			case Utils.SpecialTime.BeforeMarketOpen: return "BMO (Before Market Open)";
			case Utils.SpecialTime.AfterMarketClose: return "AMC (After Market Close)";
			case Utils.SpecialTime.NoTimeSpecified: return "NTS (No Time Specified)";
			default: return null;
		}
	}]
	,GetSpecialTimeByValue : function(value) {
		switch(value.toUpperCase())
		{
			case "BMO": return Utils.SpecialTime.BeforeMarketOpen;
			case "AMC": return Utils.SpecialTime.AfterMarketClose;
			case "NTS": return Utils.SpecialTime.NoTimeSpecified;
			default: return null;
		}
	}
	,GetStartTimeBySpecialValue : function(specialTime) {
		switch(specialTime)
		{
			case Utils.SpecialTime.BeforeMarketOpen: return "07:00";
			case Utils.SpecialTime.AfterMarketClose: return "16:00";
			case Utils.SpecialTime.NoTimeSpecified: return "07:00";
			default: return null;
		}
	}
	,GetEndTimeBySpecialValue : function(specialTime) {
		switch(specialTime)
		{
			case Utils.SpecialTime.BeforeMarketOpen: return "08:00";
			case Utils.SpecialTime.AfterMarketClose: return "17:00";
			case Utils.SpecialTime.NoTimeSpecified: return "23:00";
			default: return null;
		}
	}
	,SetSpecialStartTime : function(value) {
		if (Utils.PeriodManager.IsSpecialTime(value))
		{
			this.isSpecialTime = true;
			this.specialTime = this.GetSpecialTimeByValue(value);
			
			this.StartTime = Utils.PeriodManager.TimeParse(this.GetStartTimeBySpecialValue(this.specialTime));
			this.EndTime = Utils.PeriodManager.TimeParse(this.GetEndTimeBySpecialValue(this.specialTime));
		}
	}
	,SetStartTime : function(time) {
		this.isSpecialTime = false;
		this.specialTime = null;
		this.StartTimeChange(time);
	}
	,SetEndTime : function(time) {
		this.isSpecialTime = false;
		this.specialTime = null;
		this.EndTimeChange(time)
	}
	,SetStartDate : function(date) {
		this.StartDateChange(date);
	}
	,SetEndDate : function(date) {
		this.EndDateChange(date);
	}
	,StartTimeChange : function(time) {
		var oldStartTime = this.StartTime;
		this.StartTime = time;
		
		if (this.isSpecialTime || this.EndTime.getTime() < this.StartTime.getTime() && this.StartDate.toDateString() == this.EndDate.toDateString())
		{
			var newEndTime = new Date(this.StartTime);
			newEndTime.setDate(5);
			newEndTime.setHours(newEndTime.getHours(), newEndTime.getMinutes() + 30);
			this.EndTime = newEndTime;
			
			var newEndDate = new Date(this.EndDate.getTime());
			newEndDate.setDate(newEndDate.getDate() - 5 + newEndTime.getDate());
			this.EndDate = newEndDate;
			
			this.EndTime = this.EndTime;
		}
		else
		{
			var newEndTime = new Date(this.EndTime);
			newEndTime.setDate(5);
			newEndTime.setHours(newEndTime.getHours() + (this.StartTime.getHours() - oldStartTime.getHours()), 
				newEndTime.getMinutes()+(this.StartTime.getMinutes() - oldStartTime.getMinutes()));
			this.EndTime = newEndTime;
			
			var newEndDate = new Date(this.EndDate.getTime());
			newEndDate.setDate(newEndDate.getDate() - 5 + newEndTime.getDate());
			this.EndDate = newEndDate;
			
			this.EndTime = this.EndTime;
		}
		
		this.isSpecialTime = false;
		this.specialTime = null;
	}
	,EndTimeChange : function(time) {
		this.isSpecialTime = false;
		this.specialTime = null;
		
		this.EndTime = time;
		if ((this.EndTime.getTime() < this.StartTime.getTime()) && 
			(this.StartDate.toDateString() == this.EndDate.toDateString()))
			this.StartTime = this.EndTime;
	}
	,StartDateChange : function(date) {
		var oldStartDate = this.StartDate;
		this.StartDate = date;
		var diff = floorDate(this.StartDate).getTime() - oldStartDate.getTime();
		var newEndDate = new Date(this.EndDate.getTime() + diff);
		this.SetEndDate(newEndDate);
		if (!this.isSpecialTime)
			this.StartTimeChange(this.StartTime);
	}
	,EndDateChange : function(date) {
		var oldEndDate = this.EndDate;
		this.EndDate = date;
		var startDate = new Date(this.StartDate);
		if (floorDate(startDate).getTime() > this.EndDate.getTime()) {
			var sd = new Date(this.StartDate);
			var diff = oldEndDate.getTime() - floorDate(sd).getTime();
			var newStartDate = new Date(this.EndDate.getTime() - diff);
			this.StartDate = newStartDate;
		}
		if (!this.isSpecialTime)
			this.StartTimeChange(this.StartTime);
	}
});

DeclareClass("Utils.GeneralPreferences", null, {
	GetTimeFormat : [decl_static, function() {
		var format = str_IsStringEmpty(GeneralPreferences.TimeFormatExpression) ? "hh:mm tt" :
				GeneralPreferences.TimeFormatExpression;
		return format;
	}],
	GetDateFormat : [decl_static, function() {
		var format = str_IsStringEmpty(GeneralPreferences.DateFormatExpression) ? "MM/dd/yyyy" :
				GeneralPreferences.DateFormatExpression;
		return format;
	}],
	GetDateTimeFormat : [decl_static, function() {
		var format = "~0, ~1".format(this.GetDateFormat(), this.GetTimeFormat());
		return format;
	}],
	GetTrendsShowOnOtherPages : [decl_static, function() {
		alert(GeneralPreferences.EnableTrendsOnOtherPages);
		return (GeneralPreferences.EnableTrendsOnOtherPages == 'true');
	}],
	ConvertUtcToUserTime : [decl_static, function(utcDate) {
		var userDate = utcDate;
		userDate.setMinutes(userDate.getMinutes() - Utils.GeneralPreferences.GetOffsetHours())
		return userDate;
	}],
	GetOffsetHours: [decl_static, function() {
		var result = GeneralPreferences.offsetHours;
		try
		{
			if (typeof(TopWindow) !="undefined" && TopWindow!=null )
				result = TopWindow.GeneralPreferences.offsetHours;
		}catch(e){}
		return result;
	}],
	GetAgoTimeMode : [decl_static, function() {
		return GeneralPreferences.AgoTimeMode;
	}]
});

DeclareClass("Utils.MonitoringHelper", null, 
{
	GenerateTransactionID : [decl_static, function() 
	{
		var g = "";
		for(var i = 0; i < 32; i++)
			g += Math.floor(Math.random() * 0xF).toString(0xF);// + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "")
		return g;
	}]
	,SetMonitoringInfo : [decl_static, function(Action, ID, Cleartime) 
	{
		ID = (ID == null ? Utils.MonitoringHelper.GenerateTransactionID() : ID);
		Cleartime = (Cleartime == null ? 1500 : Cleartime);
		Utils.MonitoringHelper.Action = Action;	
		Utils.MonitoringHelper.ID = ID;
		//console.log("Set action:" + Utils.MonitoringHelper.Action);
		Utils.MonitoringHelper.__setTimer(Cleartime);
	}]
	,SetMonitoringInfoIfEmpty : [decl_static, function(Action, ID, Cleartime) 
	{
		if (this.GetAction() == null)  
			this.SetMonitoringInfo(Action, ID, Cleartime);
	}]
	,GetAction : [decl_static, function() 
	{
		return Utils.MonitoringHelper.Action;	
	}]
	,GetTransactionID : [decl_static, function() 
	{
		return Utils.MonitoringHelper.ID;
	}]
	,GetMonitoringLocation : [decl_static, function()
	{
		if (typeof(nav_currentNavInfo) != "undefined" && nav_IsNavigationEnabled())
		{
			var ploc = nav_currentNavInfo.GetPageLocation();
			
			if (ploc == null || ploc == PID_PLSEARCHRESULTS)
				return nav_currentNavInfo.GetPageID();
			
			return ploc;
		}		
		return null;
	}]
	,__setTimer: [decl_static, function(time)
	{
		if (Utils.MonitoringHelper.timerId != null)
			window.clearTimeout(Utils.MonitoringHelper.timerId);
			
		Utils.MonitoringHelper.timerId = window.setTimeout(Utils.MonitoringHelper.__clearMonitoringInfo, time); 
	}]
	,__clearMonitoringInfo : [decl_static, function() 
	{
		//console.log("Terminate action:" + Utils.MonitoringHelper.Action);
		Utils.MonitoringHelper.Action = null;	
		Utils.MonitoringHelper.ID = null;
		Utils.MonitoringHelper.timerId = null;
	}]
});

DeclareClass("Utils.Timer", null, 
{
	SetTimeout : [decl_static, function(func, time) 
	{
		
		var callbackObj = new Object;
		callbackObj.CallbackFunc = func;
		callbackObj.TransactionID = Utils.MonitoringHelper.GetTransactionID();
		callbackObj.Action = Utils.MonitoringHelper.GetAction();
		callbackObj.callback = function()
		{
			if (this.TransactionID != null)
				Utils.MonitoringHelper.SetMonitoringInfo(this.Action, this.TransactionID)
			this.CallbackFunc();
		}
		return window.setTimeout(callbackObj.CreateCallback(callbackObj.callback), time);
	}]
	,ClearTimeout : [decl_static, function(id) 
	{
		window.clearTimeout(id);
	}]
});
DeclareClass("Utils.SavedSearchEventListener", "Utils.EventListenerBase",
{
	constructor : function(tags,handler)
	{
		this.base(null, null, handler)
		this.__searchID = 0;
		this.AnalyzeHandler = this.CreateCallback(this.AnalyzeSearchState);
	}
	,Attach : function()
	{
		GlobalAdvancedSearchEventManager.AttachEvent("onxmlchange",this.AnalyzeHandler);	
	}	
	,Detach : function()
	{
		GlobalAdvancedSearchEventManager.DetachEvent("onxmlchange", this.AnalyzeHandler);	
	}
	,AnalyzeSearchState : [decl_virtual, function(state)
	{
		var val = srch_advGetDecimalSearchID();
		if (this.__searchID != val)
		{
			this.__searchID = val;
			this.Handler(this);
		}
	}]
	,GetSearchID : function()
	{
		return srch_advGetDecimalSearchID();
	}
	,GetAlertID : function()
	{
		return srch_advGetDecimalAlertID();
	}
});

DeclareClass("Utils.SearchEventListener", "Utils.EventListenerBase",
{
	constructor : function(tags,handler)
	{
		this.base(null, null, handler)
		this.__tags = tags;
		this.__values = [];
		this.AnalyzeHandler = this.CreateCallback(this.AnalyzeSearchState);
	}
	,Attach : function()
	{
		srch_seEventer.attachEvent("onstatechange", this.AnalyzeHandler);	
	}	
	,Detach : function()
	{
		srch_seEventer.detachEvent("onstatechange", this.AnalyzeHandler);	
	}	
	,AnalyzeSearchState : [decl_virtual, function(state)
	{
		for (var i = 0; i < this.__tags.length; i++)
		{
			switch(this.__tags[i])
			{
				case SRCH_TN_PERIOD:
					this.AnalyzePeriod(state,i);
					break;
				default:
					this.AnalyzeSearchTag(state,i);
					break;
			}
		}		
	}]
	,AnalyzePeriod : function(state,index)
	{
		if (nav_currentNavInfo.GetParameter(P_CALENDAR_FILTER_TYPE) != "1")
			state = null;
		this.AnalyzeSearchTag(state,index);
	}
	,AnalyzeSearchTag : [decl_virtual, function(state,index,filter)
	{
		if (!filter) filter = SRCH_SES_FILTER;
		var val = "";
		if (state == filter)
			val = this.GetTagValueFromSearch(this.__tags[index]);
		
		if (this.__values[index] != val)
		{
			this.__values[index] = val;
			this.Handler(this);
		}
	}]
	,GetTagValue : function(tagName)
	{
		for (var i = 0; i < this.__tags.length; i++)
		{
			if (tagName == this.__tags[i])
				return this.__values[i];
		}
	}
	,GetTagValueFromSearch : function(tagName)
	{
		var val = "";
		var tag = srch_inpGetTag(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME,tagName)));
		if (tag)
		{
			nodes = tag.getElementsByTagName(SRCH_TP_VALUE);
			if (nodes && nodes.length > 0)
				val = nodes[0].text;
		}
		return val;
	}
});

DeclareClass("Utils.ModuleEventListener", "Utils.CustomEventListener",
{
	constructor: function(id, kwdfltr, onSettingsChange, onRegister, onDispose)
	{
		this.moduleId = id;
		this.keywordFilter = kwdfltr;
		this.module = null;
		this.base(nav_WorkspaceModules, [["onmoduleregister", onRegister], ["onmoduledispose", onDispose], ["onmodulesettingschange", onSettingsChange]]);
	}
	,Dispose : [decl_virtual, function()
	{
		this.base.Dispose();
		this.module = null;
	}]
	,GetModule : function()
	{
		return this.module;
	}
	,IsApplicableEvent : [decl_virtual, function(eventname, args)
	{
		var module = args[0];
			
		var isApplicable = false;
		if (!str_IsStringEmpty(this.moduleId)) {
			isApplicable = module.GetID() == this.moduleId;
		} else {
			isApplicable = module.HasKeyword(this.keywordFilter) && module.IsVisible();
		}
						
		if (eventname == "onmoduledispose") {
			this.module = null;
		 } else if (isApplicable) {
			this.module = module;
		}		
		return isApplicable;
	}]
});


DeclareEnum("Utils.RSSLinkType",
{	
	Container : 0,
	SavedSearch: 1
});

DeclareClass("Utils.RSSLinkBuilder", null,
{
	GetURL : [decl_static, function(type, name)
	{
		var param = "";
		switch(type)
		{
			case Utils.RSSLinkType.SavedSearch:
				param = "?name=" + encodeURIComponent(name);
				return "~0/search.rss~1".format(TouchPointConfig.BaseRssUrl, param);

			case Utils.RSSLinkType.Container:
			    return "~0/~1.rss".format(TouchPointConfig.BaseRssUrl, encodeURIComponent(name));
		}
	}]
});

var dm_splitter_default = ',';
var dm_subsplitter_default = ':';

function dm_Pair(first,second)
{
	this.first = first;
	this.second = second;
}

/// Name value item class
function dm_NameValueItem(itm_name, itm_value, isNameUnique)
{
	if (isNameUnique == true)
	{
		this.first = itm_value;
		this.second = itm_name;
	}
	else
	{
		this.first = itm_name;
		this.second = itm_value;
	}
	this.isNameUnique = isNameUnique;
}
dm_NameValueItem.prototype = new dm_Pair;
dm_NameValueItem.prototype.constructor = dm_NameValueItem;
dm_NameValueItem.prototype.getName = function()
{ 
	if (this.isNameUnique == true)
		return this.second;
	else
		return this.first;
}
dm_NameValueItem.prototype.setName = function(nm)
{ 
	if (this.isNameUnique == true)
		this.second = nm;
	else
		this.first = nm;
}
dm_NameValueItem.prototype.getValue = function()
{
	if (this.isNameUnique == true)
		return this.first;
	else
		return this.second;
}
dm_NameValueItem.prototype.setValue = function(val)
{ 
	if (this.isNameUnique == true)
		this.first = val;
	else
		this.second = val;
}
dm_NameValueItem.prototype.Save = function(dm)
{
	var res = '';
	res += (dm.encodeFunc == null) ? this.getName() : dm.encodeFunc(this.getName());
	if (this.getName() != this.getValue())
	{
		res += (dm.getSplitter(1) == null) ? dm_subsplitter_default : dm.getSplitter(1);
		res += (dm.encodeFunc == null) ? this.getValue() : dm.encodeFunc(this.getValue());
	}
	return res;
}
dm_NameValueItem.prototype.Load = function(dm, s)
{
	if (s == null || s.length == 0)
		return false;
	var res = s.split((dm.getSplitter(1) == null) ? dm_subsplitter_default : dm.getSplitter(1));
	var nm;
	var val;	
	if (res.length == 2)
	{
		nm = res[0];
		vl = res[1];
	}
	else if (res.length == 1)
		nm = vl = res[0];
	else	
		return false;
	
	this.setName((dm.decodeFunc == null) ? nm : dm.decodeFunc(nm) );
	this.setValue( (dm.decodeFunc == null) ? vl : dm.decodeFunc(vl) );
	return true;
}

// keyed collection
function dm_KeyedCollection(comparer, ignoreCase)
{
	this.resetData();
	this.comparer = comparer;
	this.ignoreCase = ignoreCase;
	this.needreload = false;
}

dm_KeyedCollection.prototype.resetData = function() {
	this.items = {};
	this.indexes = [];
}

dm_KeyedCollection.prototype.prepareKey = function(key)
{
	if (this.ignoreCase == true)
		return (key+"").toLowerCase();
	return key;
}
dm_KeyedCollection.prototype.getItem = function(key)
{
	return  this.items[this.prepareKey(key)];
}
dm_KeyedCollection.prototype.GetIndexByKey = function(key)
{
	var cnt = this.indexes.length;
	if (cnt > 0)
	{
		if (this.needreload == true)
			for(var i = 0; i < cnt; i++)		
				this.getItem(this.indexes[i]).sortIndex = i;
				
		var item = this.getItem(key);
		if (item != null)
		{
			if (typeof(item.sortIndex) == "number")
				return item.sortIndex;
			
			this.needreload = true;	
			return this.GetIndexByKey(key);
		}
	}
	return -1;
}
dm_KeyedCollection.prototype.GetIndexByValue = function(val)
{
	for(var i = 0; i < this.indexes.length; i++)
		if (this.Get(this.indexes[i]) == val)
			return i;
	return -1;
}
dm_KeyedCollection.prototype.GetKeyByIndex = function(idx)
{
	return this.indexes[idx];
}
dm_KeyedCollection.prototype.Get = function(key)
{
	var item = this.getItem(key);
	if (item && item != null)
		return item.second;
	return null;
}
dm_KeyedCollection.prototype.GetByIndex = function(idx)
{
	return this.Get(this.GetKeyByIndex(idx));
}
dm_KeyedCollection.prototype.SwapItemsByIndexes = function(idx1, idx2)
{
	if (idx1 == idx2)
		return;
 	var key =  this.indexes[idx1];
 	this.indexes[idx1] = this.indexes[idx2];
 	this.indexes[idx2] = key;
}
dm_KeyedCollection.prototype.MoveItem = function(oldidx, newidx)
{
	if (oldidx == newidx || oldidx>=this.getCount() || oldidx<0 || newidx>=this.getCount() || newidx<0)
		return;
 	this.Insert(this.getItem(this.GetKeyByIndex(oldidx)),newidx);
}
dm_KeyedCollection.prototype.Add = function(key, val, notsort)
{
	return this.AddInternal(new dm_Pair(key,val), notsort);
}
dm_KeyedCollection.prototype.AddItem = function(item, notsort) 
{
	return this.AddInternal(item, notsort);
}
dm_KeyedCollection.prototype.AddInternal = function(item, notsort)
{
	if (item == null)
		return;
	if ((typeof(item.first) == "undefined") || (typeof(item.second) == "undefined") )
		return;
	if (item.first == null)
		return;
	if (this.getCount() > 0)
	{
		if (this.comparer && this.comparer.Compare && notsort != true &&
			this.comparer.Compare(this.GetByIndex(this.getCount()-1), item.second) == 1)
			{
				for(var i=0; i < this.getCount(); i++)
					if (this.comparer.Compare(this.GetByIndex(i), item.second) == 1)
					{
						this.Insert(item, i);
						return i;
					}
			}
		else if (this.getItem(item.first) != null)
		{
			this.items[this.prepareKey(item.first)].second = item.second;
			return this.GetIndexByKey(item.first);
		}
	}

	this.items[this.prepareKey(item.first)] = item;
	this.indexes[this.indexes.length] = item.first;
	item.sortIndex = this.getCount()-1;
	return item.sortIndex;
}
dm_KeyedCollection.prototype.Insert = function(item, idx)
{
	if (item == null)
		return;
	if ((typeof(item.first) == "undefined") || (typeof(item.second) == "undefined") )
		return;
	if (item.first == null)
		return;
	if (idx<0 || idx>this.getCount())
		return;
	this.Delete(item.first);
	this.items[this.prepareKey(item.first)] = item;
	switch(idx)
	{
		case 0:
			this.indexes.unshift(item.first);
			this.needreload = true;
			break;
		case this.getCount():
			this.indexes.push(item.first);
			item.sortIndex = this.getCount()-1;
			break;
		default:
			var tempar = this.indexes.splice(idx,this.indexes.length-1);
			this.indexes.push(item.first);
			this.indexes = this.indexes.concat(tempar);
			this.needreload = true;
			break;
	}
	return item.second;
}
dm_KeyedCollection.prototype.Delete = function(key) 
{
	if (key == null)
		return null;
	var item = this.getItem(key);
	if (!item)
		return null;
	this.indexes.splice(this.GetIndexByKey(key), 1);
	delete(this.items[this.prepareKey(key)]);
	this.needreload = true;
	return item;
}
dm_KeyedCollection.prototype.DeleteByIndex = function(idx) 
{
	return this.Delete(this.GetKeyByIndex(idx));
}
dm_KeyedCollection.prototype.Clear = function() 
{
	this.resetData();
}
dm_KeyedCollection.prototype.getCount = function()
{
	return this.indexes.length;
}
dm_KeyedCollection.prototype.Merge = function(col)
{
	for (var i = 0; i < col.getCount(); i++)
		this.Add(col.GetKeyByIndex(i),col.GetByIndex(i));
}
dm_KeyedCollection.prototype.Sort = function()
{
	if (this.comparer && this.comparer.Compare && this.getCount() > 1)
		tpl_quickSortR(this, 0, this.getCount()-1, this.comparer.Compare, dm_KeyedCollection.Swaper, dm_KeyedCollection.Getter);
}
dm_KeyedCollection.Swaper = function(idx1, idx2, obj)
{
	obj.SwapItemsByIndexes(idx1, idx2);
}
dm_KeyedCollection.Getter = function(idx, obj)
{
	return obj.GetByIndex(idx);
}


/// DMObject
function dm_DMObject(id, encodeFunc, decodeFunc, splitters)
{
	this.init(id, encodeFunc, decodeFunc, splitters);
}
dm_DMObject.prototype.init = function(id, encodeFunc, decodeFunc, splitters)
{
	this.id = id;
	this.splitters = splitters;
	if (this.splitters == null)
		this.splitters = new Array(dm_splitter_default, dm_subsplitter_default);
	this.encodeFunc = encodeFunc;
	this.decodeFunc = decodeFunc;
	this.isDirty = true;
	this.Load();
}
dm_DMObject.prototype.getSplitter = function(level)
{
	return this.splitters[level];
}

dm_DMObject.prototype.GetAssociatedObject = function()
{
	if (this.id == null)
		return null;
	return document.getElementById(this.id);
}
dm_DMObject.prototype.GetAssociatedObjectValue = function()
{
	var obj = this.GetAssociatedObject();
	if (obj != null)
		return obj.value;
	return null;
}
dm_DMObject.prototype.SetAssociatedObjectValue = function(v)
{
	var obj = this.GetAssociatedObject();
	if (obj != null)
		obj.value = v;
}
dm_DMObject.prototype.Save = function()
{
	var values = this.SaveInternal();
	this.SetAssociatedObjectValue(values);
	return values;
}
dm_DMObject.prototype.Load = function(s)
{
	if (s == null)
	{
		if (this.isDirty == false)	// skip loading
			return;
		s = this.GetAssociatedObjectValue();
	}
	this.isDirty = false;
	this.Clear();
	if (s != null)
		this.SetAssociatedObjectValue(s);
	if (s == null || s.length == 0)
		return;
	this.LoadInternal(s);
}
dm_DMObject.prototype.getStringValue = function()
{
	return this.Save();
}
dm_DMObject.prototype.Clear = function() 
{
	this.ClearInternal();
}
dm_DMObject.prototype.SaveInternal = function()
{
	return "";
}	
dm_DMObject.prototype.LoadInternal = function(s)
{
}	
dm_DMObject.prototype.ClearInternal = function()
{
}

/// Name value collection class
function dm_NameValueCollection(id, encodeFunc, decodeFunc, splitters, isNameUnique)
{
	this.collection = new dm_KeyedCollection();	
	if (isNameUnique == null)
		this.isNameUnique = true;
	else
		this.isNameUnique = isNameUnique;
	this.init(id, encodeFunc, decodeFunc, splitters);
}
dm_NameValueCollection.prototype = new dm_DMObject;
dm_NameValueCollection.prototype.constructor = dm_NameValueCollection;
dm_NameValueCollection.prototype.getCount = function()
{
	this.Load();
	return this.collection.getCount();
}
dm_NameValueCollection.prototype.ContainsName = function(name)
{
	return this.GetValue(name) == null ? false : true;
}
dm_NameValueCollection.prototype.GetValue = function(name)
{
	var idx = -1;
	if (this.isNameUnique == true)
		idx = this.collection.GetIndexByValue(name);
	else
		idx = this.collection.GetIndexByKey(name);
	if (idx == -1)
		return null;
	return this.GetValueByIndex(idx);
}
dm_NameValueCollection.prototype.GetNameByValue = function(name, toLower)
{
	var idx = -1;
	if (this.isNameUnique == true)
		idx = this.collection.GetIndexByKey(name, toLower);
	else
		idx = this.collection.GetIndexByValue(name);
	if (idx == -1)
		return null;
	return this.GetNameByIndex(idx);
}
dm_NameValueCollection.prototype.GetNameByIndex = function(idx)
{	
	return this.getItem(idx).getName();
}
dm_NameValueCollection.prototype.GetValueByIndex = function(idx)
{
	return this.getItem(idx).getValue();
}
dm_NameValueCollection.prototype.getItem = function(idx)
{
	this.Load();
	return this.collection.getItem(this.collection.GetKeyByIndex(idx));
}
dm_NameValueCollection.prototype.Add = function(name, val)
{
	this.Load();
	this.collection.AddItem(new dm_NameValueItem(name,val, this.isNameUnique));
}
dm_NameValueCollection.prototype.Delete = function(key) 
{
	this.Load();
	if (this.isNameUnique == true)
		this.collection.DeleteByIndex(this.collection.GetIndexByValue(key));
	else
		this.collection.Delete(key);
}
dm_NameValueCollection.prototype.Insert = function(name, val, idx) 
{
	this.Load();
	this.collection.Insert(new dm_NameValueItem(name,val,this.isNameUnique),idx);
}
dm_NameValueCollection.prototype.SaveInternal = function()
{
	var values = "";
	for(var i=0; i< this.collection.getCount(); i++)
	{
		if (values.length > 0) values += this.getSplitter(0);	
		values += this.collection.getItem(this.collection.GetKeyByIndex(i)).Save(this);
	}
	return values;
}
dm_NameValueCollection.prototype.LoadInternal = function(s)
{
	if (s == null || s.length == 0)
		return;
	var values = s.split(this.getSplitter(0));
	for (var i = 0; i < values.length; i++)
	{
		var itm = new dm_NameValueItem(null,null, this.isNameUnique);
		if (itm.Load(this, values[i]) == true)
			this.collection.AddItem(itm);
	}
}
dm_NameValueCollection.prototype.ClearInternal = function()
{
	this.collection.Clear();
}

// ---- Query string 
function dm_QueryString()
{
	this.base = dm_NameValueCollection;
	this.base(null, encodeURIComponent, decodeURIComponent, new Array('&', '='), false); 
	//this.collection = new dm_KeyedCollection();
	//this.init(null, encodeURIComponent, decodeURIComponent, new Array('&', '='));
}
dm_QueryString.prototype = new dm_NameValueCollection;
dm_QueryString.prototype.constructor = dm_QueryString;
dm_QueryString.prototype.CombineQueries=function(queryObj)
{
	for(var i=0, ic=queryObj.getCount(); i<ic; i++)
	{
		var name = queryObj.GetNameByIndex(i);
		var val = queryObj.GetValueByIndex(i);
		this.Delete(name);
		if (!str_IsStringEmpty(val) && name != val)
			this.Add(name, val);
	}
}

// utility functions
function dm_getDMObject(id)
{
	var obj = document.getElementById(id);
	if (obj == null)
		return null;
	if (obj.dm == null)
		return;
	return obj.dm;
}

function dm_getDMObjectValue(id)
{
	var obj = dm_getDMObject(id);
	if (obj == null)
		return;
	return obj.getStringValue();
}

function dm_setDMObjectValue(id, val)
{
	var obj = dm_getDMObject(id);
	if (obj == null)
		return;
	return obj.Load(val);
}

function do_logoff()
{
	var rc = confirm('Are you sure you want to log out?');
	if ( !rc ) 
		return;
	window.location.replace(url_AddParam(WebFrameworkConfig.LoginUrl, 'logoff', 1));
}

function do_addFolder(parentcntid)
{
	if (parentcntid == null && typeof(nav_currentNavInfo)!='undefined' && nav_currentNavInfo != null)
		parentcntid = nav_currentNavInfo.GetContainerLocation();
	nav_openPopupEx(PID_ADDFOLDER, url_MakeParam(P_PARENTCONTAINER_ID, parentcntid), 650, 460, false, false );
}

function do_insertFile()
{
	nav_openPopup(PID_INSERTIMAGEPOPUP, 380, 150, false, false );
}

function do_modifyFolder(cntid)
{
	nav_openPopupEx(PID_ADDFOLDER, url_MakeParam(P_CONTAINER_ID, cntid), 650, 480, false, false );
}

function do_ShowMessageProperties(msgid, msgType, query)
{
	if(msgType==MT_EVENT)
		return do_ViewEvent(msgid);	
	var url = url_MakeParam(P_MESSAGE_ID, msgid);
	if (query)
		url = url_CombineParams(url, query);
	nav_openPopupEx(PID_MESSAGEPROPERTIES, url, 650, 440, false, false );
}

function do_UploadFile(cntid) 
{

	if (cntid==null && nav_currentNavInfo != null)
		cntid = nav_currentNavInfo.GetContainerLocation();
	if (str_IsStringEmpty(cntid))
	{
		alert("You shoud select container before upload file(s)");
		return;
	}
	var  type = currentNavContInfo.GetParameter(ContainerItem.PN_TYPE);
	if (type != CT_FOLDER && type != CT_CHANNEL)
	{
		alert("It is not permitted to upload file(s) into this container.");
		return;
	}
	do_UploadFilesModal(cntid);
}

function do_addFeed()
{
	nav_openPopup(PID_CHFEEDTYPE, 580, 270, false, false );
}

function do_addRSSFeed()
{
	if (AuthorizationNeeded()) return; 	
	nav_openPopup(PID_ADDFEED, 580, 400, false, false );
}

function do_HTML2RSS()
{
	nav_openPopup(PID_HTML2RSS, 620, 410, true, false );
}

function do_HTML2RSSRequestToSupport()
{
	nav_openPopup(PID_HTML2RSSREQUESTTOSUPPORT, 620, 410, true, false );
}

function do_GoogleNewsToFeed()
{
	nav_openPopup(PID_GOOGLENEWSTOFEED, 620, 400, false, false );
}

function do_showCustomMetaStructuresList()
{
	return nav_openPopup(PID_CUSTOMMETASTRUCTURESLIST, 700, 440, false, false );
}

function do_ChangeSubscriptions(dsName, subscribe)
{
	if (AuthorizationNeeded()) return; 	
	
	subscribe = typeof(subscribe) != "undefined" ? subscribe : true;
	new httpcmd_ChangeSubscriptions(dsName, subscribe);
}

function do_ChangeFavorites(dsName, isFavorite)
{
	if (AuthorizationNeeded()) return; 
	
	isFavorite = typeof(isFavorite) != "undefined" ? isFavorite : true;
	new httpcmd_ChangeFavorites(dsName, isFavorite);
}

function do_addBlog()
{
	nav_openPopupEx(PID_ADDBLOG, "", 650, 420, false, false );
}

function do_modifyBlog(cntid)
{
	nav_openPopupEx(PID_ADDBLOG, url_MakeParam(P_CONTAINER_ID, cntid), 650, 460, false, false );
}

function do_addCalendar()
{
	nav_openPopup(PID_ADDCALENDAR, 650, 440, false, false );
}

function do_modifyCalendar(cntid)
{
	nav_openPopupEx(PID_ADDCALENDAR, url_MakeParam(P_CONTAINER_ID, cntid), 650, 440, false, false );
}

function do_addChannel()
{
	nav_openPopupEx(PID_ADDCHANNEL, "", 650, 440, false, false );
}

function do_modifyChannel(cntid,query)
{
	var url = url_MakeParam(P_CONTAINER_ID, cntid);
	if (query)
		url = url_CombineParams(url, query);
	nav_openPopupEx(PID_ADDCHANNEL, url, 650, 460, false, false );
}

function do_modifyRSSFeed(cntid, query)
{
	var url = url_MakeParam(P_CONTAINER_ID, cntid);
	if (query)
		url = url_CombineParams(url, query);
	nav_openPopupEx(PID_ADDRSSFEED, url, 650, 460, false, false );
}

function do_modifyMonitorNewsFeed(cntid, query)
{
	var url = url_MakeParam(P_CONTAINER_ID, cntid);
	if (query)
		url = url_CombineParams(url, query);
	nav_openPopupEx(PID_MODIFYMONITORNEWSFEED, url, 650, 440, false, false );
}


function do_modifyContainer(id, type, query)
{
	switch (type)
	{
		case CT_USERBLOG:
			do_modifyBlog(id);
			break;
		case CT_FOLDER:
			do_modifyFolder(id);
			break;
		case CT_CHANNEL:
			do_modifyChannel(id, query);
			break;
		case CT_BLOG:
			do_modifyRSSFeed(id, query);
			break;
		case CT_CALENDAR:
			do_modifyCalendar(id);
			break;
		case CT_MONITORNEWSFEED:
			do_modifyMonitorNewsFeed(id, query);
			break;
	}
}

function do_deleteContainer(id,type)
{
	if (AuthorizationNeeded()) return; 
	
	var name = "item";
	switch (type)
	{
		case CT_FOLDER:
			name = "folder";
			break;
	}
	if (!confirm("Are you sure you want to delete this "+name+"?"))
		return;
	//new httpcmd_DeleteContainer(id);
	batchOperations.StartBatchOperation( id, C_DELETE_CONTAINER );
}

function do_deletePage(id)
{
	if (AuthorizationNeeded()) return;

	if (!confirm("Are you sure you want to delete this page?"))
		return;
	batchOperations.StartBatchOperation( id, C_DELETE_PAGE );
}

function do_deleteContainerContent()
{
	if (AuthorizationNeeded()) return;
	
	var pid = nav_currentNavInfo.GetPageID();
	var cntID;
	cntID = nav_currentNavInfo.GetContainerLocation();
	if (!cntID) {
		alert("No container currently selected to delete content from.");
		return;
	}	
	if (!confirm("Are you sure you want to delete all messages?"))
		return;
	
	//new httpcmd_DeleteContainerContent(cntID);
	batchOperations.StartBatchOperation( cntID, C_DELETE_CONTAINER_CONTENT );
}

function do_deleteMessage(id, cntid, ondeleteComplete) {
	if (AuthorizationNeeded()) return false;
	
	if (!confirm("Are you sure you want to delete this item?"))
		return false;
	Utils.MonitoringHelper.SetMonitoringInfo(MA_DeleteMessage);
	new httpcmd_DeleteMessage(id, cntid, ondeleteComplete);
	return true;
}

function do_blogNewPost()
{
	if (AuthorizationNeeded()) return;

	nav_openPopup(PID_BLOGNEWPOST, 600, 415, false, false );
}

function do_blogMessage(msgid)
{
	if (AuthorizationNeeded()) return;

	nav_openPopupEx(PID_BLOGNEWPOST, url_MakeParam(P_MESSAGE_ID, msgid), 600, 415, false, false );
}

function do_SaveMessage(msgid, title)
{
	if (AuthorizationNeeded()) return;
	do_enableApplicationComponent(APP_APPLICATIONSECTIONS.Folders);
	nav_openPopupEx(PID_SAVEIT, url_CombineParams(url_MakeParam(P_MESSAGE_ID, msgid), url_MakeParam(P_TITLE, title)), 380, 280, false, false );
}

function do_CreateCustomMetaStructure()
{
	nav_openPopupModal(PID_CREATECUSTOMMETASTRUCTURE, 490, 390,  false, false, false, null, null, null );
}

function do_createMessageTags(msgid, title, type)
{
	if (AuthorizationNeeded()) return;

	nav_openPopupEx(PID_CONTENTTAGGING, url_CombineParams(url_CombineParams(url_MakeParam(P_MESSAGE_ID, msgid),url_MakeParam(P_TITLE, title)), url_MakeParam(P_TYPE, type)), 585, 500, false, false );
}

function do_viewContainerTags(cntid, title, type)
{
	nav_openPopupEx(PID_CONTENTTAGGING, url_CombineParams(url_MakeParam(P_TITLE, title),url_CombineParams(url_MakeParam(P_CONTAINER_ID, cntid), url_MakeParam(P_TYPE, type))),  585, 500, false, false );
}

function do_showCluster(clusterid, clustername, pid, urlparams)
{
	if (!clusterid || clusterid == "0") return;
	if (!clustername)
		clustername = "";
	var params = url_CombineParams(urlparams, url_MakeParam(P_CLUSTER_ID, clusterid));
	params = url_CombineParams(params, url_MakeParam(P_CLUSTER_NAME, clustername));
	if (str_IsStringEmpty(pid))
		nav_ChangePageParams(params);
	else
	{
		if (pid == PID_FOLDERS) SetShowIncludeSubFolders(true,false)
		nav_gotoPage(pid, params);
	}
}

function do_openClusterInNewWindow(clusterid, clustername, pid)
{
	var params = nav_buildUrl(pid);
	params = url_AddParameters(params, url_MakeParam(P_CLUSTER_ID ,clusterid));
	params = url_AddParameters(params, url_MakeParam(P_CLUSTER_NAME ,clustername));
	var wnd = window.open(params);
	try{wnd.opener = null;}catch(e){}
}

function do_showContainerMessagesWithRightsCheck(cntid, cnt_name, type)
{
	var callback = function (allow)
	{
		if (allow)
			do_showContainerMessages(cntid, cnt_name, type);
		else
		{
			if (IS_SNP_USER)
				do_OpenSnPTrialForm();
			else
				alert("Access is denied");
		}
	}
	new httpcmd_CheckContainerRights(cntid, callback);
}

var MANUALLYSELECTEDCONTAINERID = null;
function do_showContainerMessages(cntid, cnt_name, type)
{
	Utils.MonitoringHelper.SetMonitoringInfo(MA_ShowContainerMessages);
	if (window.opener != null)
	{	
		var hasFunction = false;
		try{ hasFunction = window.opener.do_showContainerMessages != null; } catch(e){}
		if(hasFunction)
		{
			window.opener.do_showContainerMessages(cntid, cnt_name, type);
			return;
		}
	}

	var pid = "";
	if (vld_IsGuidEmpty(cntid))
	{
		cntid = null;
		cnt_name = null;
	}
	try
	{
		pid = TPContainerToNavigationMap[type];
	}
	catch(e)
	{
		if (window.opener && window.opener.TPContainerToNavigationMap)
			pid = window.opener.TPContainerToNavigationMap[type];
	}
	if (str_IsStringEmpty(pid))
		pid = PID_FEEDS;

	if (cntid == null)
		nav_gotoPage(pid);
	else
	{
		if (typeof(srch_inpDeleteFilters)!='undefined')
		{
			var tagname = cnv_ContTypeToSrchTag(type);
			var needsearch = false;
			switch(type) 
			{
				case CT_CHANNEL:
				case CT_BLOG:
				case CT_MONITORNEWSFEED:
					needsearch = srch_inpDeleteFilters(SRCH_TN_FEEDCATEGORY);
					break;
			}
			/*if (!str_IsStringEmpty(tagname) && srch_inpDeleteFilters(tagname) == true || needsearch)
				srch_inpDoSearch(false);*/
			if (needsearch)
				srch_ResearchOnNextStep();
		}
		//added to unambiguous definition from wich container id have been added to navigation (used by advanced search)
		MANUALLYSELECTEDCONTAINERID = cntid;
		nav_gotoPage(pid, url_MakeParam(P_CONTAINER_ID, cntid));
		MANUALLYSELECTEDCONTAINERID = null;
	}
}

function do_showUserBlogAuthorMessages(userid, title)
{
	nav_gotoPage(PID_BLOGS, url_CombineParams(url_MakeParam(P_USER_ID, userid), url_MakeParam(P_LOCATION, title)));
}

function do_showLink(link)
{
	if (!str_IsStringEmpty(link)) window.open(link);	
}

function do_showDocumentWithRightsCheck(docid, mstype, link, isEmail, mode)
{
	var callback = function (allow)
	{
		if (allow)
			do_showDocument(docid, mstype, link, isEmail, mode);
		else
		{
			if (IS_SNP_USER)
				do_OpenSnPTrialForm();
			else
				alert("Access is denied");
		}
	}
	new httpcmd_CheckMessageRights(docid, callback);
}

function do_showDocument(docid, mstype, link, isEmail, mode, getURL, query)
{
	var restURL = "";
	switch(mstype) 
	{
		case MT_USERBLOGPOST:
			if (event)
				event.cancelBubble = true;
			var _url = url_MakeParam(P_MESSAGE_ID, docid);
			_url = url_CombineParams(_url, url_MakeParam(P_MODE, mode));
			restURL = url_AddParameters(nav_buildUrl(PID_BLOGS), _url);
			if (!getURL) 
			{
				if (nav_IsNavigationEnabled() && nav_currentNavInfo.GetPageID() == PID_BLOGS) {					
					nav_gotoPage(PID_BLOGS, _url);				
			}
			else 
			{
				nav_openPopupEx(PID_SHOWBLOGPOST, _url, 670, 650, true, true, false, null, null);
			}	
			}	
			break;
		case MT_EVENT:
			if (!getURL) 
			{
				do_ViewEvent(docid);
			}
			break;
		default:
			if(isEmail=='true' || isEmail==true) 
			{
				restURL = url_AddParam(nav_buildPopupUrl(PID_SHOWMESSAGE), P_MESSAGE_ID, docid);
			} 
			else 
			{
				restURL = nav_buildPopupUrl(PID_DOCUMENTVIEWER);
				restURL = url_AddParam(restURL, P_MESSAGE_ID, docid);
				restURL = url_AddParam(restURL,P_MODE, mode);
				restURL = url_AddParam(restURL, P_TYPE, mstype);
				if (query)
					restURL = url_CombineParams(restURL, query);
			}
			if (!getURL) {
				window.open(restURL);
			}
			break;
	}
	return restURL;
}

function do_getUrlForExternal(docid)
{
	var url = url_AddParam(nav_buildPopupUrl(PID_DOCUMENTVIEWER), P_MESSAGE_ID, docid);
	return encodeURIComponent(window.location.protocol+"//"+window.location.host+"/"+url);
}

function do_Delicious(docid, title, synopsis)
{
	synopsis = str_IsStringEmpty(synopsis) ? "" : synopsis;
	var url = do_getUrlForExternal(docid);
	window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+url+'&title='+encodeURIComponent(title)+'&notes='+encodeURIComponent(synopsis), 'delicious','toolbar=no,width=700,height=400'); 
}

function do_DiggIt(docid, title, synopsis)
{
	synopsis = str_IsStringEmpty(synopsis) ? "" : synopsis;
	var url = do_getUrlForExternal(docid);
	window.open('http://digg.com/submit?phase=2&amp;url='+url+'&amp;title='+encodeURIComponent(title)+'&amp;bodytext='+encodeURIComponent(synopsis));

}

function do_showContextSearchResolver(onclose, onopen)
{
	return nav_openPopupModal(PID_CONTEXTSEARCHRESOLVER, 800, 500, false, false, false, null, null, onclose, onopen);
}
function do_showCompanyLookup(command, onclose)
{
	return nav_openPopupModalEx(PID_CONTEXTSEARCHRESOLVER, url_MakeParam(P_COMMAND, command), 800, 500, false, false, false, null, null, onclose );
}
function do_UploadFilesModal(cntId) {
	nav_openPopupModalEx(PID_UPLOADFILES, url_MakeParam(P_CONTAINER_ID, cntId), 480, 320, false, false, false, null, null, null);
}

function do_InsertFilesModal(cntId, dsName) {
	nav_openPopupModalEx(PID_UPLOADFILES, url_CombineParams(url_MakeParam(P_CONTAINER_ID, cntId), url_MakeParam(P_FILEUPLOAD_DLG_TYPE, "insert")) + '&'+ url_MakeParam("dsName", dsName), 480, 260, false, false, false, null, null, null);
}

function do_EmailItModal(msgIds) {
	if(msgIds.indexOf(",")>0)
		nav_openPopupModalEx(PID_EMAILIT, url_MakeParam(P_MESSAGE_IDS, msgIds), 600, 430, false, false, false, null, null, null);
	else		
		new httpcmd_GetPreferenceValue("UseOutlook",
			function (value)
			{
				if (value.toLowerCase() != "false")
					new httpcmd_OutlookEmailIt( msgIds );
				else
					nav_openPopupModalEx(PID_EMAILIT, url_MakeParam(P_MESSAGE_IDS, msgIds), 600, 430, false, false, false, null, null, null);
			}		
		);
}

function do_BlogItModal(msgid, override) {
	if (AuthorizationNeeded()) return;

	var params = msgid ? url_MakeParam(P_MESSAGE_ID, msgid) : null;
	
	if (override)
		params = url_CombineParams(params, url_MakeParam(P_MSG_OVERRIDE, "true"))
	
	var cntId = null;
	if (typeof(nav_currentNavInfo)!='undefined' && nav_currentNavInfo != null)
		cntId = nav_currentNavInfo.GetContainerLocation();
	if (cntId) {
		params = params ? url_CombineParams(params, url_MakeParam(P_CONTAINER_ID, cntId)) : url_MakeParam(P_CONTAINER_ID, cntId);
	}
	do_enableApplicationComponent(APP_APPLICATIONSECTIONS.Blogs);
	do_enableApplicationComponent(APP_APPLICATIONSECTIONS.Blogs);
	nav_openPopupModalEx(PID_BLOGIT, params, 570, 500, true, false, false, null, null, null);
}

function do_EditBlogPost(msgid, cntid) 
{
	if (cntid)
	{
		setWindowHourGlass(true);
		new httpcmd_WhoAmI(cntid, new Function("role","do_EditBlogPostCallBack(\""+msgid+"\", role)"));
	}
	else
		do_EditBlogPostCallBack(msgid, false);
}
function do_EditBlogPostCallBack(msgid, role)
{
	if (role != false)
	{
		setWindowHourGlass(false);
		if (str_IsStringEmpty(role) || role.toLowerCase() == "reader")
		{
			alert("You have no rights to perform this operation");
			return;
		}
	}
	do_BlogItModal(msgid, true);
}

function do_setEntitlements(cntid)
{	
	nav_openPopupModalEx(PID_SETENTITLEMENTS, url_MakeParam(P_CONTAINER_ID, cntid), 400, 150, false, false, false, null, null, null);
}
function do_editSearch(srchId)
{
	srch_EditSearch(srchId);
}
function do_deleteSearch(srchId, callback)
{
	if (AuthorizationNeeded()) return false;

	if (!confirm("Are you sure you want to delete this item?"))
		return false;
	Utils.MonitoringHelper.SetMonitoringInfo(MA_DeleteSearch);
	new httpcmd_DeleteSearch(srchId, callback);
	return true;
}
function do_newSearch(pid)
{
	if (!srch_advClear())
		return;
	nav_NavigateTo(pid,null,PID_PLADVANCEDSEARCH);
	return false;
}

function do_is_message_exist(titleId,dsName) 
{
	var titleObj = document.getElementById( titleId );
	var title = titleObj!= null ? titleObj.value :"";
	title = str_Trim( title );
	if ( title.length == 0 )
	{
		alert("Please provide title.")
		return;
	}
	setWindowHourGlass();
	var containers = new Array();
	var ds = data_GetDataset(dsName);
	if ( !ds.HasSelection() )
	{
		setWindowHourGlass(false);
		alert( "Please select folder to save.");
		return;
	}
	var selcol = ds.GetSelectedItemsCopy();
	for(var i=0; i< selcol.GetCount(); i++)
		containers.push(selcol.GetByIndex(i).GetItemID());
	new httpcmd_IsMessageExist(title, containers[0], do_need_overwrite, titleObj);
}

function do_need_overwrite( obj, txt )
{
	if ( typeof(txt) != "undefined" && txt != null && txt.length > 0 )
	{
		setWindowHourGlass( false );
		if(!confirm('Item with such subject already exists. Do you want to overwrite it?'))
		{
			obj.focus();
			return;
		}
		setWindowHourGlass();
		document.forms[0].overwrite.value = txt;
	}
	document.forms[0].submit();
}

function do_removePrincipal(dsName, id)
{
	var ds = data_GetDataset(dsName);
	// the commented lines should be deleted after the build 2.0.31.0 will be released
	//var creatorguid = typeof(ContainerCreatorGuid) != "undefined" ? ContainerCreatorGuid : null; 
	if (ds) 
	{
		var xItem = ds.Get(id);
		if (xItem) 
		{
			//if (creatorguid != id) deleted 
				data_DeleteDSItem(dsName, xItem);
			//else
			//alert("You can't delete containers creator."); 
		}
	}
}
function do_removeMetaValueLink(dsName, id)
{
	var ds = data_GetDataset(dsName);
	if (ds) 
	{
		if( ds.GetCount() == 1 ) return;
		var xItem = ds.Get(id);
		if (xItem) data_DeleteDSItem(dsName, xItem);
	}
}

function do_removeTrustedLink(dsName, id)
{
	var ds = data_GetDataset(dsName);
	if (ds) 
	{
		var xItem = ds.Get(id);
		if (xItem) data_DeleteDSItem(dsName, xItem);
	}
}

function do_removeSingleTrustedEmail(dsName, id)
{
	TrustedDatasetChanged(dsName,id,true);
}

function do_removeCustomMetaStructureLink(dsName, id)
{
	var ds = data_GetDataset(dsName);
	if (ds) 
	{
		var xItem = ds.Get(id);
		if (xItem) data_DeleteDSItem(dsName, xItem);
	}
}
function do_editCustomMetaStructureLink(dsName, id, type)
{
	var pid = null;
	var addParamName = null;
	switch( type )
	{
		case "0":
			pid = PID_CMSCHECKBOX;
			break;
		case "1":
			pid = PID_CMSLISTBOX;
			break;
		case "2":
			pid = PID_CMSCOMBOBOX;
			break;
		case "3":
			pid = PID_CMSNUMBERBOX;
			break;
		case "4":
			pid = PID_CMSTEXTBOX;
			break;
		case "5":
			pid = PID_CMSTEXTBOX;
			break;
		case "6":
			pid = PID_CMSTREE;
			break;
	}
	
	if( pid != null )
		return nav_openPopupModalEx(pid, url_MakeParam(P_CMS_ID, id), 580, 460, false, true );
}

function do_showPrincipalProperties(id, type)
{
	if ( type == "User")
		do_ShowUserProperties(id);
	else
		alert("Not implemented");
}

function do_showUserGroupFinder(onclose, onopen, findmode, managable, showself, company)
{
	var params = url_CombineParams(url_MakeParam(P_FINDMODE, findmode),url_MakeParam(P_FIND_MANAGEABLE, managable));
	params = url_CombineParams(params,url_MakeParam(P_FIND_SHOW_SELF, showself));
	params = url_CombineParams(params,url_MakeParam(P_COMPANY_NAME, company));
	
	return nav_openPopupModalEx(PID_USERGROUPFINDER, params, 580, 420, false, false, false, null, null, onclose, onopen );
}

function do_showSharedProperies(cntid, cnttype, cntname, creatorid, title)
{
	var url = url_CombineParams(url_MakeParam(P_CONTAINER_ID, cntid),url_MakeParam(P_TYPE, cnttype));
	url = url_CombineParams(url,url_MakeParam(P_LOCATION, cntname));
	url = url_CombineParams(url,url_MakeParam(P_USER_ID, creatorid));
	if (title)
		url = url_CombineParams(url,url_MakeParam(P_TITLE, title));
	nav_openPopupEx(PID_SHAREDPROPERTIES, url, 650, 440, false, false );
}
function do_removeSecurityPrincipal(dsName, principalID, principalType, isSystem )
{
	if ( isSystem == "true" )
	{
		alert( "You can't remove your own company." );
		return;
	}
	if(confirm('Are you sure you want to delete this item?'))
		new httpcmd_RemoveSecurityPrincipal( dsName, principalID, principalType, do_removeSecurityPrincipal_callback);
}
function do_removeSecurityPrincipal_callback(dsName, id, ptype)
{	
	var ds = data_GetDataset(dsName);
	if (ds) 
	{
		var xItem = ds.Get(id);
		if (xItem) data_DeleteDSItem(dsName, xItem);
	}
	
	if(ptype == 'Company')
		nav_RefreshWorkspaceModules(KEY_USERS);	
	do_CheckRightOnThisLocation(PID_MYACCOUNT);
}
function do_removeTeamUser(dsName, teamId, userId)
{
	if(confirm('Are you sure you want to remove this user from team?'))
		new httpcmd_RemoveTeamUser( dsName, teamId, userId, do_removeTeamUser_callback);
}
function do_removeTeamUser_callback(dsName, id)
{	
	var ds = data_GetDataset(dsName);
	if (ds) 
	{
		var xItem = ds.Get(id);
		if (xItem) data_DeleteDSItem(dsName, xItem);
	}
	do_CheckRightOnThisLocation(PID_MYACCOUNT);
}

function do_CommentMessage(docid, mstype, mode)
{
	do_showDocument(docid, MT_USERBLOGPOST, null, null, mode);
}
function do_CompleteMessage(docid)
{
	do_showDocument(docid, MT_USERBLOGPOST);
}

function do_openHome()
{
	nav_NavigateTo(PID_HOME, null, null);
}

function do_openMyAccount(ploc)
{
	nav_NavigateTo(PID_MYACCOUNT, null, ploc);
}

function do_editSPrincipal(id, type, name, run_usr_setup, compname, compid)
{
	var _url = url_MakeParam(P_PRINCIPAL_ID, id);
	_url = url_CombineParams(_url, url_MakeParam(P_PRINCIPAL_TYPE, type));
	_url = url_CombineParams(_url, url_MakeParam(P_PRINCIPAL_NAME, name));
	
	if (!vld_IsGuidEmpty(compid) && !str_IsStringEmpty(compname))
	{
		_url = url_CombineParams(_url, url_MakeParam(P_COMPANY_ID, compid));	
		_url = url_CombineParams(_url, url_MakeParam(P_COMPANY_NAME, compname));	
	}
	if (type == "User" && nav_currentNavInfo != null 
		&& nav_currentNavInfo.GetParameter(P_PRINCIPAL_TYPE) == "Team"
		&& nav_currentNavInfo.GetParameter(P_PRINCIPAL_ID) != null 
		&& !str_IsStringEmpty(nav_currentNavInfo.GetParameter(P_PRINCIPAL_NAME)) )
	{
		_url = url_CombineParams(_url, url_MakeParam(P_TEAM_ID, nav_currentNavInfo.GetParameter(P_PRINCIPAL_ID)));	
		_url = url_CombineParams(_url, url_MakeParam(P_TEAM_NAME, nav_currentNavInfo.GetParameter(P_PRINCIPAL_NAME)));
	}
	
	var trg = (type=="CrossTeam")?PID_PLMYACCOUNTPREFERENCESMYMEMBERGROUPS:PID_PLMYACCOUNTADMINMEMBERS;
		
	nav_NavigateTo(PID_MYACCOUNT, _url, trg);
}

function do_editTeamMembers(principalId, principalName, teamType)
{
	var params = url_MakeParam(P_ADMIN_EDIT_MODE,'teammembers');
	params = url_CombineParams(params, url_MakeParam(P_PRINCIPAL_ID,principalId));
	params = url_CombineParams(params, url_MakeParam(P_PRINCIPAL_TYPE, teamType));
	params = url_CombineParams(params, url_MakeParam(P_PRINCIPAL_NAME, principalName));
	nav_ChangePagePersistantParams(params);
}

function do_NewCompany()
{
	nav_NavigateTo(PID_MYACCOUNT, url_MakeParam(P_PRINCIPAL_TYPE, "Company"), PID_PLMYACCOUNTADMINMEMBERS);
}
function do_NewTeam()
{
	nav_NavigateTo(PID_MYACCOUNT, url_MakeParam(P_PRINCIPAL_TYPE, "Team"), PID_PLMYACCOUNTADMINMEMBERS);
}
function do_NewUser( companyId, companyName, teamId, teamName )
{
	var params = url_MakeParam(P_PRINCIPAL_TYPE, "User");
	if ( companyId )
		params = url_CombineParams( params, url_MakeParam(P_COMPANY_ID, companyId) );
	if ( !str_IsStringEmpty(companyName) )
		params = url_CombineParams( params, url_MakeParam(P_COMPANY_NAME, companyName) );
	if ( !str_IsStringEmpty(teamId) )
		params = url_CombineParams( params, url_MakeParam(P_TEAM_ID, teamId) );
	if ( !str_IsStringEmpty(teamName) )
		params = url_CombineParams( params, url_MakeParam(P_TEAM_NAME, teamName) );
	
	nav_NavigateTo(PID_MYACCOUNT, params, PID_PLMYACCOUNTADMINMEMBERS);
}
function do_NewCrossTeam()
{
	nav_NavigateTo(PID_MYACCOUNT, url_MakeParam(P_PRINCIPAL_TYPE, "CrossTeam"), PID_PLMYACCOUNTPREFERENCESMYMEMBERGROUPS);
}

function do_showAlertDetails(alertId, containerId, searchId, sourceType, getterFn, setterFn)
{
	var url;
	if(!str_IsStringEmpty(alertId))
		url = url_CombineParams(url,url_MakeParam(P_ALERT_ID, alertId));
	if(!str_IsStringEmpty(containerId))
		url = url_CombineParams(url,url_MakeParam(P_CONTAINER_ID, containerId));
	if(!str_IsStringEmpty(searchId))
		url = url_CombineParams(url,url_MakeParam(P_SEARCH_ID, searchId));
	if(!str_IsStringEmpty(sourceType))
		url = url_CombineParams(url,url_MakeParam(P_ALERT_SOURCE_TYPE, sourceType));
	if(!str_IsStringEmpty(getterFn))
		url = url_CombineParams(url,url_MakeParam(P_GETTER_FUNCTION, getterFn));
	if(!str_IsStringEmpty(setterFn))
		url = url_CombineParams(url,url_MakeParam(P_SETTER_FUNCTION, setterFn));
		
	nav_openPopupEx(PID_ALERTDETAILS, url, 400, 200, false, false );
}

function do_deleteAlertSubscription(alertId)
{
	if(confirm('Are you sure you want to delete this item?'))
		new httpcmd_DeleteAlert( alertId );
}

function do_changeAlertEmails(oldEmail, newEmail, onclose)
{	
	return nav_openPopupModalEx(PID_ALERTNEWADDRESS, url_MakeParam(P_EMAILS, oldEmail+","+newEmail), 500, 350, false, false, false, null, null, onclose);
}

function do_CreateCMS()
{
	return nav_openPopup(PID_CUSTOMMETASTRUCTURESELECT, 635, 300, false, false);
}
function do_NewEvent()
{
	var sdate = nav_currentNavInfo.GetParameter(P_NAVCALENDAR_DATE);
	nav_openPopupEx(PID_NEWEVENT, url_MakeParam(P_NAVCALENDAR_DATE, sdate), 650, 670, true, false );
}
function do_ViewEvent(msgid)
{	
	var _url = url_MakeParam(P_MESSAGE_ID, msgid);
	var width = 650, height = 500;
	nav_openPopupEx(PID_NEWEVENT, _url, width, height, true, false );
}
function do_ExportEvent(msgid)
{
	var _url = nav_buildPopupUrl(PID_ITEMSEXPORT);
	_url = url_AddParam(_url, P_EXPORT_TYPE, '1'); // event
	_url = url_AddParam(_url, P_MESSAGE_ID, msgid);
	window.open(_url);
}
function do_ExportContainerContact(email_prefix)
{
	var _url = nav_buildPopupUrl(PID_ITEMSEXPORT);
	_url = url_AddParam(_url, P_EXPORT_TYPE, '2'); // container
	_url = url_AddParam(_url, P_EMAIL, email_prefix);
	window.open(_url);
}
function do_ShowUserProperties(id)
{
	nav_openPopupEx(PID_USERPROPERTIES, url_MakeParam(P_PRINCIPAL_ID, id), 500, 400, false, false );
}

function do_inpDoSearchByFilter(name, value, dispvalue, needclear, changenav)
{
	if (typeof(this.srch_inpDoSearchByFilter) != "undefined")
		srch_inpDoSearchByFilter(name, value, dispvalue, needclear, changenav);
	else if (window.opener && typeof(window.opener.srch_inpDoSearchByFilter) != "undefined")
		window.opener.srch_inpDoSearchByFilter(name, value, dispvalue, needclear, changenav);
}
function do_InitEnvironment(brandName, userRef, first, last, email, login, close_script )
{
	var _url = url_MakeParam(P_BRAND_NAME, brandName);
	_url = url_CombineParams(_url, url_MakeParam(P_USER_ID, userRef) );
	_url = url_CombineParams(_url, url_MakeParam(P_FIRST_NAME, first) );
	_url = url_CombineParams(_url, url_MakeParam(P_LAST_NAME, last) );
	_url = url_CombineParams(_url, url_MakeParam(P_EMAILS, email) );
	_url = url_CombineParams(_url, url_MakeParam(P_USER_LOGIN, login) );
	
	return nav_openPopupModalEx(PID_MYACCOUNTINITENVIRONMENT, _url, 320, 240, false, false, false, null, null, new Function(close_script) );
}
function do_reAuth( ticket )
{
	new httpcmd_ReAuthenticate( ticket );
}
var Data_ObjDivToPrint = null;
function do_PrintPreview(strId){
	if (strId == null) return false;
	if (typeof(strId)=="string"){
		Data_ObjDivToPrint = document.getElementById(strId);
		window.open('print_report.aspx',null,'target=_blank,status=0,toolbar=0,scrollbars=1,menubar=1,resizable=yes');
	}
}
function PrintPrewClear(){
	Data_ObjDivToPrint="empty";
	delete Data_ObjDivToPrint;
}

function do_OpenNewslettersMenu(obj){
	if(obj && obj.tagName && obj.tagName.toUpperCase()=="SPAN")
	{
		var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();		
		if(isHeadlinesView)
		{
			var parentTable = findParentTag(obj, "TABLE");		
			if(!parentTable)
				return;			
			if(parentTable.nextSibling && parentTable.nextSibling.tagName.toUpperCase()=="TABLE")
				parentTable.nextSibling.style.display = (parentTable.nextSibling.style.display=="none" || parentTable.nextSibling.style.display=="") ? "block" : "none";		
		}
		else
		{
			var parentTR = findParentTag(obj, "TR");		
			if(!parentTR)
				return;			
			var child = parentTR.nextSibling.firstChild.firstChild;
			if(child.tagName.toUpperCase()=="SPAN")
				child.style.display = (child.style.display=="none" || child.style.display=="") ? "block" : "none";
		}
	}
}

function findParentTag(startElem, tagName)
{
	if(startElem.tagName
		&& startElem.tagName.toUpperCase()==tagName.toUpperCase())
		return startElem;
	else if(startElem.parentNode)
		return findParentTag(startElem.parentNode, tagName);
		
	return null;
}

function ShowStatusWindow(text, keywords, jsNames, parent)
{
	if (parent == null) parent = window;
		
	var wnd = parent.nav_openWinModalEx('', 'Status', 250, 100, false, false);
	
	var contentString = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' /><title>Status</title>"+
	"<link	href=\"" + cmd_getCssFileName("iiglobal.css")+"\" rel=\"stylesheet\" type=\"text/css\" />";
	
	if (jsNames != null)
		for(var i=0; i<jsNames.length; i++)
			contentString+="<script src=\"" + jsNames[i] +"\" language='javascript'></script>";
			
	if (keywords != null)	
		contentString +=  "<script>window.setTimeout('window.close()',"+TouchPointConfig.SplashScreenDelay+");window.onunload = function (){if (!window.opener.closed) window.opener.evnt_FireEvent(EVT_REFRESH_MODULES,'"+keywords+"');}</script>";
		
		//contentString +=  "<script>\r\nfunction winClose(){\r\nif (!window.opener.closed) window.opener.evnt_FireEvent(EVT_REFRESH_MODULES,'"+keywords+"');\r\nwindow.close();\r\n}\r\nwindow.setTimeout('winClose()',"+TouchPointConfig.SplashScreenDelay+"); </script>";
	
	contentString += "</head><body>"+	
	"<div class='pop00' style='padding-left:10;margin-left:110;padding-top:5;height:25;'>Status</div><div align='center' style='padding-top:20;'>"+	
	"<img src='" + WebFrameworkConfig.ImagesPath + "/icon_indicator.gif' height='16' width='16' /><br><br>"+ text + 
	"</div></body></html>";
		
	if( wnd != null )
	{
		wnd.document.open();
		wnd.document.write(contentString);
		wnd.document.close();
		wnd.focus();
	}
	
	return wnd;
}

function ShowSplashScreen(keywords, onTop)
{
	if (window.opener != null)
		window.opener.Utils.MonitoringHelper.SetMonitoringInfo(MA_Refresh);
	else	
		Utils.MonitoringHelper.SetMonitoringInfo(MA_Refresh);
		
	if(TouchPointConfig.SplashScreenDelay<=0){
		nav_RefreshWorkspaceModules(keywords);
		return;
	}
	var wnd = window;
	if(onTop==true){		
		if(!wnd_IsWindowClosed(window.TopWindow))
			wnd = window.TopWindow;
		else{
			if(window.TopWindow==null){
				evnt_SubscribeOnEvent("ShowSplashScreen", ShowSplashScreen);
				evnt_FireEvent("ShowSplashScreen", keywords, onTop);
			}
			return;
		}
	}
	
	var jsNames = cmd_getJSFileNamesWithoutDublicats("Runtime/tpvars.js","Runtime/fwk.js","Runtime/dm.js","Runtime/Common.js","Runtime/cmn.js","Runtime/EventManager.js");
	
	return ShowStatusWindow("The system is processing your request.", keywords, jsNames, wnd);
}

// Display login window and close popups (if any)
function do_LogIn(windowsToClose) {
	if (windowsToClose) {
		windowsToClose.map(function(item) { item.close(); });
	}
	GlobalSoftWindow = new PopupWindow("InfoNgen Authorization", 800, 500);
	GlobalSoftWindow.NavigateURL(WebFrameworkConfig.RootUrl  + "login.aspx?cl=rd");
	GlobalSoftWindow.Show(true);
	return true;
}

function do_LogOut(reload)
{
	if (!confirm("Are you sure you want to log out?")) return;
	tpl_DropLoginCookie();
	if(reload)
		window.location.reload();
	else
		window.location.replace(WebFrameworkConfig.DefaultPageUrl);
}

function do_SetupCategories() {
	GlobalSoftWindow = new PopupWindow("InfoNgen Personalization", 800, 500, null, null, false, false);
	GlobalSoftWindow.NavigateURL(WebFrameworkConfig.RootUrl  + "Modules/MyAccount/EnvironmentInfo/UserCategoriesSetup.aspx");
	GlobalSoftWindow.Show(true);
	return true;
}

function do_SetupLanguages() {
	GlobalSoftWindow = new PopupWindow("InfoNgen Personalization", 800, 500, null, null, false, false);
	GlobalSoftWindow.NavigateURL(WebFrameworkConfig.RootUrl  + "Modules/MyAccount/EnvironmentInfo/UserLanguagesSetup.aspx");
	GlobalSoftWindow.Show(true);
	return true;
}

function AuthorizationNeeded() {
	if (IS_ANONYMOUS_USER) {
		// enumerate popup's chain to close them later
		var currentWindow  = window;
		var windows = [];
		
		while (currentWindow.opener && !currentWindow.opener.closed) {
			windows.push(currentWindow);
			currentWindow = currentWindow.opener;
		}				
		currentWindow.setTimeout(currentWindow.do_LogIn.bind(currentWindow, windows), 0);
		return true;		
	}
	return false;
}

function do_Browse()
{
	var pid = nav_currentNavInfo.GetPageID();
	var ploc = null;
	var params = null;
	switch(pid)
	{
		case PID_FEEDS:	
			ploc = PID_PLMANAGEFEEDS; 
			break;
		case PID_FOLDERS:	ploc = PID_PLMANAGEFOLDERS; break;
		case PID_BLOGS:		ploc = PID_PLMANAGEBLOGS; break;
		case PID_CALENDARS:	ploc = PID_PLMANAGECALENDARS; break;
		default: 
			pid = PID_FEEDS;
			ploc = PID_PLMANAGEFEEDS;
			break;
	}	
	nav_NavigateTo(pid,params,ploc);
}
function do_ManagePortfolio(){ do_openMyAccount(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS); return false; }
function do_ManageNewsletters()
{ 
	window.flg_SetNewslettersOnLoad = true;
	var callback = function (xml)
	{
		var query = null;
		if (xml!=null)
		{	
			var objID  = null;
			var ndAccessor =  new Xml.NodeAccessor(xml);			
			if(ndAccessor.SelectSingleNode("//"+P_NEWSLETTERS_ID+"[1]")!=null)
				objID  = ndAccessor.SelectSingleNode("//"+P_NEWSLETTERS_ID+"[1]").text;

			if(objID !=null && parseInt(objID) >0 )
			{
				query = url_CombineParams(
					url_CombineParams(
						url_MakeParam(P_MODE, "edit"), 
						url_MakeParam(P_BEDATA_REFERENCE, objID)
					)
				);
				
				if(NewslettersModuleControl!=null)
				{
					NewslettersModuleControl.LoadItemDS(objID);
					// set selected newsletter name in grid
					try{ data_MarkItemSelected("NewslettersDS", objID, true,true,false,false,event);} catch(e) {}
				}
			}
		}
		nav_NavigateTo(PID_MYACCOUNT, query, PID_PLMYACCOUNTPREFERENCESMYNEWSLETTERS);		
	}	
	new httpcmd_NewslettersFirstGet(callback, null);	
	return false; 
}

function do_NewPortfolio()
{  
	flg_CreateNewPortfolioOnLoad = true;
	do_openMyAccount(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS); 
	return false; 
}
function do_ManageSearches() { nav_NavigateTo(PID_MANAGESEARCHES); return false; }

var GlobalSoftWindow = null;
function CloseGlobalSoftWindow()
{	
	if (window.TopWindow.GlobalSoftWindow)
		setTimeout(function(){window.TopWindow.GlobalSoftWindow.Hide(true)},1);
}
function ClosePopupArea()
{
	if(typeof(UI)!='undefined' && typeof(UI.Popuparea)!='undefined')
		UI.Popuparea.__closeAllPopups();
}
function CloseGlobalSoftWindow2()
{
	if(window.EventManager!=null && window.EventManager.EventsCount()>0 && closeCount++<20)
		window.setTimeout(CloseGlobalSoftWindow2, 50);
	else
		if (window.top.GlobalSoftWindow != null)
			setTimeout(function(){window.top.GlobalSoftWindow.Hide(true)},1);
}
function GlobalSoftWindowNavigateTo(url)
{
	if (window.TopWindow.GlobalSoftWindow)
		setTimeout(function(){window.TopWindow.GlobalSoftWindow.NavigateURL(url)},1);
}

function do_ShowSnpHeadlines()
{
	nav_NavigateTo(PID_FEEDS, url_MakeParam(P_BRANDFILTER, BRANDNAME_SNP));
}

function do_OpenSnPTrialForm()
{
	var url = "Html/SnP/trialform.html";
	url = url_AddParam(url, "sendto", BrandsConfig.SnPTrialFormEmail);
	window.open(url);				
}
function do_CheckRightOnThisLocation(redirectTo)
{
	if (!window.TopWindow.nav_IsNavigationEnabled()) return;
	var pageLoc = window.TopWindow.nav_currentNavInfo.GetPageLocation();
	
	var callback = function(hasRights)
	{
		if (!hasRights)
		{
			if (redirectTo != null)
				window.TopWindow.nav_NavigateTo(redirectTo);
			window.TopWindow.location.reload();	
		}
	}
	new httpcmd_CheckPageRights(pageLoc, callback);
}

function do_updateLayout(wideLayout) {
	TouchPointSettings.setWideLayout(wideLayout.toString());
	var container = $("contentContainer");
	if (container) {
		container.className = wideLayout ? 'wideLayout' : 'defaultLayout';
	}
}

// Data command
// ---------------
function data_GetSelectedMessage()
{
	return data_GetSelectedItem("Messages");
}

function data_GetSelectedMessages()
{
	return data_GetSelectedItems("Messages");
}

function data_GetSelectedMessagesForEmailing()
{
	return data_GetSelectedItemsForEmailing();
}

function data_GetSelectedContainer()
{
	return data_GetSelectedItem("Containers");
}

function data_doEditBlogPost()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item to edit.");
		return;
	}
	do_EditBlogPost(xItem.GetNodeValue(MessageItem.PN_ID), xItem.GetNodeValue(MessageItem.PN_CONTAINERID));
}

function data_doBlogMessage()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item to blog.");
		return;
	}
	do_BlogItModal(xItem.GetNodeValue(MessageItem.PN_ID));
}
function data_doTagMessage()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		data_doTagContainer();
		return;
	}
	do_createMessageTags(xItem.GetNodeValue(MessageItem.PN_ID),  xItem.GetNodeValue(MessageItem.PN_TITLE), xItem.GetNodeValue(MessageItem.PN_TYPE));
}

function data_doSaveMessage()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item to save.");
		return;
	}
	do_SaveMessage(xItem.GetNodeValue(MessageItem.PN_ID), xItem.GetNodeValue(MessageItem.PN_TITLE));
}

function data_doExportIt()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item to export.");
		return;
	}
	do_ExportEvent(xItem.GetNodeValue(MessageItem.PN_ID));
}

function data_doEmailIt()
{
	Utils.MonitoringHelper.SetMonitoringInfo(MA_EmailIt);
	var coll = data_GetSelectedMessagesForEmailing();
	if (coll == null || coll.getCount()<=0)
	{
		alert("Please select item(s) to e-mail.");
		return;
	}
	var ids = "";
	for(var c1 = 0; c1<coll.getCount(); c1++)
	{
		var id = coll.GetByIndex(c1).GetNodeValue(MessageItem.PN_ID);
		if(c1>0)
			ids+=","+id;
		else
			ids = id;
	}
	do_EmailItModal(ids);
}

function data_doDelicious()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item.");
		return;
	}	
	do_Delicious(xItem.GetItemID(), 
			  xItem.GetNodeValue(MessageItem.PN_TITLE),
			  xItem.GetNodeValue(MessageItem.PN_SYNOPSIS));
}

function data_doDiggIt()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		alert("Please select item.");
		return;
	}	
	do_DiggIt(xItem.GetItemID(), 
			  xItem.GetNodeValue(MessageItem.PN_TITLE),
			  xItem.GetNodeValue(MessageItem.PN_SYNOPSIS));
}

function data_doTagContainer()
{
	if (AuthorizationNeeded()) return;
	
	var xItem = data_GetSelectedContainer();
	if (xItem == null)
	{
		alert("Please select item to tag.");
		return;
	}
	do_viewContainerTags(xItem.GetNodeValue(ContainerItem.PN_ID), xItem.GetNodeValue(ContainerItem.PN_TITLE), xItem.GetNodeValue(ContainerItem.PN_TYPE));
}

function data_doDeleteMessage()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		data_doDeleteContainer();
		return;
	}
	var id = xItem.GetItemID();
	do_deleteMessage(id, xItem.GetNodeValue(MessageItem.PN_CONTAINERID), _data_doDeleteMessage_complete.bind(this, id, xItem.GetNodeValue(MessageItem.PN_TYPE)));

}

function data_doDeleteMessageNewsletters()
{
	// 1. Confirm message
	var nSelectedCount = data_DataStoreCollection!=null ? data_DataStoreCollection.GetSelectedCountForEmailing() : 1;		
	var text = nSelectedCount > 1 ? "items":"item";
	if (!confirm("Are you sure you want to delete this " + text + " ?"))
			return false;
		
	// 2. Collect data
	var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();
	var dsName = isHeadlinesView ? "Subscriptions.Latest" : "Subscriptions.LatestS";	
	var arr = [];
	var selItems = data_DataStoreCollection.GetSelectedItemsForEmailing();
	if(selItems && selItems.getCount() > 0)
		for(var i=0; i<selItems.getCount(); i++)
		{
			var clasterId = selItems.GetByIndex(i).GetNodeValue(MessageItem.PN_CLUSTERID);
			var msgId = selItems.GetByIndex(i).GetNodeValue(MessageItem.PN_ID);
			if(msgId!=null && msgId>0)
				data_DeleteDSItemByID(dsName, msgId);
			
			if(clasterId!=null && clasterId>0)			
				arr.push(clasterId);
			else if(msgId!=null && msgId>0)
				arr.push(msgId);
		}
		
	Utils.MonitoringHelper.SetMonitoringInfo(MA_DeleteMessageNewsletters);
	var searchId = nav_currentNavInfo.GetParameter(P_NEWSLETTERS_SELECTED_SEARCH);
	var newsletterId = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
	if(searchId && newsletterId)
		new httpcmd_NewslettersDelHeadlines({"MsgId":arr, "NewsletterId":newsletterId, "SearchId":searchId}, data_doDeleteMessageNewslettersComplete);
	return true;
}

function data_doDeleteMessageNewslettersComplete(xml, arrId)
{
	data_DataStoreCollection.ClearSelectedItemsForEmailing();
}

function data_doUpdateCommentMessageNewsletters(comment)
{
	// 1. Collect data
	var nsId = null;
	var msgId = null;
	var ssId = null;
	var selItems = data_DataStoreCollection.GetSelectedItemsForEmailing();
	if(selItems && selItems.getCount() > 0)
	{
		var lastItem = selItems.GetByIndex(0);		
		msgId = lastItem.GetNodeValue(MessageItem.PN_ID);
		nsId = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
		ssId = nav_currentNavInfo.GetParameter(P_NEWSLETTERS_SELECTED_SEARCH);

		var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();	
		var dsName = isHeadlinesView ? "Subscriptions.Latest" : "Subscriptions.LatestS";
		var ds = data_GetDataset(dsName);
			if(ds!=null)
				ds.Get(msgId).SetNodeValue(MessageItem.PN_IS_COMMENT_PRESENT, (comment!=null && comment.length>0) ? "true" : false);
	}		
	if(nsId && ssId && msgId)
		new httpcmd_NewslettersHeadlineCommentUpdate(nsId, ssId, msgId, comment, null, null)
	return true;
}

function _data_doDeleteMessage_complete(msgid, type)
{
	switch (type)
	{
		case MT_USERBLOGPOST:
			if(nav_IsNavigationEnabled()){
				if(nav_currentNavInfo.GetParameter(P_MESSAGE_ID))
					nav_ChangePageParams(P_MESSAGE_ID, true);
			}
			else
				window.close();
			break;
	}
}

function data_doDeleteContainer()
{
	var xItem = data_GetSelectedContainer();
	if (xItem == null)
	{
		alert("Please select item to delete.");
		return;
	}
	do_deleteContainer(xItem.GetItemID(),xItem.GetNodeValue(ContainerItem.PN_TYPE));
}

function data_doShowMessageProperties()
{
	var xItem = data_GetSelectedMessage();
	if (xItem == null)
	{
		data_doShowContainerProperties();
		return;
	}
		
	do_ShowMessageProperties(xItem.GetItemID(), xItem.GetNodeValue(MessageItem.PN_TYPE));
}

function data_doShowContainerProperties(query)
{
	var xItem = data_GetSelectedContainer();
	if (xItem == null)
	{
		alert("Please select item to view.");
		return;
	}
	do_modifyContainer(xItem.GetItemID(),xItem.GetNodeValue(ContainerItem.PN_TYPE), query);
}
function data_doChangeContainerFavorite()
{
	var xItem = data_GetSelectedContainer();
	if (xItem == null)
	{
		alert("Please select item to view.");
		return;
	}
	var command = new httpcmd_ChangeFavorite(xItem.GetItemID(), xItem.GetNodeValue(ContainerItem.PN_ISFAVORITE) == "false");
	return (command instanceof httpcmd_ChangeFavorite);
}
function data_doChangeContainerSubscription()
{
	var xItem = data_GetSelectedContainer();
	if (xItem == null)
	{
		alert("Please select item to view.");
		return;
	}
	var command = new httpcmd_ChangeSubscription(xItem.GetItemID(), xItem.GetNodeValue(ContainerItem.PN_ISSUBSCRIBED) == "false");
	return (command instanceof httpcmd_ChangeSubscription);
}

function do_openScrollableAlerts(setPositionAndSize)
{
	var wsa_value = setPositionAndSize && tpl_GetCookie("wsa_preferences") || "";
	wsa_value = wsa_value&&wsa_value.split(",") || [];
	var width = Math.max(wsa_value[2]||(IS_TMC_USER?1000:835), 100);
	var height = Math.max(wsa_value[3]||500, 100);
	var top = wsa_value[1]==null?(window.screen.availHeight-height)/2:wsa_value[1];
	var left = wsa_value[0]==null?(window.screen.availWidth-width)/2:wsa_value[0];
	var wnd = nav_openPopupEx(PID_SCROLLABLEALERTS, null, width, height, true, true, null, left, top);
	try{
		wnd.__browserTopDx = wnd.screenTop - wsa_value[1];
		wnd.__browserleftDx = wnd.screenLeft - wsa_value[0];
	}catch(e){}
}
function do_enableApplicationComponent(component){
	if ((APPLICATIONCOMPONENTS & component) != component)
	{
		if(component == APP_APPLICATIONSECTIONS.Trends && !GeneralPreferences.IsTrendsEnableBySuperAdmin)
			return false;
		APPLICATIONCOMPONENTS = APPLICATIONCOMPONENTS | component;
		evnt_FireEvent(EVT_APPLICATION_COMPONENTS_UPDATED, APPLICATIONCOMPONENTS);
		new httpcmd_SetPreferenceValue("ApplicaionComponents", APPLICATIONCOMPONENTS);
	}
	return true;
}
function do_InitEnvironment(brandName, userRef, first, last, email, login, close_script )
{
	var _url = url_MakeParam(P_BRAND_NAME, brandName);
	_url = url_CombineParams(_url, url_MakeParam(P_USER_ID, userRef) );
	_url = url_CombineParams(_url, url_MakeParam(P_FIRST_NAME, first) );
	_url = url_CombineParams(_url, url_MakeParam(P_LAST_NAME, last) );
	_url = url_CombineParams(_url, url_MakeParam(P_EMAILS, email) );
	_url = url_CombineParams(_url, url_MakeParam(P_USER_LOGIN, login) );
	
	return nav_openPopupModalEx(PID_MYACCOUNTINITENVIRONMENT, _url, 320, 240, false, false, false, null, null, new Function(close_script) );
}

function data_ClearPagingCookie()
{
	tpl_SetCookie(P_NEWSLETTERS_ARCHIVE_GRID_PAGE, 1, true);
}
var DE_STATUS_LOADING = "loading";
var DE_STATUS_COMPLETE = "complete";
var DE_STATUS_ERROR = "error";

var StatusCode = { OK: "OK", ERROR: "ERROR"};


function dynamicStatusInfo(status, statusText)
{
	this.status = status;
	this.statusText = statusText;
}

function de_attachDynamicElement(obj, init)
{
	dom_setProperty(obj, "tpl_dynamicElement", new dynamicElement(obj, init));
	return obj.tpl_dynamicElement;
}

DeclareClass("dynamicElement", "dom_DOMObject", 
{
	constructor:  function(id, init)
	{
		this.base(id);	
		this.clientRenderer = null;
		this.mAction = null;
		this.mTransactionID = null;
		this.ServiceUrl = this.getAttribute("ServiceUrl");
		this.ServiceQueryString = this.getAttribute("ServiceQueryString");
		if (this.ServiceQueryString)
			this.ServiceQueryString = decodeURIComponent(this.ServiceQueryString);
		this.PersistantPostParameters = this.getAttribute("PersistantPostParameters");
		this.DataLoadText = this.getAttribute("DataLoadText");
		this.NoDataText = this.getAttribute("NoDataText");
		this.GetDataOnLoad = this.getAttribute("GetDataOnLoad");
		this.EnableHiddenLoading = this.getAttribute("EnableHiddenLoading");
		this.RefreshOnShow = this.getAttribute("RefreshOnShow");
		this.DataType = this.getAttribute("DataType");
		this.RequestPriority = this.getAttribute("RequestPriority");
		this.CustomRequestHandler = this.getAttribute("CustomRequestHandler");
		this.CustomID = this.getAttribute("CustomID");
		this.DisplayStatus = this.getAttribute("DisplayStatus");
		this.SupportPostback = this.getAttribute("SupportPostback");
		this.ClientDataObject = this.getAttribute("ClientDataObject");
		this.ClientDataObjectParams = this.getAttribute("ClientDataObjectParams");
		this.RootUrl = this.getAttribute("RootUrl");
		//count of efforts after redirect on login page and return back
		this.__countEffortsAfterLogin = 0;
		this.LoadDefaults();
		
		// events (TODO: use OOP pattern for this)
		this.OnLoading = function() { return true;}
		this.OnComplete = function() { return true;}
		this.OnError = function() { return true;}
		this.OnBeforeDataReady = function() { return true; }
		
		this.httpConnect = null;
		if (str_IsStringEmpty(this.ClientDataObject))
		{
			var thisObj = this;
			this.httpConnect = new XMLHttp.Connection(this.ServiceUrl, this.ServiceQueryString, "POST", "application/x-www-form-urlencoded", function(txt){thisObj.OnDataReceived(thisObj, txt)} );
		}
		
		this.currentParameters = new dm_QueryString();
		this.isRequestDeffered = false;
		this.events = new cmn_EventContainer();
		this.ClearParameters();
		if (init != false)
			this.Init();
		this.DataExpireTime = this.getAttribute("DataExpireTime");
		this.timerid = null;
		if(this.DataExpireTime!=null)
			this.timerid = window.setInterval(function(){thisObj.GetData();}, thisObj.DataExpireTime);
	}
	,Init : function()
	{
		if (this.GetDataOnLoad == "true")
			this.GetData();
	}
	,LoadDefaults : function()
	{
		if (str_IsStringEmpty(this.RootUrl))
			this.RootUrl = ''; 
		if (str_IsStringEmpty(this.ServiceUrl))
			this.ServiceUrl = this.RootUrl + "DynamicDataProcessor.aspx";
		if (str_IsStringEmpty(this.ServiceQueryString))
			this.ServiceQueryString = '';
		if (str_IsStringEmpty(this.PersistantPostParameters))
			this.PersistantPostParameters = '';
		if (this.DataLoadText == null)		
			this.DataLoadText = "Loading...";
		if (this.NoDataText == null)		
			this.NoDataText = "There are no items to show";
		if (str_IsStringEmpty(this.GetDataOnLoad))
			this.GetDataOnLoad = "true";
		if (str_IsStringEmpty(this.EnableHiddenLoading))
			this.EnableHiddenLoading = "false";
		if (str_IsStringEmpty(this.RefreshOnShow))
			this.RefreshOnShow = "false";
		if (str_IsStringEmpty(this.DataType))
			this.DataType = '';
		if (str_IsStringEmpty(this.RequestPriority))
			this.RequestPriority = XMLHTTP_PRIO_NORMAL;
		if (str_IsStringEmpty(this.CustomRequestHandler))
			this.CustomRequestHandler = '';
		if (str_IsStringEmpty(this.CustomID))
			this.CustomID = '';
		if (str_IsStringEmpty(this.DisplayStatus))
			this.DisplayStatus = 'true';
		if (str_IsStringEmpty(this.SupportPostback))
			this.SupportPostback = 'false';
		if (str_IsStringEmpty(this.ClientDataObject))
			this.ClientDataObject = ''; 
		if (str_IsStringEmpty(this.ClientDataObjectParams))
			this.ClientDataObjectParams = ''; 
	}
	,Dispose : function()
	{
		if (this.timerid != null)
			window.clearInterval(this.timerid);
		if (this.httpConnect != null)
			this.httpConnect.Dispose();
		this.httpConnect = null
		this.currentParameters = null;
		this.isRequestDeffered = false;
		this.events = null;
		if (this.clientRenderer != null)
			this.clientRenderer.Dispose();
		
	}
	,attachEvent : function(evt, fn)
	{
		this.events.attachEvent(evt, fn);
	}
	,OnDisplayChange : function(vis)
	{
		if (vis == true)
		{
			if (this.isRequestDeffered == true)
				this.Refresh();
			else if (this.RefreshOnShow == "true")
				this.Refresh(this.DataLoadText);
		}
		else
			if (this.EnableHiddenLoading == "false")
				this.DeferRequest();
	}
	,SetElementHTML : function(html)
	{
		try
		{
			var renderer = new UI.RenderableObject();
			renderer.obj = this.Obj();
			renderer.SetObjectInnerHtml(html);
		}catch(e){};
	}
	,RenderAsIFrame : function(dataType)
	{
		var temp = this.GetParentQuery();
		var url = url_CombineParams(url_MakeParam(P_CTLDATATYPE, dataType), url_CombineParams(url_MakeParam(P_TRANSACTIONID, this.mTransactionID), url_MakeParam(P_MONITORINGACTION, this.mAction)));
		var src = this.RootUrl + 'DynamicPostBackPage.aspx?' + url;
		src = url_CombineQueryStrings(src, temp);
		src = src.replace(/\'/ig, escape("'"));
		this.Obj().innerHTML = "<div>Loading...</div><iframe style='display:none' frameborder='0' width='100%' height='100px' scrolling='no' src='" + src+ "' onload=\"dynamicElement.ProcessIFrameLoading('" + this.Obj().id +"')\"></iframe>";
	}
	,ProcessIFrameLoading : [decl_static, function(id)
	{
		var elem = document.getElementById(id);
		if (elem == null || elem.tpl_dynamicElement == null)
			return;
		elem.tpl_dynamicElement.UpdateElementSize();
	}]
	,ReleaseIFrameResources : function()
	{
		// SCH: The reason for doing releasing by timeout is: 
		// this function can be called by the releasing iframe itself and it cause 
		// problems in FireFox.
		window.setTimeout("dynamicElement.__ReleaseIFrameResources(\"" + this.Obj().id + "\")", 1);
	}
	,__ReleaseIFrameResources : [decl_static, function(id)
	{
		var elem = document.getElementById(id);
		if (elem == null || elem.tpl_dynamicElement == null)
			return;
		elem.tpl_dynamicElement.__ClearIFrameData();
		elem.tpl_dynamicElement.Refresh(this.DataLoadText);
	}]
	,__ClearIFrameData : function()
	{
		var ifr = this.Obj().lastChild;
		if (ifr == null || str_IsStringEmpty(ifr.tagName) || ifr.tagName.toLowerCase() != "iframe")
			return;
		try { 
			ifr.contentWindow.document.open();
			ifr.contentWindow.document.write("");
			ifr.contentWindow.document.close();
			document.body.focus();
		}catch(e){};
	}
	,UpdateElementSize : function()
	{
		try
		{
			var div = this.Obj().firstChild;
			if (div != null && !str_IsStringEmpty(div.tagName))
			div.style.display = "none";
			var ifr = this.Obj().lastChild;
			if (ifr == null || str_IsStringEmpty(ifr.tagName) || ifr.tagName.toLowerCase() != "iframe")
				return;
			ifr.style.display = "";
			var par = this.Obj();
			ifr.runtimeStyle.height = ifr.contentWindow.document.body.scrollHeight + "px";
			ifr.contentWindow.focus();
		}catch(ex) {}
		
	}
	,SetElementHTMLEx : function(html)
	{
		var text = dom_getTagContent("form", html);
		if (str_IsStringEmpty(text))
			return;
		
		//scripts
		var regEx =  new RegExp("<script[^<]*>([\\s\\S]*?)<\/script>", "gim");
		var scripts = text.match(regEx);
		text = text.replace(regEx, "");
		
		//load include files	
		this.scriptsArr = new Array();
		var counter = 0;
		var regCom = new RegExp("<!--|-->", "gim");
		if (scripts != null)
		{
			for(var i = 0; i < scripts.length; i++)
			{
				var temp = dom_getTagContent("script", scripts[i]);
				if (!str_IsStringEmpty(temp))
				{
					this.scriptsArr[this.scriptsArr.length] = temp.replace(regCom,"");
					continue;
				}	
				var needeval = true;
				var scr = window.document.createElement("SCRIPT");
				var attrs = dom_getTagAttributes(scripts[i]);
				for (var j=0; j<attrs.length; j++)
				{
					var attr=document.createAttribute(attrs[j][0]);
					attr.value=attrs[j][1];
					scr.setAttributeNode(attr);
				}
				var scripttags = window.document.getElementsByTagName("script");
				for (var idx in scripttags)
					if (scripttags[idx].src == scr.src)
					{
						needeval = false;
						break;
					}
				if (needeval)
				{
					window.document.body.insertBefore(scr,window.document.body.firstChild);
					if (this.CheckScriptsLoaded(scr) == false)
					{
						if (scr.attachEvent)
							dom_attachEventForObject(scr, "readystatechange", CreateObjectCallback(this, this.OnScriptsLoaded) );
						else
						{
							scr.readyState = "complete";	// this is dummy property to make this.CheckScriptsLoaded work
							dom_attachEventForObject(scr, "load", CreateObjectCallback(this, this.OnScriptsLoaded));
						}
						counter++;
					}
				}
			}
		}
		
		this.htmlText = text;
		this.loadingScripts = counter;
		if (this.loadingScripts == 0)
			this.SetObjectContent();

	}
	,SetObjectContent : function()
	{
		var text = this.htmlText;
		var scripts = this.scriptsArr;
		
		this.SetElementHTML(text);
		
		if (scripts != null)
		{
			for (var i = 0; i < scripts.length; i++)	
			{
				try
				{
					if(!str_IsStringEmpty(scripts[i]))
						window.execScript(scripts[i]);
				}
				catch(e){};
			}
		}
		try
		{
			if (!str_IsStringEmpty(this.NoDataText))
			{
				var renderer = new UI.RenderableObject();
				renderer.obj = this.Obj();
				renderer.SetTextIfEmpty(this.NoDataText);
			}
		}
		catch(e){};
	}
	,CheckScriptsLoaded : function(obj)
	{
		if (obj && obj.readyState != 'loaded' && obj.readyState != 'complete')
			return false;
		return true;
	}
	,OnScriptsLoaded : function(evt)
	{
		if (this.CheckScriptsLoaded(evt.srcElement) == false)
			return;
		this.loadingScripts--;
		if (this.loadingScripts > 0)
			return;
		this.SetObjectContent();
	}
	,GetData : function()
	{
		this.ChangeStatus(DE_STATUS_LOADING,this.DataLoadText);
		this.DoSend();
	}
	,DoSend : function()
	{
//		//ANIDIM
//		if (!str_IsStringEmpty(this.DataType))
//			alert('Do Send for ' + this.DataType);
		
		//this.ChangeStatus(DE_STATUS_LOADING,this.DataLoadText);		
		if (!this.IsVisible() && this.EnableHiddenLoading == "false")
		{
			this.isRequestDeffered = true;
			return;
		}
		this.mTransactionID = Utils.MonitoringHelper.GetTransactionID();
		this.mAction = Utils.MonitoringHelper.GetAction();
		// SCH: any data that require call to server is performed by timeout.
		// This will give the browser time to do some actions that may
		// be caused by client data object processing.		
		if (!str_IsStringEmpty(this.ClientDataObject))
			this.__DoSend();
		else	
			setTimeout(this.CreateCallback(this.__DoSend), 1);
	}
	,__DoSend : function()
	{
		this.isRequestDeffered = false;
		if (this.SupportPostback == "true")
		{
			this.RenderAsIFrame(this.DataType);
			return;
		}
		
		if (!str_IsStringEmpty(this.ClientDataObject))
		{			
			if (this.currentParameters.GetValue(P_SUPPORT_XML) == 'true')
			{
                // if ClientDataObject is a string - we create object
                // otherwise (assuming this is a function) - we run it
                var func = this.ClientDataObject;
                if(typeof(func) == 'string') {
                    func = window.eval(func);
				new func(this, this.currentParameters);
                } else {
                    func(this, this.currentParameters);
                }
			}
			else
			{
				if ( this.clientRenderer == null)
					this.clientRenderer = UI.Control.LoadControl(this.ClientDataObject, this.Obj(), this.ClientDataObjectParams);
				this.clientRenderer.ProcessRequest();	
			}
		}
		else if (this.httpConnect != null)
		{
			if (!str_IsStringEmpty(this.DataType))
				this.currentParameters.Add(P_CTLDATATYPE, this.DataType);
			if (!str_IsStringEmpty(this.Obj().id))
				this.currentParameters.Add(P_PARENT_EL_ID, this.Obj().id);
			if (this.SupportPostback == "true")
				this.currentParameters.Add(P_SUPPORT_POSTBACK, "true");
				
			this.httpConnect.SetMonitoringInfo(this.mAction, this.mTransactionID);
			this.httpConnect.SetConnectionOptions(this.ServiceUrl, this.GetServiceQuery(), "POST", "application/x-www-form-urlencoded");
			this.httpConnect.Send(this.currentParameters.getStringValue(), this.RequestPriority);
			StartTimeLogByKey(this.DataType,"Sending request. ControlType = " + this.DataType, LOGCT_XMLHTTP);
		}
	}
	,CombineQueries : function(query)
	{
		this.currentParameters.CombineQueries(query);
	}
	,ClearParameters : function()
	{
		this.currentParameters.Clear();
		this.currentParameters.Load(this.PersistantPostParameters)
	}
	,AddParameter : function(name, val)
	{
		this.currentParameters.Delete(name);
		this.currentParameters.Add(name, val);
	}
	,RemoveParameter : function(name)
	{
		this.currentParameters.Delete(name);	
	}
	,ValidateResponse : function(response)
	{
		var isValid = true;
		if (response && this.__countEffortsAfterLogin == 0 && typeof(IncompleteRequestErrorGuid) != "undefined" && response.indexOf(IncompleteRequestErrorGuid) != -1)
		{
			this.__countEffortsAfterLogin = 1;
			this.DoSend();
			isValid = false;
		}
		return isValid
	}	

	,OnDataReceived : function(thisObj, text)
	{
		EndTimeLogByKey(this.DataType); // for  log started in DoSend();
		if (!this.ValidateResponse(text)) return;
		this.__countEffortsAfterLogin = 0;

		if (!this.OnBeforeDataReady(thisObj, text)) {
			return;
		}

		this.OnDataReady(thisObj, text);
	}

	,OnDataReady : function(thisObj, text)
	{
		StartTimeLog("Processing response. ControlType = " + this.DataType, LOGCT_XMLHTTP);
		thisObj.ChangeStatus(DE_STATUS_COMPLETE,text);	
		EndTimeLog();
	}
	,ExecuteCommand : function(commandName, params, txt, defer)
	{
		this.ClearParameters();
		this.currentParameters.Add(commandName, params);
		this.ChangeStatus(DE_STATUS_LOADING,txt);		
		if (defer != true)
			this.DoSend();
		else 
			this.isRequestDeffered = true;
	}
	,Refresh : function(txt, defer)
	{
		this.ChangeStatus(DE_STATUS_LOADING,txt);
		if (defer != true)
			this.DoSend();
		else
			this.isRequestDeffered = true;
	}
	,DeferRequest : function()
	{
		if (this.httpConnect != null && this.httpConnect.IsRequestInProgress() == true)
		{
			LogInfo("Request aborted.", LOGCT_XMLHTTP);
			EndTimeLogByKey(this.DataType); // for  log started in DoSend();
			this.httpConnect.TerminateRequest();
			this.isRequestDeffered = true;
		}
	}
	,GetParentQuery : function()
	{
		var temp;
		if (typeof(nav_GetNavigationQuery) == "undefined" || !nav_IsNavigationEnabled() )
			temp = url_GetQueryString(window.location.href);
		else
			temp = nav_GetNavigationQuery();
		return temp;
	}
	,GetServiceQuery : function()
	{
		this.ServiceQueryString = url_CombineQueryStrings(this.GetParentQuery(), this.ServiceQueryString);
		return this.ServiceQueryString;
	}
	,ChangeStatus : function(status, statusText)
	{
		// notify
		switch (status)	{
			case DE_STATUS_COMPLETE:
				if (!this.OnComplete(this, status, statusText))
					return;
				break;
			case DE_STATUS_LOADING:
				if (!this.OnLoading(this, status, statusText))
					return;
				break;
			case DE_STATUS_ERROR:
				if (!this.OnError(this, status, statusText))
					return;
				break;
		}

		if (this.CustomRequestHandler){
			var func = this.CustomRequestHandler;
			if(typeof(func) == 'string')
					func = window.eval(func);
			return func(this.CustomID, new dynamicStatusInfo(status, statusText));
			//return;
		}
		
		switch (status)
		{
			case DE_STATUS_COMPLETE:
				this.SetElementHTMLEx(statusText);
				break;	
			default:
				if (str_IsStringEmpty(this.ClientDataObject) && !str_IsStringEmpty(statusText) && !str_IsStringEmpty(this.DataLoadText))
					this.SetElementText(statusText);
				break;
		}
		
		return true;
	}
	,SetElementText : function(txt)
	{
		if (this.DisplayStatus == "false")
			return;
		var renderer = new UI.RenderableObject();
		renderer.obj = this.Obj();
		renderer.SetObjectInnerText(txt);
	}
});


DeclareNamespace("Data");

DeclareClass("Data.StorageAdapter", null,
{
	constructor : function(storage)
	{
		this.isAttached = true;
		if (storage != null)
		{
			var parts = storage.split('@');
			switch (parts[0])
			{
				case "element":
					this.type = "element";
					break;
				case "cookie":
					this.type = "cookie";
					break;
				case "variable":
					this.type = "variable";
					break;
				default:
					this.isAttached = false;
					break;
			}
			this.pathid = parts[1];
		}
		else
			this.isAttached = false;
	}
	,IsAttached : function()
	{
		return (this.isAttached == true);
	}
	,GetData : function()
	{
		if (this.isAttached == false)
			return;
		switch (this.type)
		{
			case "element":
				var obj = new dom_DOMObject(this.pathid);
				return obj.Obj().value;
			case "cookie":
				var res = tpl_GetCookie(this.pathid);
				if (str_IsStringEmpty(res) || res == null || res.toLowerCase() == "null")
					return null;
				return res;
			case "variable":
				var res;
				eval("res = "+this.pathid);
				return res;
			default:
				return null;
		}
	}
	,SetXmlData : function(data)
	{
		if (this.isAttached == false)
			return;
		this.SetData(data.GetXml());
	}
	,SetData : function(data)
	{
		if (this.isAttached == false)
			return;
		switch (this.type)
		{
			case "element":
				var obj = new dom_DOMObject(this.pathid);
				if (obj.Obj() != null)
					obj.Obj().value = data;
				break;
			case "cookie":
				tpl_SetCookie(this.pathid, data, true);
				break;
		}
	}
});



DeclareClass("Data.XmlItemBase", null,
{
	constructor : function(x, idQuery)
	{
		this.xdoc = new Xml.NodeAccessor(x);
		this.idQuery = idQuery;
		this.idName = idQuery;		
	}
	,GetEmptyXml : function()
	{
		return "<xml/>";
	}
	,CreateItem : function(xml)
	{
		if (xml == null)
			return null;
		return new data_XmlDataItem(xml, this.idQuery);
	}
	,LoadInternal : function(x)
	{
		this.xdoc.LoadXml(x);
	}
	,Load : function(x)
	{
		this.LoadInternal(x);
	}
	,GetXml : function()
	{
		return this.xdoc.GetXml();
	}
	,GetXmlDocument : function()
	{
		return this.xdoc.GetRootNode();
	}
	,GetDataRoot : function()
	{
		return this.xdoc.GetRootNode();
	}
	,GetDataNodes : function()
	{
		var r = this.GetDataRoot();
		if (r == null)
			return null;
		return r.childNodes;
	}
});


DeclareClass("Data.XmlItem", "Data.XmlItemBase",
{
	constructor : function(x, idQuery)
	{
		this.base(x, idQuery);
	}
	,GetNodeValue : function(n)
	{	
		return this.xdoc.GetNodeValue(n);
	}
	,SetNodeValue : function(n,v,a)
	{
		this.xdoc.SetNodeValue(n,v,a);
	}
	,GetNodeAttribute : function(n,a)
	{	
		return this.xdoc.GetNodeAttribute(n,a);
	}
	,GetID : function()
	{
		if (this.itemID != null)
			return this.itemID;
		var node = this.GetXmlDocument().selectSingleNode(this.idQuery)
		if (node != null)
			this.itemID = node.text;
		return this.itemID;
	}
	,MergeNodes : function(x)
	{
		var xItem = new Data.XmlItem(x);
		var nodes = xItem.GetDataNodes();
		for (var i = 0; i < nodes.length; i++)
			this.xdoc.SetNodeValue(nodes[i].nodeName, nodes[i].text);
	}
	,ClearNodes : function(id_name)
	{
		// SCH: actually we needn't pass id_name. This object MUST know it.
		var nodes = this.GetDataNodes();
		for ( var i = 0; i < nodes.length; i++ )
		{
			if ( nodes[i].nodeName != id_name )
				nodes[i].text = "";
		}
	}
	,GetBooleanAttribute : function(name, defVal)
	{
		var attr = this.xdoc.GetAttribute(name);
		if (attr == null)
			return defVal;
		if (attr == "true")
			return true;
		return false;
	}
	,SetBooleanAttribute : function(name, val)
	{
		this.xdoc.SetAttribute(name, (val == true) ? "true" : "false");
	}
	,GetAttribute : function(name)
	{
		return this.xdoc.GetAttribute(name);
	}
	,SetAttribute : function(name, val)
	{
		return this.xdoc.SetAttribute(name, val);
	}
	,GetIndex : function()
	{
		var attr = this.xdoc.GetAttribute("index");
		if (attr == null)
			return -1;
		return parseInt(attr);
	}
});


DeclareClass("Data.XmlList", "Data.XmlItemBase",
{
	constructor : function(x, idQuery, itemQuery, sortedBy)
	{
		this.base(x, idQuery);
		this.itemQuery = itemQuery;
		this.selectQuery = "//" + this.itemQuery + "[translate(" + this.idName + ", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')=";
		this.selectQueryEnd = "]";
		this.selectedItemQuery = "//" + this.itemQuery + "[@selected='true']";
		this.transformer = null;
		this.sortedBy = sortedBy;
		this.sortOrder = "asc";
		this.undeterminedSortType = false;
	}
	,CreateSortXSLTransformer : function(field, order, selectedXPathParam)
	{
		this.parentName = this.xdoc.GetRootNode().nodeName;
		if (this.parentName == null)
			return null;
		this.undeterminedSortType = false;
		
		var sorttmpl = [];
		if (!str_IsStringEmpty(field))
		{
			var sortfields = field.split(",");
			var item = this.GetByIndex(0);
			for(var i=0, sfield; sfield = sortfields[i]; i++)
			{
				if (!str_IsStringEmpty(sfield))
				{
					var sorttype = "text";
					if (item != null)
					{
						if (item.GetNodeType(sfield) != "String")
							sorttype = "number";
					}
					else
						this.undeterminedSortType = true;
					sorttmpl.push("<xsl:sort select=\"");
					sorttmpl.push(sfield);
					sorttmpl.push("\" order=\"");
					sorttmpl.push(order == "desc" ? "descending" : "ascending");
					sorttmpl.push("\" data-type=\"");
					sorttmpl.push(sorttype);
					sorttmpl.push("\" />");
				}
			}
		}
		var selectedXPath = "//" + this.itemQuery;
		if (!str_IsStringEmpty(selectedXPathParam)) 
			selectedXPath += selectedXPathParam;
		
		var xslttmpl = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" >"+
        "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\" />"+
        "<xsl:template match=\"~0\" >"+
                "<xsl:element name=\"{name()}\">"+
                    "<xsl:for-each select=\"~1\">"+
							"~2"+
                            "<xsl:copy>"+
                                "<xsl:attribute name=\"index\">"+
                                        "<xsl:value-of select=\"position()-1\"/>"+
                                "</xsl:attribute>"+
                                "<xsl:for-each select=\"@*\">"+
										"<xsl:if test=\"local-name() != 'index'\">"+ 
											"<xsl:copy/>"+
										"</xsl:if>"+
                                "</xsl:for-each>"+
                                "<xsl:copy-of select=\"*\"/>"+
                            "</xsl:copy>"+
                    "</xsl:for-each>"+
                "</xsl:element>"+
        "</xsl:template>"+
        "</xsl:stylesheet>";
        xslttmpl = xslttmpl.format(this.parentName, selectedXPath, sorttmpl.join(""));
        return new Xml.XslTransformer(xslttmpl);
	}
	,__GetById : function(id)
	{
		var xNode = this.xdoc.SelectSingleNode(this.selectQuery + Xml.Helper.PrepareXPathLiteral(id.toString().toLowerCase()) + this.selectQueryEnd);
		if (xNode == null)
			return null;
		return xNode;
	}
	,__GetByIndex : function(idx)
	{
		var childs = this.GetDataNodes();
		if (childs == null || childs[idx] == null)
			return null;
		return childs[idx];
	}
	,__GetSelectedNodes : function()
	{
		return this.xdoc.SelectNodes(this.selectedItemQuery);
	}
	,__GetSelectedSingleNodes : function()
	{
		return this.xdoc.SelectSingleNode(this.selectedItemQuery);
	}
	,SelectNodeValues : function(nodeName) {		
		var result = [];
		var rootNode = this.GetXmlDocument();
		if (rootNode) {
			result = rootNode.selectNodes("~0/~1/text()".format(this.itemQuery, nodeName));
			result = Array.getFrom(result).map(function(node) { return node.text; });
		}
		return result;
	}
	,GetById : function(id)
	{
		return this.CreateItem(this.__GetById(id));
	}
	,GetByIndex : function(idx)
	{
		return this.CreateItem(this.__GetByIndex(idx));
	}
	,GetIndexById : function(id)
	{
		var xItem = this.GetById(id);
		if (xItem == null)
			return -1;
		return xItem.GetIndex();
	}
	,GetCount : function()
	{
		var childs = this.GetDataNodes();
		if (childs == null)
			return 0;
		return childs.length;
	}
	,GetSelectedNodes : function()
	{
		return this.__GetSelectedNodes();
	}
	,GetSelectedItems : function()
	{
		var xNodes = this.__GetSelectedNodes();
		var xItems = new Array();
		if (xNodes != null)
		{
			for(var i=0; i < xNodes.length; i++)
				xItems[i] = this.CreateItem(xNodes[i])
		}
		return xItems
	}
	,GetSelectedItem : function()
	{
		return this.CreateItem(this.__GetSelectedSingleNodes());
	}
	,GetSelectedCount : function()
	{
		var childs = this.__GetSelectedNodes();
		if (childs == null)
			return 0;
		return childs.length;
	}
	,InsertXml : function(xml, pos, notSort)
	{
		if (pos == -1)
		{
			var old = this.xdoc.CreateSubNode("dummy", "", root);
			pos = this.GetDataNodes().length - 1;
			if (pos > 0)
				new Xml.NodeAccessor(this.GetDataNodes()[pos-1]).SetAttribute("last", "false");
			node.SetAttribute("index", pos);
			node.SetAttribute("last", "true");

			Xml.Document.ReplaceChild(root, newNode, old);
			if (!String.IsNullOrEmpty(this.sortedBy) && notSort != true)
				this.UpdateIndexes();
		}
		else
		{
			root.insertBefore(newNode, this.GetDataNodes()[pos]);
			if (notSort != true)
				this.UpdateIndexes();
		}
		return this.CreateItem(newNode.xml);
	}
	,InsertXml : function(xml, pos, notSort)
	{
		if (pos == null)
			pos = -1;
		var node = new Xml.NodeAccessor(xml);
		var newNode = node.IsDocumentNode() ? node.GetFirstChild() : node.xmlDoc;
		var root = this.GetDataRoot();
		if (pos == -1)
		{
			var old = this.xdoc.CreateSubNode("dummy", "", root);
			pos = this.GetDataNodes().length - 1;
			node.SetAttribute("index", pos);
			Xml.Document.ReplaceChild(root, newNode, old);
			if (!str_IsStringEmpty(this.sortedBy) && notSort != true)
			{
				this.UpdateIndexes();
				var xItem = this.CreateItem(xml);
				pos = this.GetById(xItem.GetItemID()).GetIndex();
			}
		}
		else
		{
			Xml.Document.InsertBefore(root, newNode, this.GetDataNodes()[pos]);
			if (notSort != true)
			{				
				this.UpdateIndexes();
				var xItem = this.CreateItem(xml);
				var xItemID = this.GetById(xItem.GetItemID());
				if(xItemID)
					pos = xItemID.GetIndex();
			}
		}
		return pos;
	}
	,DeleteById : function (id, notSort)
	{
		var xNode = this.__GetById(id);
		if (xNode == null)
			return;
		this.xdoc.GetRootNode().removeChild(xNode);
		if(notSort != true )
			this.UpdateIndexes();
	}
	,DeleteByIndex : function(idx)
	{
		var xNode = this.__GetById(idx);
		if (xNode == null)
			return;
		this.xdoc.GetRootNode().removeChild(xNode);
		this.UpdateIndexes();
	}
	,TransformXML : function(field, order, selectedXPathParam)
	{
		if (this.xdoc.GetRootNode() == null)
			return;
		if (this.sortedBy != field || this.transformer == null || 
			this.parentName != this.xdoc.GetRootNode().nodeName || this.undeterminedSortType
			|| !str_IsStringEmpty(selectedXPathParam) || this.sortOrder != order)
			this.transformer = this.CreateSortXSLTransformer(field, order, selectedXPathParam);
		this.sortedBy = field;
		if (!str_IsStringEmpty(order))
			this.sortOrder = order;
		this.LoadInternal(this.transformer.Transform(this.GetDataRoot()));
	}
	,Sort : function(field, order)
	{
		this.TransformXML(field, order);
	}
	,UpdateIndexes : function()
	{
		this.Sort(this.sortedBy);
	}
	,Clear : function()
	{
		this.Load(this.GetEmptyXml());
	}
	,Load : function(x, selectedXPathParam)
	{
		this.LoadInternal(x);
		if ( !str_IsStringEmpty(selectedXPathParam) )
			this.TransformXML(this.sortedBy, null, selectedXPathParam)
		else if ( !str_IsStringEmpty(this.sortedBy) )
			this.UpdateIndexes();
	}
	
});

DeclareClass("Data.DSItemBase", null,
{
	constructor : function(data, xml, storage, events)
	{
		this.xdata = data;
		this.events = new cmn_EventContainer(events);
		this.status = new dynamicStatusInfo(DE_STATUS_LOADING, "Loading...");
		this.dataStorageAdapter = new Data.StorageAdapter(storage);
		if ( ((xml == null) ? true : (xml instanceof String ? str_IsStringEmpty(xml) : false ) ) && this.dataStorageAdapter.IsAttached())
		{
			xml = this.dataStorageAdapter.GetData();
			if (str_IsStringEmpty(xml))
				xml = this.xdata.GetEmptyXml();
		}	
		this.__SetXml(xml, null, true);
	}
	,__SetXml : function(xml, st, isFirst)
	{
		this.Clear();
		if (xml == null)
		{
			if (this.xdata.GetXmlDocument() != null && isFirst != true)
			{
				this.xdata.Load(null);
				this.ChangeStatus(new dynamicStatusInfo(DE_STATUS_LOADING, st));
				this.UpdateDataStorage();
			}
			return;
		}
		this.xdata.Load(xml);
		this.ChangeStatus(new dynamicStatusInfo(DE_STATUS_COMPLETE, st));
		this.UpdateDataStorage();
	}
	,UpdateDataStorage : function()
	{
		this.dataStorageAdapter.SetXmlData(this);
	}
	// SCH: for two functions below I prefer to use new naming convention
	,attachEvent : function(evt, func)
	{
		return this.events.attachEvent(evt, func);
	}
	,detachEvent : function(evt, id)
	{
		this.events.detachEvent(evt, id);
	}	
	,FireEvent : function(evt, o)
	{
		this.events.fireEvent(evt,o);
	}
	,FireEvent : function(evt, o)
	{
		if(this.events.__isPaused)
			this.events.__eventsStorage.push({evt: evt, args: o});
		else
			this.events.fireEvent(evt,o);
	}
	,PauseEvents: function()
	{
		this.events.__isPaused = true;
		this.events.__eventsStorage = [];
	}
	,ResumeEvents: function()
	{	
		this.events.__isPaused = false;
		while(this.events.__eventsStorage.length>0){
			var item = this.events.__eventsStorage.shift();
			this.events.fireEvent(item.evt, item.args);
		}
	}
	,GetXml : function()
	{
		if (this.xdata == null)
			return null;
		return this.xdata.GetXml();
	}
	,GetXmlDocument : function()
	{	// SCH: need to research possibility of returning here document
		return this.xdata.GetXmlDocument();
	} 
	,ChangeStatus : function(st)
	{	
		this.status = st;
		this.FireEvent("onstatuschange", this);
	}
	,Touch : function()
	{	
		var st = this.status;
		this.ChangeStatus(new dynamicStatusInfo(DE_STATUS_LOADING, "Loading"));
		this.ChangeStatus(st);
	}
	,Clear : function()
	{	
		// SCH: put common implementation here
	}
});


DeclareClass("Data.DSItem", "Data.DSItemBase",
{
	constructor : function(xml, idpath, storage)
	{
		this.base(new Data.XmlItem(null, idpath), xml, storage);
		this.itemIndex = this.xdata.GetIndex(); 
		this.parentDataSourceName = '';  // SCH: probably we will support this property
	}
	,getValue : function(name)
	{	// SCH: this function is obsolete. replaced by GetNodeValue
		return this.GetNodeValue(name);
	}
	,GetNodeValue : function(name)
	{	
		return this.xdata.GetNodeValue(name);
	}
	,SetNodeValue : function(name, val)		
	{
		this.xdata.SetNodeValue(name, val);
	}
	,GetItemID : function()
	{
		return this.xdata.GetID();
	}
	,Merge : function(xml)
	{
		this.xdata.MergeNodes(xml);
		this.FireEvent("ondatasetchange");
	}
	,GetNodeType : function(name)
	{	
		var type =this.xdata.GetNodeAttribute(name, "ValueType");
		if (type == null)
			type = "String";
		return type;
	}
	,GetTypedNodeValue : function(name)
	{	
		// SCH: probably better to move this stuff into Data.XmlItem
		var value = this.GetNodeValue(name);
		if (value != null)
		{
			var valueType = this.GetNodeType(name);
			switch(valueType)
			{
				case "Int":
					return parseInt(value);
				case "Decimal":
					return parseFloat(value)
				default:
					return value;
			}
		}
		return value;
	}
	,SetTypedNodeValue : function(name, val, valtype)
	{
		this.xdata.SetNodeValue(name, val, [new Xml.Attribute("ValueType", valtype)]);
	}
	,SetAttributeValue : function(name, val)
	{
		this.xdata.SetAttribute(name, val);
	}
	,SetNodeAttributeValue : function(nm, attributename, val)
	{
		// SCH: is it function needed??
		this.xdata.SetNodeAttributes(nm, [new Xml.Attribute(attributename, val)]);
	}
	,ClearValues : function(id_name)
	{
		// SCH: we need to remove id_name. See also comment on ClearNodes.
		this.xdata.ClearNodes(id_name);
	}
	,IsSelected : function(val)
	{
		return this.xdata.GetBooleanAttribute("selected", false);
	}
	,IsSelectable : function()
	{
		return this.xdata.GetBooleanAttribute("selectable", true);
	}
	,SetSelectable : function(val)
	{
		this.xdata.SetBooleanAttribute("selectable", val);		
	}
	,MarkSelected : function(val)
	{
		if(!this.IsSelectable())
			return;	
		this.xdata.SetBooleanAttribute("selected", val);		
	}
	,GetIndex : function()
	{
		return this.itemIndex;
	}
	,GetGroupID : function()
	{
		return this.xdata.GetAttribute("GroupID");
	}
	,SetGroupID : function(v)
	{
		return this.xdata.SetAttribute("GroupID", v);
	}
	,MarkAsEmpty : function()
	{
		this.SetSelectable(false);
		return this.xdata.SetAttribute("EmptyItem", "");
	}
	
});

DeclareClass("Data.DSItemList", "Data.DSItemBase",
{
	// SCH: we need to review usability of these parameters
	constructor : function(xml, idpath, itemQuery, commandMapping, name, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection) 
	{
	
		this.base(new Data.XmlList(null, idpath, itemQuery, sortedby), xml, storage, events);
		this.name = name;
		this.needDropSelection = needDropSelection == false? false : true;
		this.itemQuery = itemQuery;
		
				
		if (!keywords && str_IsStringEmpty(keywords))
			this.keywords = null;
		else
			this.keywords = keywords.split(",");
	
		if (dynamicGroupsCreator && !str_IsStringEmpty(dynamicGroupsCreator) && groupsDSName && !str_IsStringEmpty(groupsDSName))
		{
			var dyncr = eval("new "+dynamicGroupsCreator+"(\""+groupsDSName+"\")");
			this.dynamicGroupsCreator = dyncr;
			this.attachEvent("onstatuschange", function(ds){dyncr.OnStatusChanged(ds, dyncr)});
		}
		else
			this.dynamicGroupsCreator =  null;	
	
		this.limit = limit;	
		this.commandMapping = new dm_NameValueCollection();
		this.commandMapping.Load(commandMapping);	
	}
	,GetItemName : function()
	{
		return this.xdata.itemQuery;
	}
	,GetCount : function()
	{
		return this.xdata.GetCount();
	}	
	,Get : function(id)
	{
		return this.xdata.GetById(id);
	}
	,GetByIndex : function(idx)
	{
		return this.xdata.GetByIndex(idx);
	}
	,GetIndexById : function(id)
	{
		return this.xdata.GetIndexById(id);
	}
	,GetIdByIndex : function(idx)
	{
		var xItem = this.GetByIndex(idx);
		if (xItem == null)
			return null;
		return xItem.GetItemID();
	}
	,GetValues : function(fieldName) {
		return this.xdata.SelectNodeValues(fieldName);
	}
	,Contains : function(id)
	{
		if (this.Get(id) == null) return false;
		return true;
	}
	,AddXmlItem : function(xml)
	{
		if (!this.SetXmlItem(xml))
		{
			this.FireEvent("onitemadd", this.AddXmlItemInternal(xml, true));
			this.UpdateDataStorage();
		}
	}
	,AddXmlItemInternal : function(xml, fireevents, notSort)
	{
		if (this.limit && this.limit > 0 && this.GetCount() == this.limit)
		{
			var xExisting = this.CreateItem(this.GetByIndex(this.GetCount()-1).GetXml());
			this.DeleteItemById(xExisting.GetItemID());
			if(fireevents == true)
				this.FireEvent("onitemdelete", xExisting);
		}
		var xItem = this.xdata.CreateItem(xml);
		
		xItem.itemIndex = this.xdata.InsertXml(xml, null, notSort);
		
		// SCH: do sorting here
		//if (notSort != false)
		//	this.xdata.Sort();
		
		xItem.parentDataSourceName = this.name;
		return xItem;
	}
	,InsertXmlItem : function(xml, pos, notSort)
	{
		if (!this.SetXmlItem(xml))
		{
			this.FireEvent("onitemadd", this.InsertXmlItemInternal(xml, pos, notSort));
			this.UpdateDataStorage();
		}
	}
	,InsertXmlItemInternal : function(xml, pos, notSort)
	{	
		if (this.limit && this.limit > 0 && this.GetCount() == this.limit)
		{
			if(pos > this.limit)
				return;
			var xExisting = this.CreateItem(this.GetByIndex(this.GetCount() - 1).GetXml());
			this.DeleteItemById(xExisting.GetItemID(), notSort);
			this.FireEvent("onitemdelete", xExisting);
		}
		var xItem = this.xdata.CreateItem(xml);
		
		xItem.itemIndex = this.xdata.InsertXml(xml, pos, notSort);
		
		xItem.parentDataSourceName = this.name;
		return xItem;
	}
	,ChangeItemProperty : function(id, name, val, fireEvent)
	{
		var xItem = this.Get(id);
		if (xItem == null)
			return;
		xItem.SetNodeValue(name, val);
		this.SetXmlItem(xItem.GetXml(), fireEvent);
	}
	,SetXmlItem : function(xml, fireEvt)
	{
		var xItem = this.xdata.CreateItem(xml);
		var xExisting = this.Get(xItem.GetItemID());
		if (xExisting == null)
			return false;
		xExisting.Merge(xml);
		this.xdata.UpdateIndexes();
		if (fireEvt != false)
			this.FireEvent("onitemchange", this.Get(xExisting.GetItemID()));
		this.UpdateDataStorage();
		return true;
	}
	,DeleteXmlItem : function(xml)
	{
		var xItem = this.xdata.CreateItem(xml);
		var xExisting = this.Get(xItem.GetItemID(), true);
		if (xExisting == null)
			return;
		xExisting = this.CreateItem(xExisting.GetXml());
		this.DeleteItemById(xItem.GetItemID());
		this.FireEvent("onitemdelete", xExisting);
		this.UpdateDataStorage();
	}
	,DeleteItemById : function(id, notSort)
	{
		this.xdata.DeleteById(id, notSort);
		this.UpdateDataStorage();
	}
	,TouchItem : function(id)
	{
		var xItem = this.Get(id);
		if (xItem == null) return;
		this.FireEvent("onitemchange", xItem);
	}
	,DoesSupportPseudoMultiSelection : function(item)
	{
		var selecteitem_value = item.xdata.GetNodeValue("SelectedItem");
		if(selecteitem_value==null)
			return false;
		return true;
	}
	,GetItemSelectedStatus : function(item)
	{
		return item.xdata.GetNodeValue("SelectedItem");
	}
	,SetItemSelectedStatus : function(item, status)
	{
		item.xdata.SetNodeValue("SelectedItem", status ? "true" : "false");
		this.TouchItem(item.GetItemID());
	}	
	,SelectItemById : function(id, sel, exclusive, extendedms)
	{
		/*
		if (exclusive == false && extendedms == true && eventObject)
			exclusive = !eventObject.ctrlKey;
		*/
		var xItem = this.Get(id);
		if (exclusive != false)
		{
			var xItems = this.xdata.GetSelectedItems();
			for (var i = xItems.length-1; i>=0; i--)
			{
				if(xItems[i].GetItemID()!=xItem.GetItemID())
				{
					this.SetItemSelectedStatus(xItems[i], false);
				this.SetSelectionInternal(xItems[i], false);
				}
			}

			if (xItem != null)
			{
				if(!sel&&this.GetItemSelectedStatus(xItem)=="true")
					sel = true;
				this.SetItemSelectedStatus(xItem, false);
				this.SetSelectionInternal(xItem, sel);
		}
			if(sel)
				this.firstSelectedItemID = xItem.GetItemID();
			else
				this.firstSelectedItemID = null;
		}
		else if (xItem != null)
		{
			if(!this.DoesSupportPseudoMultiSelection(xItem))
			this.SetSelectionInternal(xItem, !xItem.IsSelected());
			else
			{
				var xItems = this.xdata.GetSelectedItems();
				if(sel)
				{
					if(xItems.length)
					{					
						this.SetItemSelectedStatus(xItem, true);
						this.SetSelectionInternal(xItem, false);
						xItem.MarkSelected(true);
						
						this.TouchItem(this.firstSelectedItemID);
					}
					else
					{
						this.firstSelectedItemID = xItem.GetItemID();
						this.SetItemSelectedStatus(xItem, false);
						this.SetSelectionInternal(xItem, true);
					}
				}
				else
				{
					this.SetSelectionInternal(xItem, false);
					//this.SetItemSelectedStatus(xItem, false);				
					if(this.firstSelectedItemID!=null
						&& xItem.GetItemID()==this.firstSelectedItemID)
					{
						if(xItems.length==1)
							this.firstSelectedItemID = null;
						else
						{
							for(var i = xItems.length-1; i>=0; i--)
							{	
								if(xItems[i].GetItemID()!=this.firstSelectedItemID)
								{
									this.firstSelectedItemID = xItems[i];					
									this.SetItemSelectedStatus(xItems[i], false);
									this.SetSelectionInternal(xItems[i], true);
									break;
								}
							}			
						}
					}
					else
						this.TouchItem(this.firstSelectedItemID);
				}
			}
		}
			
		/*if (xItem != null)
		{
			var nipos = xItem.GetIndex();
			var lipos = this.lastSelItemPos == null ? 0 : this.lastSelItemPos;
			var selst = this.lastSelItemStat == null ? true : this.lastSelItemStat;
			if(extendedms == true && window.event && window.event.shiftKey)
			{
				var lItem = this.GetByIndex(lipos);
				if (lItem != null && Math.abs((nipos - lipos)) > 1)
				{
					
					var shift = nipos > lipos ? 1 : -1;
					for(var i = lipos; i != nipos; i += shift )
					{
						var xItem = this.GetByIndex(i);
						if (xItem != null && xItem.IsSelected() != selst)
							this.SetSelectionInternal(xItem, selst);
					}
				}
			}
			else
			{
				this.lastSelItemPos = xItem.GetIndex();
				this.lastSelItemStat = xItem.IsSelected();
			}
		}*/
	}
	,SetItemSelectionAbility : function(id, isSelectable)
	{
		var xItem = this.Get(id);
		xItem.SetSelectable(isSelectable);
		this.FireEvent("onitemchange", xItem);
		this.UpdateDataStorage();	
	}
	,LoadData : function(xml, resel, st)
	{	
		if (xml != null && resel == true)
		{
			var xItems = this.xdata.GetSelectedItems();
			if (xItems != null && xItems.length > 0)
			{
				var tmpcol = this.CreateCopy();
				tmpcol.__SetXml(xml);
				for(var i=0; i<xItems.length; i++)
				{
					var xItem = tmpcol.Get(xItems[i].GetItemID());
					if (xItem != null)
						tmpcol.SetSelectionInternal(xItem, true);
				}
				xml = tmpcol.GetXml();
		}
	}
		this.__SetXml(xml, st);
	}
	,SetSelectionInternal : function(xItem, sel)
	{
		if (sel == true)
			this.FireEvent("onbeforeitemselect",xItem);
		else
			this.FireEvent("onbeforeitemdeselect",xItem);
		xItem.MarkSelected(sel);
		this.UpdateDataStorage();
		this.FireEvent("onitemchange", xItem);
		if (sel == true)
			this.FireEvent("onafteritemselect",xItem);
		else
			this.FireEvent("onafteritemdeselect",xItem);
	}
	,ClearSelection : function()
	{
		var xItems = this.xdata.GetSelectedItems();
		for (var i = 0; i < xItems.length; i++)
			this.SetSelectionInternal(xItems[i], false); 
	}
	,HasSelection : function()
	{
		return this.xdata.GetSelectedCount() != 0;
	}
	,GetItemCopy : function(id)
	{
		var xItem = this.Get(id);
		if (xItem == null)
			return null;
		return this.xdata.CreateItem(xItem.GetXml());	
	}
	,GetSelectedCount : function()
	{
		return this.xdata.GetSelectedCount();
	}
	,GetSelectedItemCopy : function(id)
	{
		var xItem = this.xdata.GetSelectedItem();
		if (xItem == null)
			return null;
		return this.xdata.CreateItem(xItem.GetXml());
	}
	,GetSelectedItemsCopy : function()
	{
		var xNodes = this.xdata.GetSelectedNodes();
		var xCollect = null;
		if(xNodes)
		{
			xCollect = this.CreateCopy();
			for(var i=0; i< xNodes.length; i++)
				xCollect.AddXmlItemInternal(xNodes[i].xml);
		}
		return xCollect;
	}
	,GetGroupingItemsCopy : function(groupID)
	{
		if (str_IsStringEmpty(groupID))
			return null;
		// SCH: move empty collection creation to separate method
		var xCollect = new data_XmlGroupingDataCollection(this.xdata.GetEmptyXml(), this.xdata.idQuery, this.xdata.itemQuery, this.name, this.xdata.sortedby, groupID );
		xCollect.status = new dynamicStatusInfo(DE_STATUS_LOADING, "Loading...");
		//this.FillGroupingItemsCopy(xCollect);
		return xCollect;
	}
	,GetRange : function(idx, count)
	{
		var cnt = idx+count > this.GetCount()? this.GetCount() : idx+count;
		var xCollect = this.CreateCopy();
		for(var i=idx; i< cnt; i++)
			xCollect.AddXmlItemInternal(this.GetByIndex(i).GetXml());
		return xCollect;
	}
	,FillGroupingItemsCopy : function(xCollect)
	{
		/*for(var i=0; i< this.GetCount(); i++)
		{
			var xItem = this.GetByIndex(i);
			if (xItem.GetGroupID() == xCollect.groupID)
					xCollect.AddXmlItemInternal(xItem.GetXml(),false, false);
		}
		xCollect.xdata.UpdateIndexes();*/
		xCollect.xdata.Load(this.GetXml(), "[@GroupID='~0']".format(xCollect.groupID));
	}
	,CreateCopy : function(full)
	{
		return new data_XmlDataCollection(full == true ? this.GetXml() : this.xdata.GetEmptyXml(), this.xdata.idQuery, this.xdata.itemQuery, null, null, null, this.xdata.sortedBy);
	}
	,CreateItem : function(x)
	{
		return this.xdata.CreateItem(x);
	}
	,ProcessCommand : function(command, data)
	{
		var internalCommand;
		switch (command)
		{
			case "update":
			case "add":
			case "delete":
				internalCommand = command;
				break;
			default:
				internalCommand = this.commandMapping.GetNameByValue(command);
				if (internalCommand == null)
					return;
				break;
		}
		switch (internalCommand.toLowerCase())
		{
			case "update":
				this.SetXmlItem(data);
				break;
			case "add":
				this.AddXmlItem(data);
				break;
			case "delete":
				this.DeleteXmlItem(data);
				break;
		}
	}
	,Clear : function()
	{
		this.xdata.Clear();
	}	
	,Sort : function(sortedby, order)
	{
		this.xdata.Sort(sortedby||this.xdata.sortedBy, order);
	}
	,HasKeyword : function(kw)
	{
		if (this.keywords == null)
			return false;
		for (var i = 0; i < this.keywords.length; i++)
			if (this.keywords[i] == kw.toLowerCase())
				return true;
		return false;
	}
	,IsAllowedOperation : function(keywords)
	{
		if (keywords == "*" || this.keywords == "*")
			return true;
		if (keywords == null)
			return false;
		if (this.IsDSName(keywords) == true)
			return true;
		var kwArray = keywords.split(",");
		for (var i = 0; i < kwArray.length; i++)
			if ( this.HasKeyword(kwArray[i]))
				return true;
		return false;
	}
	,IsDSName : function(name)
	{
		if (str_IsStringEmpty(name))
			return false;
		return this.name == name.split('@')[0];
	}
});

DeclareClass("data_XmlDataItem", "Data.DSItem", 
{
	constructor : function(xml, idpath, name, storage)
	{
		this.base(xml, idpath, storage);
	}
});


DeclareClass("data_XmlDataCollection", "Data.DSItemList", 
{
	constructor : function(xml, idpath, itemQuery, commandMapping, name, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection)
	{
		this.base(xml, idpath, itemQuery, commandMapping, name, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection);
	}
});


DeclareClass("Data.DSGroupedList", "Data.DSItemList", 
{
	constructor : function(xml, idpath, itemQuery, name, sortedby, groupID)
	{
		this.base(xml, idpath, itemQuery, null, name, null, sortedby, null, null,  null, null);
		this.dsparent = data_GetDataset(name);
		this.groupID = groupID;
		this.selchange = false;
		this.timeid = null;
		this.eventhandles = new Array();
		if (this.dsparent != null)
		{
			var thisVar = this;
			this.eventhandles["onbeforeitemselect"] = this.dsparent.attachEvent("onbeforeitemselect", function(p){thisVar.OnBeforeItemSelChanged(thisVar, p, true)} );
			this.eventhandles["onbeforeitemdeselect"] = this.dsparent.attachEvent("onbeforeitemdeselect", function(p){thisVar.OnBeforeItemSelChanged(thisVar, p, false)} );
			
			this.eventhandles["onafteritemselect"] = this.dsparent.attachEvent("onafteritemselect", function(p){thisVar.OnAfterItemSelChanged(thisVar, p, true)} );
			this.eventhandles["onafteritemdeselect"] = this.dsparent.attachEvent("onafteritemdeselect", function(p){thisVar.OnAfterItemSelChanged(thisVar, p, false)} );
			
			this.eventhandles["onstatuschange"] = this.dsparent.attachEvent("onstatuschange", function(p){thisVar.OnDataSetReadyStateChange(thisVar, p)} );
			this.eventhandles["onitemchange"] = this.dsparent.attachEvent("onitemchange", function(p){thisVar.OnItemChanged(thisVar, p)} );
			this.eventhandles["onitemdelete"] = this.dsparent.attachEvent("onitemdelete", function(p){thisVar.OnItemDeleted(thisVar, p)} );
			this.eventhandles["onitemadd"] = this.dsparent.attachEvent("onitemadd", function(p){thisVar.OnItemAdded(thisVar, p)} );
			this.ChangeStatus(new dynamicStatusInfo(this.dsparent.status.status, this.dsparent.status.statusText))
		}
	}
	,IsValidItem : function(xItem)
	{
		return xItem.GetGroupID() == this.groupID;
	}
	,OnBeforeItemSelChanged : function(thisVar, xItem, sel)
	{
		if (thisVar.IsValidItem(xItem))
			this.selchange = true;
	}
	,OnAfterItemSelChanged : function(thisVar, xItem, sel)
	{
		if (thisVar.IsValidItem(xItem))
		{
			thisVar.selchange = false;
			thisVar.SetSelectionInternal(thisVar.Get(xItem.GetItemID()), sel);
		}
	}
	,OnDataSetReadyStateChange : function(thisVar, parent)
	{
		if (parent.status.status == DE_STATUS_COMPLETE)
		{
			thisVar.Clear();
			thisVar.dsparent.FillGroupingItemsCopy(thisVar);
			thisVar.timeid = window.setTimeout(function(){thisVar.ChangeStatusTime(thisVar, new dynamicStatusInfo(parent.status.status, parent.status.statusText))}, 10);
		}
		else
		{
			if (thisVar.timeid != null)
			{
				window.clearTimeout(thisVar.timeid);
				thisVar.timeid = null;			
			}
			thisVar.ChangeStatus(new dynamicStatusInfo(parent.status.status, parent.status.statusText))
		}
	}
	,ChangeStatusTime : function(thisVar, st)
	{
		thisVar.timeid = null;
		thisVar.ChangeStatus(st);
	}
	,OnItemChanged : function(thisVar, xItem)
	{
		if (thisVar.IsValidItem(xItem) && !this.selchange)
			thisVar.SetXmlItem(xItem.GetXml());
	}
	,OnItemDeleted : function(thisVar, xItem)
	{
		if (thisVar.IsValidItem(xItem))
			thisVar.DeleteXmlItem(xItem.GetXml());
	}
	,OnItemAdded : function(thisVar, xItem)
	{
		if (thisVar.IsValidItem(xItem))
			thisVar.AddXmlItem(xItem.GetXml());
	}
	,Dispose : function()
	{
		this.DetachDataSourceEvents();
	}
	,DetachDataSourceEvents : function()
	{
		if (this.eventhandles != null)
		{
			for(var key in this.eventhandles)
				this.dsparent.detachEvent(key, this.eventhandles[key]);
		}
	}
});



// -----------------------


DeclareClass("data_XmlGroupingDataCollection", "Data.DSGroupedList",
{
	constructor : function(xml, idpath, itemQuery, name, sortedby, groupID)
	{
		this.base(xml, idpath, itemQuery, name, sortedby, groupID);
	}
});

// ------------------------
DeclareClass("Data.DynamicGroupsCreator", null, 
{
	constructor : function(DSName)
	{
		this.GroupsDSName = DSName;
		this.groupsTmpl = "[not(@GroupID=\"~0\")]";
		this.copyGpoupDS = null;
	}
	,OnStatusChanged : function(dsSrc, thisVar)
	{
		if (dsSrc.status.status == DE_STATUS_COMPLETE)
			thisVar.Create(dsSrc)
		else 
			thisVar.Clear(dsSrc);
	}
	,Create : function(dsSrc)
	{
		this.CreateDSCopy();
		if (dsSrc.GetCount() > 0)
		{
			var item = null;
			var itemPath = "//~0".format(dsSrc.GetItemName());
			var attrs = "";
			var xpath = itemPath+"[@GroupID]";
			var xmlDoc = dsSrc.GetXmlDocument();

			while((item = xmlDoc.selectSingleNode(xpath)) != null)
			{
				var xItem = dsSrc.CreateItem(item.xml);
				this.AddGroup(xItem);
				attrs += this.groupsTmpl.format(xItem.GetGroupID());
				xpath = itemPath+attrs;
			}
		}
		this.SetXmlToGroupsDS();
	}
	,Clear : function(dsSrc)
	{
		if (str_IsStringEmpty(dsSrc.status.statusText)) dsSrc.status.statusText = "Loading...";
		var ds = data_GetDataset(this.GroupsDSName);
		if (ds != null)
			ds.Clear();
		this.copyGpoupDS = null;
	}
	,CreateDSCopy : function()
	{
		var ds = data_GetDataset(this.GroupsDSName);
		if (ds != null)
			this.copyGpoupDS = ds.CreateCopy(false);
	}
	,SetXmlToGroupsDS : function()
	{
		var ds = data_GetDataset(this.GroupsDSName);
		if (ds != null && this.copyGpoupDS != null)
			ds.__SetXml(this.copyGpoupDS.GetXml());
	}
	,AddGroup : function(xItem)
	{
		if (this.copyGpoupDS != null && xItem != null)
		{
			var id = xItem.GetGroupID();
			var name = this.GetGroupName(xItem);
			var xGItem = data_createEmptyItem(GroupItem);
			xGItem.SetNodeValue(GroupItem.PN_ID, id);
			xGItem.SetNodeValue(GroupItem.PN_GROUPNAME, name);
			xGItem.SetTypedNodeValue(GroupItem.PN_WEIGHT, id, "Decimal");
			this.copyGpoupDS.AddXmlItem(xGItem.GetXml());
		}
	}
	,GetGroupName : function(xItem)
	{
		return xItem.GetGroupID();
	}
});

DeclareClass("Data.HourDynamicGroupsCreator", "Data.DynamicGroupsCreator",
{
	constructor : function(DSName)
	{
		this.base(DSName);
	}
	,GetGroupName : function(xItem)
	{
		return xItem.GetNodeValue(MessageItem.PN_OCCURANCE);
	}
});

DeclareClass("Data.SearchDynamicGroupsCreator", "Data.DynamicGroupsCreator",
{
	constructor : function(DSName)
	{
		this.base(DSName);
	}
	,GetGroupName : function(xItem)
	{
		try
		{
			var startDate = new Date(Date.parse(xItem.GetNodeValue(MessageItem.PN_STARTDATE)));
			return startDate.ToString(GeneralPreferences.DateFormatExpression);
		}
		catch(e){}
	}
});
	
// -----------------------
function date_StartDateCompare (item1, item2)
{
	try
	{
		var val1 = new Date(Date.parse(item1.GetTypedNodeValue(MessageItem.PN_STARTDATE)));
		var val2 = new Date(Date.parse(item2.GetTypedNodeValue(MessageItem.PN_STARTDATE)));
		return tpl_CompareDate(val1, val2)
	}
	catch(e){}
	return 0;
}
// -----------------------
function data_DataStore()
{
	this.collection = new dm_KeyedCollection();
	this.events = new cmn_EventContainer();
	this.selectedItems = new dm_KeyedCollection();
	this.selectedItemsForEmailing = new dm_KeyedCollection();	
}
data_DataStore.prototype.attachEvent=function(evt, func)
{
	return this.events.attachEvent(evt, func);
}
data_DataStore.prototype.detachEvent=function(evt, id)
{
	return this.events.detachEvent(evt, id);
}
data_DataStore.prototype.RegisterDataset=function(name, xml, itemIDQuery, itemQuery, commandMapping, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection)
{
	var ds = this.GetDataset(name);
	if (ds == null || ds.GetItemName() != itemQuery)
	{
		if (ds != null)
			this.DestroyDataSet(name);
		ds = new data_XmlDataCollection(xml, itemIDQuery, itemQuery, commandMapping, name, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection);
		this.collection.Add(name, ds);
	}
	else
		this.SetDatasetData(name, xml);
	if (ds.HasSelection() == true)
		this.selectedItems.Add(name, ds);
	else
		this.selectedItems.Delete(name);
	this.events.fireEvent("ondatasetregistered", ds);
	ds.events.fireEvent("ondatasetregistered",ds);
	return ds;
}
data_DataStore.prototype.SetDatasetData=function(name, xml, st)
{
	var ds = this.collection.Get(name);
	if (ds != null)
	{
		ds.LoadData(xml, true, st);

		//AL: Hightlight user selected items for emailing
		if(ds.DoesSupportPseudoMultiSelection && this.selectedItemsForEmailing.getCount()>0)
		{
			var expandItem = false;
			for(var i=0; i<ds.GetCount(); i++)
			{
				var itemKey = name+ds.GetIdByIndex(i);				
				var item = this.selectedItemsForEmailing.getItem(itemKey);
				if(item!=null && ds.GetByIndex(i).xdata.xdoc.xmlDoc.nodeName != "ContainerItem")
				{
					if(!expandItem)
					{		
						expandItem = true;
						ds.SelectItemById(ds.GetIdByIndex(i), true, expandItem, true);
					}
					else
						ds.SelectItemById(ds.GetIdByIndex(i), true, false, true);
				}
			}			
		}
	}
}
data_DataStore.prototype.DestroyDataSet=function(name)
{
	var ds = this.collection.Get(name);
	if (ds == null)
		return;
	ds.LoadData(null);	
	this.collection.Delete(name);
}
data_DataStore.prototype.Dispose=function()
{
	for (var i = this.collection.getCount() - 1; i >= 0; i--)
		this.DestroyDataSet(this.collection.GetKeyByIndex(i));
}
data_DataStore.prototype.ChangeDatasetStatus=function(name, st)
{
	var ds = this.collection.Get(name);
	if (ds != null)
		ds.ChangeStatus(st);
}
data_DataStore.prototype.GetDataset=function(name)
{
	var ds =  this.collection.Get(name);
	if (ds == null)
	{
		for (var i = 0; i < this.collection.getCount(); i++)
		{
			var dsT = this.collection.GetByIndex(i);
			if (dsT.IsAllowedOperation(name) == true)
			{
				ds = dsT;
				break;
			}
		}
	}
	return ds;
}
data_DataStore.prototype.GetDatasetRecordByIndex=function(dsName, idx)
{
	var ds = this.GetDataset(dsName);
	if (ds == null)
		return null;
	return ds.GetByIndex(idx);
}
data_DataStore.prototype.DeleteItemByID=function(dsName, id)
{
	var ds = this.GetDataset(dsName);
	if (ds == null)
		return;
	var xItem = ds.Get(id);
	if (xItem == null)
		return;
	ds.DeleteXmlItem(xItem.GetXml());
}
data_DataStore.prototype.UpdateDatasetRecord=function(category, command, data)
{
	for (var i = 0; i < this.collection.getCount(); i++)
	{
		var ds = this.collection.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
			ds.ProcessCommand(command, data);
	}
}
data_DataStore.prototype.ClearDataset=function(category)
{
	for (var i = 0; i < this.collection.getCount(); i++)
	{
		var ds = this.collection.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
			ds.LoadData("<xml/>");
	}
}
data_DataStore.prototype.SelectSingleItem=function(category, id)
{
	for (var i = 0; i < this.collection.getCount(); i++)
	{
		var ds = this.collection.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
		{
		var xItem = this.collection.GetByIndex(i).GetItemCopy(id);
		if (xItem != null)
			return xItem;
	}
	}
	return null;
}
data_DataStore.prototype.MarkItemSelected = function(db, id, sel, exclusive, invert, extendedms, cb_selection) 
{	
	// [AL] check whether this is original event (Firefox triggers repeated event for row selection despite cancelBubble)
	if(cb_selection&&cb_selection!=true&&cb_selection.srcElement&&typeof(cb_selection.srcElement.tagName)!="undefined")
	{	
		var srcElementName = cb_selection.srcElement.tagName.toLowerCase();
		if(srcElementName.length>=5&&srcElementName.substring(0, 5)=="input")
			return;
	}
	
	var ds = this.GetDataset(db);	
	
	//AL: Store user selected items for emailling in local storage
	var itemToSel = ds.Get(id);
	if (ds.DoesSupportPseudoMultiSelection && ds.DoesSupportPseudoMultiSelection(itemToSel)
		&& 	itemToSel.xdata.xdoc.xmlDoc.nodeName != "ContainerItem")
	{		
		var key = db.toString() + itemToSel.GetItemID();
		if (itemToSel == null)
			return;
		var attr = itemToSel.IsSelected();
		var node = ds.GetItemSelectedStatus(itemToSel);
		if (node == null)
			return;

		node = node.toUpperCase() == "TRUE" ? true : false;		
		// Expand new item. Clear storage and add new one. attr=true node=false
		if (cb_selection!=true || (!attr && node /* [AL] && eventObject && !eventObject.ctrlKey*/)) 
		{
			// APL: prevent clicking on header already selected item
			if(this.selectedItemsForEmailing.Get(key) == null)
			{	
				// Clear collection with selected items and call TouchItem
				var idToTouch = [];
				for(var i=0; i<this.selectedItemsForEmailing.getCount(); i++)
				{
					// Store ids
					var xClearItemID = this.selectedItemsForEmailing.GetByIndex(i).GetItemID();
					idToTouch.push(xClearItemID);					
				}				
				this.selectedItemsForEmailing.Clear();
				
				// Touch
				for(var i=0; i<idToTouch.length; i++)
				{
					var xTouchItem = ds.Get(idToTouch[i]);
					xTouchItem.SetAttributeValue("selected", "false");
					ds.SetItemSelectedStatus(xTouchItem, false);				
				}
						
				// Remove selected attribute
				if(!attr==true)
					this.selectedItemsForEmailing.Add(key, ds.CreateItem(itemToSel.GetXml()), true);
			}
		}
		// Add to storage attr=true node=true
		else if (!attr /*&& node*/ /* [AL] eventObject && eventObject.ctrlKey*/)
			this.selectedItemsForEmailing.Add(key, ds.CreateItem(itemToSel.GetXml()), true);
		// Delete from storage
		else 
		{
			var index = this.selectedItemsForEmailing.GetIndexByKey(key);
			if (index >= 0)
				this.selectedItemsForEmailing.Delete(key);
		}
	}			
	
	var item = ds.Get(id);
	sel = (invert == true && item != null) ? !item.IsSelected() : sel;
	if (item == null || !item.IsSelectable() || (item.IsSelected() == sel && exclusive))
		return;
	if (ds.needDropSelection)
	{
		for (var i = 0; i < this.collection.getCount(); i++)
		{
			if (this.collection.GetKeyByIndex(i) != db)
			{	
				// only one dataset with keyword(the main purpose of keywords to make group operation)
				// can be selected. So all other dropped.
				if ( !str_IsStringEmpty(this.collection.GetByIndex(i).keywords) && this.collection.GetByIndex(i).needDropSelection)
				{
					// AL: Fix Bug #48: NL name selection gets lost if expend headline
					// clear only one DataSet which name was posted to function
					if(this.collection.GetByIndex(i).name==db)
					{
						this.collection.GetByIndex(i).ClearSelection();
						this.selectedItems.Delete(this.collection.GetKeyByIndex(i));
					}
				}
				continue;
			}
			// APL: Added cb_selection!=undefined - support multiple selection in Advanced search topic grid
			this.ChangeSelectionInternal(this.collection.GetByIndex(i), id, sel, exclusive||(cb_selection!=true&&cb_selection!=undefined), extendedms);
		}
	}
	else
		this.ChangeSelectionInternal(ds, id, sel, exclusive, extendedms);					
}
data_DataStore.prototype.ClearSelectedItemsForEmailing = function()
{
	this.selectedItemsForEmailing.Clear();
}
data_DataStore.prototype.ChangeItemAttribute = function(dsName, id, name, value)
{
	var ds = this.GetDataset(dsName);
	var xItem = ds.Get(id);
	//xItem.SetNodeValue("@"+name, value.toString());	
	xItem.SetAttributeValue(name, value.toString());
	return xItem;
}

data_DataStore.prototype.ChangeSelectionInternal=function(dsCollection, id, sel, exclusive, extendedms)
{
	if (sel == true)
		this.selectedItems.Add(dsCollection.name, dsCollection);
	dsCollection.SelectItemById(id, sel, exclusive, extendedms);
	if (sel == false && dsCollection.HasSelection() == false)
		this.selectedItems.Delete(dsCollection.name);
		
}
data_DataStore.prototype.DropDatasetSelections=function(dsName)
{
	var dsCollection = this.selectedItems.Get(dsName);
	if (dsCollection == null)
		return;
	dsCollection.ClearSelection();
	this.selectedItems.Delete(dsName);
}
data_DataStore.prototype.GetSelectedItem=function(category)
{
	var xItem = null;
	for (var i = 0; i < this.selectedItems.getCount(); i++)
	{
		var ds = this.selectedItems.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
		{
			xItem = this.selectedItems.GetByIndex(i).GetSelectedItemCopy();
			if (xItem != null && this.selectedItems.GetByIndex(i).needDropSelection)
				return xItem;
		}
	}
	return xItem;
}
data_DataStore.prototype.GetSelectedCount=function(category)
{
	for (var i = 0; i < this.selectedItems.getCount(); i++)
	{
		var ds = this.selectedItems.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
		return this.selectedItems.GetByIndex(i).GetSelectedCount();
	}
	return 0;
}
data_DataStore.prototype.GetSelectedCountForEmailing=function()
{
	if(this.selectedItemsForEmailing!=null)
		return this.selectedItemsForEmailing.getCount();
	return 0;
}
data_DataStore.prototype.GetSelectedItems=function(category)
{
	for (var i = 0; i < this.selectedItems.getCount(); i++)
	{
		var ds = this.selectedItems.GetByIndex(i);
		if (ds.IsAllowedOperation(category) == true)
		{
		var xCollect= this.selectedItems.GetByIndex(i).GetSelectedItemsCopy();
		if (xCollect != null)
			return xCollect;
	}
	}
	return null;
}
data_DataStore.prototype.GetSelectedItemsForEmailing=function()
{
	return this.selectedItemsForEmailing;
}

var data_DataStoreCollection = new data_DataStore();
function data_RegisterDataset(name, xml, itemIDQuery, itemQuery, commandMapping, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection)
{
	return data_DataStoreCollection.RegisterDataset(name, xml, itemIDQuery, itemQuery, commandMapping, storage, sortedby, limit, keywords, dynamicGroupsCreator, groupsDSName, events, needDropSelection);
}
function data_GetDataset(name)
{
	return data_DataStoreCollection.GetDataset(name);
}

function data_SetDatasetData(name, xml, st)
{
	data_DataStoreCollection.SetDatasetData(name, xml, st);
}

function data_DestroyDataset(name)
{
	data_DataStoreCollection.DestroyDataSet(name);
}

function data_ClearDataset(category)
{
	data_DataStoreCollection.ClearDataset(category);
}

function data_UpdateDatasetRecord(category, command, data)
{
	
	data_DataStoreCollection.UpdateDatasetRecord(category, command, data);
}

function data_ChangeItemProperty(dsName, xItem, name, val)
{
	xItem.SetNodeValue(name, val);
	data_DataStoreCollection.UpdateDatasetRecord(dsName, "update", xItem.GetXml());
}

function data_ChangeItemAttribute(dsName, id, name, val)
{
	var xItem = data_DataStoreCollection.ChangeItemAttribute(dsName, id, name, val);
	data_DataStoreCollection.UpdateDatasetRecord(dsName, "update", xItem.GetXml());
}

function data_AddDSItem(dsName, xItem)
{
	data_DataStoreCollection.UpdateDatasetRecord(dsName, "add", xItem.GetXml());
}

function data_UpdateDSItem(dsName, xItem)
{
	data_DataStoreCollection.UpdateDatasetRecord(dsName, "update", xItem.GetXml());
}

function data_DeleteDSItem(dsName, xItem)
{
	data_DataStoreCollection.UpdateDatasetRecord(dsName, "delete", xItem.GetXml());
}

function data_DeleteDSItemByID(dsName, id)
{
	data_DataStoreCollection.DeleteItemByID(dsName, id);
}

function data_GetDatasetRecordByIndex(dsName, idx)
{
	return data_DataStoreCollection.GetDatasetRecordByIndex(dsName, idx);
}

function data_SelectSingleItem(category, id)
{
	return data_DataStoreCollection.SelectSingleItem(category, id);
}

function data_GetDatasetItem(ds, id)
{
	return data_SelectSingleItem(ds,id);
}

function data_GetSelectedCount(category)
{
	return data_DataStoreCollection.GetSelectedCount(category);
}

function data_GetSelectedItem(category)
{
	return data_DataStoreCollection.GetSelectedItem(category);
}

function data_GetSelectedItems(category)
{
	return data_DataStoreCollection.GetSelectedItems(category);
}

function data_GetSelectedItemsForEmailing()
{
	return data_DataStoreCollection.GetSelectedItemsForEmailing();
}

function data_MarkItemSelected(db, id, state, exlusive, invert, extendedms, cb_selection)
{
	data_DataStoreCollection.MarkItemSelected(db, id, state, exlusive, invert, extendedms, cb_selection);
}

function data_DropDatasetSelections(dsName)
{
	data_DataStoreCollection.DropDatasetSelections(dsName);
}

function data_attachEvent(evt, func)
{
	return data_DataStoreCollection.attachEvent(evt, func);
}
function data_detachEvent(evt, id)
{
	return data_DataStoreCollection.detachEvent(evt, id);
}

function data_parseDataUpdateXml(name, xml){
	return data_parseDataUpdateXmlInternal(name, xml, data_parseModuleMetaInfoXml, data_SetRequestStatus, data_SetDatasetData);
}

function data_parseDataUpdateXmlInternal(name, xml, parseModuleMetaInfoHandler, setStatusHandler, setDatasetDatHandler){
	var xmlDoc = new Xml.NodeAccessor(xml);
	if (xmlDoc.xmlDoc.parseError.errorCode != 0){
		setStatusHandler(name, DE_STATUS_ERROR, "Unidentified System Error.", cmn_htmlEncode(xmlDoc.GetXml()));
		return null;
	}
	
	var statusText = parseModuleMetaInfoHandler(xmlDoc.GetXmlDocument());
	var dsName = null;
	var dataSection = xmlDoc.SelectSingleNode("//Data");
	var data = null;
	if (dataSection != null){
		dsName = dataSection.attributes.getNamedItem("DSName");
		if (dataSection.firstChild != null)
			data = dataSection.firstChild.xml;
		else
			data = "<xml></xml>";	// SCH: rewrite this
	}

	// Status section processing
	var statusSection = xmlDoc.SelectSingleNode("//Status");
	if (statusSection && statusSection.selectSingleNode("code").text == StatusCode.ERROR){
		setStatusHandler(dsName != null?dsName.text:name, DE_STATUS_ERROR, statusSection.selectSingleNode("errMsg").text);
		return dsName&&dsName.text || name;
	}
	if (dsName!= null)
		setDatasetDatHandler(dsName.text, data, statusText);
	return dsName&&dsName.text || name;
}

function data_SetRequestStatus(dsName, staus, errorMsg, serverErrorMsg){
	var ds = data_GetDataset(dsName);
	if (ds != null)
		ds.ChangeStatus(new dynamicStatusInfo(staus, errorMsg));
	else
		alert(errorMsg);
	ErrorToServer(serverErrorMsg||errorMsg);
}

function data_parseModuleMetaInfoXml(xml)
{
	var minfo = data_MetaInfoXml2Obj(xml);
	if(minfo.MetaInfo != null){
		StartTimeLog("Processing metainfo for module: " + (minfo.ModuleName||"Unknown") );
		nav_ChangeModuleSettingsBatch(minfo.ModuleName, minfo.MetaInfo, true);
		EndTimeLog();
	}
	return minfo.StatusText;
}

function data_MetaInfoXml2Obj(xml)
{
	var xmlDoc = new Xml.NodeAccessor(xml), result = {StatusText:null, MetaInfo:null, ModuleName:null};
	var metaSection = xmlDoc.SelectSingleNode("//MetaInfo");
	if (metaSection != null){
		var moduleNameNode = metaSection.selectSingleNode("ModuleName");
		result.ModuleName = moduleNameNode.text;
		var itemCountNode = metaSection.selectSingleNode("ItemCount");
		var totalItemCountNode = metaSection.selectSingleNode("TotalItemCount");
		// paging parameters processing	
		var hasNextPageNode = metaSection.selectSingleNode("HasNextPage");
		var pageNumberNode = metaSection.selectSingleNode("PageNumber");
		var pageRelevanceSortNode = metaSection.selectSingleNode("RelevanceSort");
		var rowsPerPageNode = metaSection.selectSingleNode("RowsPerPage");
		var statusTextNode = metaSection.selectSingleNode("StatusText");
		var pageIdentityNode = metaSection.selectSingleNode("PageIdentity");
		if (moduleNameNode && hasNextPageNode && moduleNameNode.text.length > 0)
			result.MetaInfo = { "HasNextPage": hasNextPageNode.text,
							"PageNumber": pageNumberNode.text,
							"ItemCountReceived": itemCountNode.text,
							"RowsPerPage": rowsPerPageNode.text,
							"PageIdentity": pageIdentityNode.text,
							"TotalItemCount": totalItemCountNode.text,
							"RelevanceSort": pageRelevanceSortNode.text};
		if (statusTextNode != null)
			result.StatusText = statusTextNode.text;
	}
	return result;
}

function data_handleStatusChangeEvent(name, st)
{
	switch (st.status)
	{
		case DE_STATUS_COMPLETE:
			data_parseDataUpdateXml(name, st.statusText);
			break;	
		default:
			data_DataStoreCollection.ChangeDatasetStatus(name, st);
			break;
	}
	return false;
}

function data_SwapSelectedItem(dsSrcName, dsDstName) {

	var xItem = data_GetSelectedItem(dsSrcName);
	
	if (xItem) {
		xItem.MarkSelected(false);
		data_DeleteDSItem(dsSrcName, xItem);
		data_AddDSItem(dsDstName, xItem);
	}
}

function data_createEmptyItem(itemInfo, id)
{
	var xml = "<"+ itemInfo.ItemName + "></"+ itemInfo.ItemName + ">";
	var item = new data_XmlDataItem(xml, data_getItemIdQuery(itemInfo) ,itemInfo.ItemName)	
	return item;
}

function data_getItemIdQuery(itemInfo)
{
	return itemInfo.ItemIDName;	
}

function data_getItemQuery(itemInfo)
{
	return  itemInfo.ItemName;	
}

function data_TouchDataset(dsName){
	var ds = data_GetDataset(dsName);
	if (ds != null)
		ds.Touch();
}

DeclareClass("Data.Helper", null,
{
	CreateCollectionByInfo : [ decl_static, function(info, x)
	{	
		return new data_XmlDataCollection(x, data_getItemIdQuery(info), data_getItemQuery(info));
	}]
	,CreateCollectionByParams : [ decl_static, function(params)
	{
		return new data_XmlDataCollection(params.Xml, params.IdPath, params.ItemQuery, params.CommandMapping,
										params.Name, params.Storage, params.SortedBy, params.Limit);
	}]
	,CreateItemByInfo : [ decl_static, function(info, x)
	{	
		return new data_XmlDataItem(x, data_getItemIdQuery(info));
	}]

});

EventOccurrence = 
{
	BMO : "BeforeMarketOpen",
	AMC : "AfterMarketClose",
	NTS : "NoTimeSpecified",
	TS 	: "TimeSpecified"
};

EventOccurrence.GetShortName = function(name)
{
	var result = null;	
	switch (name) {
		case EventOccurrence.BMO:
			result = "BMO";
			break;
		case EventOccurrence.AMC:
			result = "AMC";
			break;
		case EventOccurrence.NTS:
			result = "NTS";
			break;
		case EventOccurrence.TS:
			result = "TS";
			break;
	}
	return result;	
};

EventOccurrence.GetLongName = function(name)
{
	var result = null;	
	switch (name) {
		case EventOccurrence.BMO:
			result = "Before Market Open";
			break;
		case EventOccurrence.AMC:
			result = "After Market Close";
			break;
		case EventOccurrence.NTS:
			result = "No Time Specified";
			break;
		case EventOccurrence.TS:
			result = "Time Specified";
			break;
	}
	return result;	
};

DeclareNamespace("UI");

DeclareClass("UI.SimpleRenderer", null,
{
	constructor : function(o)
	{
		this.domObject = new dom_DOMObject(o);
	}
	,GetDOMObject : function()
	{
		return this.domObject;
	}
	,AssignObject : function(o)
	{
		this.domObject = new dom_DOMObject(o);
	}
	,SetObjectInnerHtml : function(html)
	{
		this.domObject.Obj().innerHTML = html;
	}
	,SetObjectOuterHtml : function(html)
	{
		var obj = this.domObject.Obj(), tn=obj.tagName.toLowerCase(), 
			span = DOMObjectFactory.CreateTempElement("span");
		if (tn=="tr") 
		{
			span.innerHTML = "<table>" + html + "</table>";
			var row = span.firstChild.rows[0].cloneNode(true);
			obj.parentElement.replaceChild(row, obj);
			this.AssignObject(row);
		} else if (tn=="td") 
		{
			span.innerHTML = "<table><tr>" + html + "</tr></table>";
			var cell = span.firstChild.rows[0].cells[0].cloneNode(true);
			obj.parentElement.replaceChild(cell, obj);
			this.AssignObject(cell);
		} else 
		{
			span.innerHTML = html;			
			obj.innerHTML = span.firstChild.innerHTML;
			obj.clearAttributes();
			obj.mergeAttributes(span.firstChild, false);			
		}
	}
});

DeclareClass("UI.SpecialRenderer", null,
{
	Render : [decl_static, function(obj)
	{
		if (!obj) return null;
		//StartTimeLog("UI.SpecialRenderer.Render", LOGCT_RENDERING);
		var uiObjects = dom_getElementsByTagNameNS(obj,"ui","uiObject");
		if (uiObjects != null && uiObjects.length > 0)
		{
			var arObj = {},
				rnd = UI.SpecialRenderer;
			for(var i=0,ic=uiObjects.length;i<ic;++i) 
			{
				var domObject = new dom_DOMObject(uiObjects[i]);
				var uiObjType = domObject.getAttribute("UIObjType");
				if (str_IsStringEmpty(uiObjType))
					uiObjType = "uiObject";
				if (arObj[uiObjType] == null)
					arObj[uiObjType] = [];
				arObj[uiObjType][arObj[uiObjType].length] = domObject;
			}
			for(var i=0; i < UI.SpecialRenderer.ProcessingObject.length; i++)
				UI.SpecialRenderer.ProcessingObject[i].RegisterObjects(arObj[UI.SpecialRenderer.ProcessingObject[i].GetObjectType()], obj);
		}
		//EndTimeLog();
	}]
	,GetUniqueID : [decl_static, function()
	{
		if (UI.SpecialRenderer.__curUniqueID == null) 
			UI.SpecialRenderer.__curUniqueID = 0;
		return ++UI.SpecialRenderer.__curUniqueID;
	}]
	,RegisterProcessingObject : [decl_static, function(obj)
	{
		if (UI.SpecialRenderer.ProcessingObject == null)
			UI.SpecialRenderer.ProcessingObject = [];
		UI.SpecialRenderer.ProcessingObject.push(obj);
	}]
});

DeclareClass("UI.SpecialRenderer.RegisterDatasets", null,
{
	GetObjectType : [decl_static, function()
	{
		return "uiDataSet";
	}]
	,RegisterObjects : [decl_static, function(uiObjects)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		var i = uiObjects.length - 1;
		while(i >= 0)
		{
			var dOb = uiObjects[i--], replace = dOb.getAttribute("Replace"), dsName = dOb.getAttribute("DSName");
			if (replace.toLowerCase() == "true" || data_GetDataset(dsName) == null)
			{
				var dsreg = data_RegisterDataset(dsName, dOb.getAttribute("DS"), dOb.getAttribute("ItemIDQuery"), 
					dOb.getAttribute("ItemQuery"), dOb.getAttribute("CmdMapping"), dOb.getAttribute("DStorage"), 
					dOb.getAttribute("SortedBy"), dOb.getAttribute("DSLimit"), dOb.getAttribute("Keywords"), 
					dOb.getAttribute("DynamicGroupsCreator"), dOb.getAttribute("GroupsDSName"), dOb.getAttribute("Events"))
			}
			dOb.Obj().removeNode();
		}
	}]
});

DeclareClass("UI.SpecialRenderer.RegisterUITemplate", null,
{
	GetObjectType : [decl_static, function()
	{
		return "uiTemplate";
	}]
	,RegisterObjects : [decl_static, function(uiObjects)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		//var i = uiObjects.length - 1;
		while(uiObjects.length > 0)
		{
			var dOb = uiObjects[0], nm = dOb.getAttribute("DSName"), itp = dOb.getAttribute("ItemTemplate"), 
				sit = dOb.getAttribute("SelectedItemTemplate"), git = dOb.getAttribute("GroupItemTemplate"), nit = dOb.getAttribute("NoDataTxtGroupItemTemplate"), tmpl;
			if (itp != null) itp = itp.replace(/\\%/gi,"%");
			if (sit != null) sit = sit.replace(/\\%/gi,"%");
			if (git != null) git = git.replace(/\\%/gi,"%");
			if (nit != null) nit = nit.replace(/\\%/gi,"%");
			if (nm.indexOf("@") == -1)
				tmpl = new UI.TemplateCollectionRender(null, nm, itp, dOb.getAttribute("BeginHtml"), 
					dOb.getAttribute("EndHtml"),  dOb.getAttribute("NoDataText"), sit, git, nit,
					dOb.getAttribute("ItemsSeparator"), dOb.getAttribute("GroupID"), 
					dOb.getAttribute("ChildDSNames"), dOb.getAttribute("OnKeyDownObject"), dOb.getAttribute("EnableAlternate"), dOb.getAttribute("MergerType"));
			else
				tmpl = new UI.XmlTemplateRenderer(null, nm, itp, dOb.getAttribute("BeginHtml"), 
					dOb.getAttribute("EndHtml"), dOb.getAttribute("NoDataText"), dOb.getAttribute("EnableAlternate") );
			//events
			tmpl.attachEvent("onitemsrendered", dOb.getAttribute("onitemsrendered"));
			tmpl.attachEvent("onrendercomplete", dOb.getAttribute("onrendercomplete"));
			tmpl.attachEvent("onkeypressed", dOb.getAttribute("onkeypressed"));
			tmpl.attachEvent("onhiddenrendercomplete", dOb.getAttribute("onhiddenrendercomplete"));
			
		
			var lngt = uiObjects.length;	
			tmpl.obj = uiObjects[0].Obj().parentNode;
			tmpl.Render();
			
			if (nm.indexOf("@") == -1) new UI.TemplateInfo(tmpl.obj, tmpl);
			if (lngt == uiObjects.length) uiObjects.splice(0,1);
			//i--;
		}
	}]
});

DeclareClass("UI.SpecialRenderer.RegisterUIObjects", null,
{
	GetObjectType : [decl_static, function()
	{
		return "uiObject";
	}]
	,RegisterObjects : [decl_static, function(uiObjects,hostRenderer)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		var i = uiObjects.length - 1;
		while(i >= 0)
		{
			var domObject = uiObjects[i--];
			var uiObj = eval('new '+domObject.getAttribute("object")+'('+domObject.getAttribute("params")+')');
			uiObj.obj = domObject.Obj().parentElement;
			uiObj.obj.id = hostRenderer.id + UI.SpecialRenderer.GetUniqueID();
			uiObj.simpleRendering = true;
			uiObj.Render();
		}
	}]
});

DeclareClass("UI.SpecialRenderer.RegisterUIScript", null,
{
	GetObjectType : [decl_static, function()
	{
		return "uiScript";
	}]
	,RegisterObjects : [decl_static, function(uiObjects)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		var i = uiObjects.length - 1;
		while(i >= 0)
		{
			var dOb = uiObjects[i--];
			eval(dOb.getAttribute("script"));
			dOb.Obj().removeNode();
		}
	}]
});

DeclareClass("UI.SpecialRenderer.RegisterDE", null,
{
	GetObjectType : [decl_static, function()
	{
		return "de";
	}]
	,RegisterObjects : [decl_static, function(uiObjects, parentObj)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		var i = uiObjects.length - 1;
		while(i >= 0)
		{
			var dOb=uiObjects[i--], obj = dOb.Obj().nextSibling;
			// TO DO: Viacheslav Kopichev (Memory leak problem)	
			dom_setProperty(obj, "tpl_dynamicElement", new dynamicElement(obj, false));

			if (parentObj && parentObj.server_control && parentObj.server_control.AttachDynamicElement) {
				parentObj.server_control.AttachDynamicElement(obj.tpl_dynamicElement);
			}

			nav_ExecuteCurrentCommandForModule(obj.id);
			obj.tpl_dynamicElement.Init();
			new UI.DynamicElementInfo(obj, obj.tpl_dynamicElement);
			dOb.Obj().removeNode();
		}
	}]
});

UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterDatasets);
UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterUITemplate);
UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterUIObjects);
UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterUIScript);
UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterDE);

DeclareClass("UI.ItemInfo", null,
{ 
	constructor : function (htmlobj, obj)
	{
		if (htmlobj && obj)
		{
			this.htmlobj = htmlobj;
			this.obj = obj;
			// TO DO: Viacheslav Kopichev (Memory leak problem)	
			var iteminfo = dom_getProperty(this.htmlobj, "iteminfo");
			if (!iteminfo || !iteminfo.length)
			{
				iteminfo = [];
				dom_setProperty(this.htmlobj, "iteminfo", iteminfo);
			}
			if (iteminfo.length > 0 && this.obj.id == iteminfo[iteminfo.length-1].obj.id) return;
			iteminfo[iteminfo.length] = this;
		}
	}
	,Dispose : function()
	{
		this.AdditionalDispose();
		var iteminfo = dom_getProperty(this.htmlobj, "iteminfo");
		if (iteminfo)
		{
			for(var i=iteminfo.length-1; i >= 0; --i)
				if (iteminfo[i] == this)
				{
					iteminfo.splice(i,1);
					break;
				}
			if (iteminfo.length == 0)
				dom_setProperty(this.htmlobj, "iteminfo", null);
		}
		this.htmlobj = null;
		this.obj = null;
	}
	,AdditionalDispose : function() { }
});

DeclareClass("UI.TemplateInfo", "UI.ItemInfo",
{ 
	constructor : function(htmlobj, obj)
	{
		this.base(htmlobj, obj);
	}
	,AdditionalDispose : function()
	{
		if (this.obj && this.obj.Dispose)
			this.obj.Dispose();
	}
});

DeclareClass("UI.DynamicElementInfo", "UI.ItemInfo",
{ 
	constructor : function(htmlobj, obj)
	{
		this.base(htmlobj, obj);
	}
	,AdditionalDispose : function()
	{
		if (this.obj && this.obj.Dispose)
			this.obj.Dispose();
		dom_setProperty(this.obj, "tpl_dynamicElement", null);
	}
});

DeclareClass("UI.RenderableObject", null,
{
	constructor : function (id)
	{
		this.id = id;
		this.obj = null;
		this.renderType = "innerHtml";
		this.cancelRendering = false;
		this.events = new cmn_EventContainer();
		this.writeLog = false;
		this.simpleRendering = false;
		this.Listeners = new Utils.EventListenersManager(this);
	}
	,EnsureObject : function()
	{
		if (this.obj != null)
			return this.obj;
		this.obj = document.getElementById(this.id);
	}
	,SetObject : function(obj)
	{
		this.obj = obj;
	}
	,SetObjectInnerHtml : function(html)
	{
		this.EnsureObject();
		if (this.obj != null)
		{
			if (!this.simpleRendering)
				this.DeleteChildren(this.obj, false);
			this.obj.innerHTML = html;
			if (!this.simpleRendering)
				this.DoSpecialRendering();
		}
	}
	,AddHtmlChild : function(child)
	{
		this.EnsureObject();
		if (this.obj != null)
		{
			this.obj.innerHTML = "";
			this.obj.appendChild(child);
			if (!this.simpleRendering)	
				this.DoSpecialRendering();
		}
	}
	,AppendHtmlChild : function(child)
	{
		this.EnsureObject();
		if (this.obj != null)
		{
			this.obj.appendChild(child);
			if (!this.simpleRendering)	
				this.DoSpecialRendering();
		}
	}	
	,SetObjectOuterHtml : function(html)
	{
		this.EnsureObject();
		if (this.obj != null)
		{
			this.DeleteChildren(this.obj, true);
			var tn = this.obj.tagName.toLowerCase(), span = DOMObjectFactory.CreateTempElement("span");
			if (tn == "tr") {
				span.innerHTML = "<table>" + html + "</table>";
				var row = span.firstChild.rows[0].cloneNode(true);
				this.obj.parentElement.replaceChild(row, this.obj);
				this.obj = row;
			} else if (tn == "td") {
				span.innerHTML = "<table><tr>" + html + "</tr></table>";
				var cell = span.firstChild.rows[0].cells[0].cloneNode(true);
				this.obj.parentElement.replaceChild(cell, this.obj);
				this.obj = cell;
			} else {
				span.innerHTML = html;			
				this.obj.innerHTML = span.firstChild.innerHTML;
				this.obj.clearAttributes();
				this.obj.mergeAttributes(span.firstChild, false);			
			}
			if (!this.simpleRendering) 
				this.DoSpecialRendering();
		}
	}
	,SetObjectInnerText : function(txt)
	{
		this.EnsureObject();
		if (this.obj != null)
		{
			this.DeleteChildren(this.obj, false);
			if (this.obj.textContent != null)
				this.obj.textContent = txt;	
			else
				this.obj.innerText = txt;
		}
	}
	,SetIfEmpty : function(txt, isHtml)
	{
		var newTxt = str_IsStringEmpty(txt) ? "" : txt;
		this.EnsureObject();
		var text = (this.obj.textContent == null) ? this.obj.innerText : this.obj.textContent;
		try{text = text.replace(/\n*/g,'');}
		catch(e){};
		if (this.obj != null && str_IsStringEmpty(text) && !str_IsStringEmpty(newTxt))
		{
			if (isHtml == true)
				this.SetObjectInnerHtml(newTxt);
			else
				this.SetObjectInnerText(newTxt);
		}
	}
	,SetTextIfEmpty : function(txt)
	{
		this.SetIfEmpty(txt, false);
	}
	,SetHtmlIfEmpty : function(txt)
	{
		this.SetIfEmpty(txt, true);
	}
	,Render : function()
	{
		this.cancelRendering = false;
		var res = this.RenderInternal();
		if (this.writeLog)
			StartTimeLog("Setting html", LOGCT_RENDERING);
		if (this.cancelRendering != true)
		{
			switch (this.renderType.toLowerCase())
			{
				case "outerhtml":
					this.SetObjectOuterHtml(res);
					break;
				case "innertext":
					this.SetObjectInnerText(res);
					break;
				default:
					this.SetObjectInnerHtml(res);
					break;
			}
		}
		if (this.writeLog) EndTimeLog();
		this.writeLog = false;
		this.OnRenderComplete();
		return res;
	}
	,DeleteChildren : function(obj, delthis)
	{
		if (obj != null)
		{
			var all = obj.all;
			for(var i=0, elem; elem = all[i]; i++)
				if (elem.iteminfo)
					for(var j=elem.iteminfo.length-1; j >= 0; j--)
						elem.iteminfo[j].Dispose();
			if(delthis == true && obj.iteminfo)
				for(var i=obj.iteminfo.length-1; i >= 0; i--)
						obj.iteminfo[i].Dispose();
		}
	}
	,CancelRendering : function()
	{
		this.cancelRendering = true;
	}
	,DoSpecialRendering : function()
	{
		this.EnsureObject();
		if (!this.obj) return null;
		UI.SpecialRenderer.Render(this.obj);
	}
	,OnRenderComplete : function() { }
	,RenderInternal : function()
	{
		this.SetObjectInnerText("Render Internal method should be overriden."); 
	}
	,attachEvent : function(evtname, func)
	{
		if (!str_IsStringEmpty(func))
			this.events.attachEvent(evtname, func);
	}
	,detachEvent : function(evtname, id)
	{
		this.events.attachEvent(evtname, id);
	}
});
// -----------------------
var ui_isWindowRenderered = false;
function ui_onLoadRendering()
{
	if (ui_isWindowRenderered == true)
		return;
	var renderer = new UI.RenderableObject();
	renderer.obj = window.document.body;
	renderer.DoSpecialRendering();
	ui_isWindowRenderered = true;
}
dom_attachEventForObject(window, "load", ui_onLoadRendering);
// -----------------------
DeclareClass("UI.XmlTemplateRendererBase" , "UI.RenderableObject",
{
	constructor : function(id, dataSourceName, itemTemplate, beginHtml, endHtml,noDataText, selectedItemTemplate, groupId, enableAlternate)
	{
		this.base(id);	
		this.itemTemplate = itemTemplate;
		this.enableAlternate = enableAlternate == "true";
		this.selectedItemTemplate = selectedItemTemplate;
		this.beginHtml = beginHtml;
		this.endHtml = endHtml;
		this.statusText = null;
		this.noDataText = noDataText;
		this.groupId = groupId;
		this.dsRef = new Utils.DataSourceEventListener(dataSourceName, this.groupId, this.OnDataSetReadyStateChange, this.OnItemChanged, this.OnItemDeleted, this.OnItemAdded)
		this.Listeners.AddCustomListener(this.dsRef);
	}
	,GetDataSource : function()
	{
		return this.dsRef.GetDataSource();
	}
	,OnItemChanged : function(xItem)
	{
		this.SetCustomData(xItem);
		this.Render();
		this.SetCustomData(null);
	}
	,OnItemDeleted : function(xItem)
	{
	}
	,OnItemAdded : function(xItem)
	{
		this.SetCustomData(xItem);
		this.Render();
		this.SetCustomData(null);
	}
	,OnDataSetReadyStateChange : function(xDs)
	{
		this.statusText = xDs.status.statusText;
		if (xDs.status.status != DE_STATUS_COMPLETE)
		{
			if (str_IsStringEmpty(this.statusText))
			{
				this.statusText = "";
				return;
			}
			this.OnDataSetLoading();
		}
		this.Render();
	}
	,OnDataSetLoading : function()
	{
	}
	,SetCustomData : function(data)
	{
		this.dsRef.SetCustomData(data);
	}
	,GetItemTemplate : function()
	{	
		if (!str_IsStringEmpty(this.itemTemplate) )
			return this.itemTemplate;
		this.EnsureObject();
		if (!this.obj) return null;
		this.itemTemplate = this.obj.ItemTemplate;
		return this.itemTemplate;
	}
	,GetSelectedItemTemplate : function()
	{	
		if (!str_IsStringEmpty(this.selectedItemTemplate))
			return this.selectedItemTemplate;
		return this.GetItemTemplate();
	}
	,GetBeginHtml : function()
	{	
		if (!str_IsStringEmpty(this.beginHtml) )
			return this.beginHtml;
		this.EnsureObject();
		if (!this.obj) return "";
		this.beginHtml = this.obj.BeginHtml;
		return this.beginHtml == null ? "" : this.beginHtml;
	}
	,GetEndHtml : function()
	{	
		if (!str_IsStringEmpty(this.endHtml) )
			return this.endHtml;
		this.EnsureObject();
		if (!this.obj) return "";
		this.endHtml = this.obj.EndHtml;
		return this.endHtml == null ? "" : this.endHtml;
	}
	,RenderInternal : function()
	{	
		if (!this.GetDataSource()) 
		{
			this.statusText = this.dsRef.GetStatusText();
			return str_IsStringEmpty(this.statusText) ? '' : this.statusText;
		}
		return this.GetBeginHtml() + this.RenderData() + this.GetEndHtml();
	}
	,InternalDispose : function()
	{	
		this.events = null;
		this.obj = null;
		this.Listeners.Dispose();
		this.dsRef = null;
	}
	,Dispose : function()
	{	
		this.InternalDispose();
	}
	,RenderData : function() { }
});
// -----------------------------
DeclareClass("UI.XmlTemplateRenderer", "UI.XmlTemplateRendererBase",
{
	constructor : function (id, dataSourceName, itemTemplate, beginHtml, endHtml, separatorHtml, enableAlternate)
	{
		this.base(id, dataSourceName, itemTemplate, beginHtml, endHtml,null, enableAlternate);
		this.xslt_initialized = false;
		this.separatorHtml = separatorHtml;
		this.transformer = null;
		this.idprefix = null;
		this.html = "";
	}
	,RenderData : function()
	{
		var data = this.GetDataSource();
		if (!data) return "";
		if (str_IsStringEmpty(this.id) && this.obj == null)
			this.id = this.GetRenderedID();
		this.InitializeTransformer();
		var xmlDoc = data.GetXmlDocument()
		this.html = (this.transformer != null)?this.transformer.Transform(xmlDoc):this.GetItemTemplate();
		return this.html;
	}
	,InitializeTransformer : function()
	{
		if (this.xslt_initialized == true)
			return;
		var tmpl = this.GetXSLTItemTemplate();
		if (!str_IsStringEmpty(tmpl))
			this.transformer = new Xml.XslTransformer(tmpl);
		this.xslt_initialized = true;
	}
	,GetXSLTItemTemplate : function()
	{
		var res = this.GetItemTemplate();
		if (!str_IsStringEmpty(res) && res.indexOf("<xsl:stylesheet") != -1)
		{
			if (!str_IsStringEmpty(this.separatorHtml) && this.obj && this.obj.parentElement.sep == null)
			{
					var begin = "<xsl:template match=\"/\">";
					var end = "</xsl:template>";
					res = res.replace(begin, "~0<span sep='true'>~1".format(begin, this.separatorHtml))
					res = res.replace(end, "</span>~0".format(end));
			}
			return res;
		}
		return null;
	}
	,SetSeparator : function(separatorHtml)
	{
		if (this.separatorHtml == separatorHtml)
			return;
		this.xslt_initialized = false;
		this.separatorHtml = separatorHtml;
		this.transformer = null;
	}
	,GetRenderedID : function()
	{
		var data = this.GetDataSource();
		if (!data || typeof(data.GetItemID) == "undefined") return "";
		if (this.idprefix == null)
		{
			var tmpl = this.GetItemTemplate();
			var match = tmpl.match(new RegExp("<[^<]*id=.*>", "ig"));
			if (match == null || match.length == 0)
				return "";
			this.idprefix = match[0];
			this.idprefix = this.idprefix.replace(/^<[^<]* id=[\"]+/i, "");
			this.idprefix = this.idprefix.replace(/[\"]+.*>/i, "");	
			this.idprefix = input_HtmlDecode(this.idprefix);
		}
		if (!str_IsStringEmpty(this.idprefix))
			return this.idprefix.replace(/{\$[^{]*}/ig, data.GetItemID())
		return "";
	}
	,GetRenderedHTML : function()
	{
		return this.html;
	}
});
// ------------------------------
DeclareClass("UI.TemplateCollectionRender", "UI.XmlTemplateRendererBase",
{
	constructor : function (id, dataSourceName, itemTemplate, beginHtml, endHtml,noDataText, selectedItemTemplate, groupItemTemplate, noDataTxtGroupItemTemplate, itemsSeparator, groupId, childDSNames, onkeydownobj, enableAlternate, mergerType)
	{
		this.base(id, dataSourceName, itemTemplate, beginHtml, endHtml,noDataText, selectedItemTemplate, groupId, enableAlternate);
		this.itemsSeparator = itemsSeparator;
		this.itemRenderer = null;
		this.selectedItemRenderer = null;
		this.isEventsAttached = false;
		this.firstItemID = null;
		this.htmlrows = null;
		this.merger = null;
		this.mergerType = mergerType;
		this.groupItemTemplate = groupItemTemplate;
		this.noDataTxtGroupItemTemplate = noDataTxtGroupItemTemplate;
		
		
		this.spliter = "<SPAN>SPLITER</SPAN>";
		this.enableLazyRendering = false;
		
		if (!str_IsStringEmpty(this.groupId))
			this.appenderStartItemCount = 1;	
		else
			this.appenderStartItemCount = 25;
			
		this.appenderIncItemCount = 20;
		this.appenderUpdItemCount = 20;
		this.appenderCurrentItem = 0;
		
		this.registredDS = [];
		this.registredDShandles = [];
		this.statusobj = null;
		this.onkeydownobj = null;
		this.timeFunc = null
		this.childDSNames = childDSNames;
		if (this.enableLazyRendering == true)
		{	
			var thisObj = this;
			this.timeFunc = function(){thisObj.AppendLazyItems(thisObj)};
		}
		
		if (!str_IsStringEmpty(onkeydownobj))
			this.onkeydownobj = eval ("new "+onkeydownobj+"(this)");
		this.InitChildrenDSEvents(childDSNames);
	}
	,Dispose : function()
	{	
		UI.QueueRenders.GetQueueRenders().Delete(this.timeFunc);
		this.timeFunc = null;
		if (this.onkeydownobj != null) this.onkeydownobj.Dispose()
		if (this.itemRenderer != null) this.itemRenderer.Dispose();
		if (this.selectedItemRenderer!= null) this.selectedItemRenderer.Dispose();
		for(var i=this.registredDShandles.length-1; i>=0; --i)
			data_detachEvent("ondatasetregistered", this.registredDShandles[i])
		this.DetachChildrenDSEvents();
		this.InternalDispose();
		this.htmlObjs = null;
		this.registredDS = null;;
		this.statusobj = null;
		this.firstItemID = null;
		this.htmlrows = null;
	}
	,GetNoDataText : function()
	{	
		if (this.statusText != null)
			return this.statusText;
		return this.noDataText;
	}
	,InitChildrenDSEvents : function(childDSNames)
	{
		if (str_IsStringEmpty(childDSNames))
			return;
		var names = childDSNames.split(",");
		var thisObj = this;
		for(var i=0,ic=names.length; i<ic; ++i)
		{
			var name = names[i];
			var ds = data_GetDataset(names[i]);
			if (!ds)
				this.registredDShandles.push(data_attachEvent("ondatasetregistered", function(p){thisObj.AttachChildrenDSEvents(p, name, thisObj)}));
			else
				this.AttachChildrenDSEvents(ds, names[i], thisObj);
		}
	}
	,AttachChildrenDSEvents : function(xDs, DSName, thisObj)
	{
		if (xDs.name == DSName && thisObj.isDSRegistred(DSName) == false)
		{
			var id = xDs.attachEvent("onstatuschange", function(p){thisObj.OnChildDataSetReadyStateChange(thisObj, p)} );
			this.registredDS[this.registredDS.length] = {"id" : id, "Name" : DSName};
		}
	}
	,DetachChildrenDSEvents : function()
	{
		for(var i=0,ic=this.registredDS.length; i<ic; ++i)
		{
			var ds = data_GetDataset(this.registredDS[i].Name);
			if (ds != null) ds.detachEvent("onstatuschange", this.registredDS[i].id);
		}
	}
	,isDSRegistred : function(DSName)
	{
		for(var i=this.registredDS.length-1; i>=0; --i)
			if (this.registredDS[i].Name == DSName) return true;
		return false;
	}
	,OnChildDataSetReadyStateChange : function(thisObj, xDs)
	{
		if (xDs.status.status == DE_STATUS_COMPLETE)
		{
			if (xDs.GetCount()==0 && !str_IsStringEmpty(this.GetNoDataText()))
				thisObj.ShowStatusObj(true, this.GetNoDataText());
			else	
				thisObj.ShowStatusObj(false);
		}
		else if (!str_IsStringEmpty(xDs.status.statusText))
			thisObj.ShowStatusObj(true, xDs.status.statusText);
	}
	,ShowStatusObj : function(show, text)
	{
		var statusobj = this.GetStatusObj();
		var dispobj = this.obj;
		if (statusobj != null && dispobj != null)
		{
			if (show == true)
			{
				dispobj.style.display = "none";
				statusobj.style.display = "block";
				statusobj.innerHTML = text;
			}
			else
			{
				statusobj.style.display = "none";
				dispobj.style.display = "block";
			}
		}
	}
	,GetStatusObj : function()
	{
		this.EnsureObject();
		if (this.statusobj != null)
			return this.statusobj;
		else if (this.obj != null)
		{
			this.statusobj = DOMObjectFactory.CreateElement("SPAN");
			this.statusobj.style.dispaly = "none";
			this.obj.parentElement.insertBefore(this.statusobj, this.obj);
			return this.statusobj;
		}
		else
			return null;
	}
	,GetGroupItemTemplate : function()
	{
		return str_IsStringEmpty(this.groupItemTemplate) ? "" : this.groupItemTemplate;
	}
	,GetNoDataTextGroupItemTemplate : function()
	{
		return str_IsStringEmpty(this.noDataTxtGroupItemTemplate) ? "" : this.noDataTxtGroupItemTemplate;
	}
	,RenderData : function()
	{
		if (this.obj != null && this.obj.parentElement == null)
		{
			this.CancelRendering();
			return "";
		}
		if (this.onkeydownobj != null && this.onkeydownobj.isattached == false)
			this.onkeydownobj.Attach();
			
		var firstObj = this.GetFirstItem();
		this.writeLog = true;
		this.appenderCurrentItem = 0;
		if (firstObj != null && this.htmlrows != null && this.htmlrows.length > 0){
			this.merger = eval("new "+(this.mergerType||"UI.TCRDefaultMerger")+"(this.htmlrows, this);");
		}
		else{
			this.merger = null;
			firstObj = null;
		}
		this.CreateHTMLRows();
		return this.RenderItems(!this.merger, firstObj);
		
	}
	,RenderItems : function(isStart, firstObj)
	{
		//------------------------------
		var res = "";
		if (this.htmlrows == null || this.htmlrows.length == 0)
			return res;
		StartTimeLog("Render Items", LOGCT_RENDERING);
		if (this.htmlrows.length == 1)
		{	
			EndTimeLog();
			this.events.fireEvent("onitemsrendered", this);
			return this.htmlrows[0];
		}
		//------------------------------
		//------------------------------
		var itemCountInfo = this.appenderCurrentItem;
		if (isStart)
		{
			this.appenderCurrentItem = this.appenderStartItemCount;
			res = this.htmlrows.slice(0, this.appenderStartItemCount).join('');
		}
		else
		{
			if (firstObj == null)
				firstObj = this.GetFirstItem();
			if (firstObj != null && firstObj.parentElement != null)
			{
				var parentFirstObj = firstObj.parentElement;
				this.CancelRendering();
				var limit = this.merger == null ? this.appenderIncItemCount : this.appenderUpdItemCount;
				limit += this.appenderCurrentItem;
				limit = limit > this.htmlrows.length ? this.htmlrows.length : limit;
				var htmlObjs = this.GetHTMLObjects(firstObj);//parentFirstObj.childNodes;
				if(this.merger)
					this.appenderCurrentItem = this.merger.MergeItems(this.htmlrows, htmlObjs, this.appenderCurrentItem, limit);
				else{
					for(var i= this.appenderCurrentItem; i < limit; i++)
						this.AddHTMLRow(firstObj, parentFirstObj, this.htmlrows[i]);
					this.appenderCurrentItem = limit;
				}

				if(this.appenderCurrentItem >= this.htmlrows.length && this.merger && htmlObjs != null)
					this.SetHtmlIfEmpty(this.GetNoDataText());
			}
		}
		itemCountInfo = this.appenderCurrentItem - itemCountInfo;
		LogInfo( "Render ~0 rows.".format(itemCountInfo), LOGCT_RENDERING);
		//------------------------------
		//------------------------------
		EndTimeLog();
		if (this.appenderCurrentItem < this.htmlrows.length)
			UI.QueueRenders.GetQueueRenders().Add(this.timeFunc);
		else
			this.events.fireEvent("onhiddenrendercomplete", this);
		
		this.events.fireEvent("onitemsrendered", this);
		return res;
		//------------------------------
	}
	,GetHTMLObjects : function(firstObj)
	{
		var res = null;
		if (firstObj == null)
			firstObj = this.GetFirstItem();		
		if (firstObj.parentElement != null);
		{
			res = firstObj.parentElement.childNodes;
			if (!str_IsStringEmpty(this.GetGroupItemTemplate()))
			{
				var tmp = [];
				for(var i = 0; i < res.length; i++)
					if(res[i].getAttribute("isHeaderRow") == null)
						tmp.push(res[i]);
				res = tmp;
			}
		}
		return res;
	}
	,AppendLazyItems : function(thisObj)
	{	
		this.RenderItems(false);
	}
	,AddHTMLRow : function(firstObj, parentFirstObj, html, insertBefore)
	{
		if (firstObj && parentFirstObj)
		{
			var newObj = DOMObjectFactory.CreateElement(firstObj.tagName);
			if(insertBefore || BrowserInfo.IsFF())
				parentFirstObj.insertBefore(newObj, insertBefore);
			else
			{
				//for IE
				parentFirstObj.insertBefore(newObj);
			}
			this.SetHTMLRow(newObj, html);
		}
	}
	,SetHTMLRow : function(obj, html)
	{
		if (!str_IsStringEmpty(html))
		{
			var olddisp = null;
			if (obj != null && !str_IsStringEmpty(this.GetGroupItemTemplate()))
				olddisp = obj.style.display;
			var renderer = this.CreateItemRenderer(null, true);
			renderer.obj = obj;
			renderer.SetObjectOuterHtml(html);
			if (olddisp != null)
				obj.style.display = olddisp;
		}
	}
	,CreateHTMLRows : function()
	{
		var res = "";
		var col = this.GetDataSource(), ids;
		
		if (col != null)
		{
			var logMsg = "Create HTML rows. DSName = " + col.name;
			StartTimeLog(logMsg, LOGCT_RENDERING);
			res = this.GetXSLTransformer(col).Transform(col.GetXmlDocument());
			this.firstItemID = this.CreateItemRenderer(col.GetByIndex(0), false).GetRenderedID();
			LogInfo( "Create rows.", LOGCT_RENDERING);
			EndTimeLog();
			ids = col.GetXmlDocument().selectNodes("//~0/~1".format(col.xdata.itemQuery, col.xdata.idQuery));
		}
		
		this.htmlrows = res.split(new RegExp(this.spliter, "ig"));
		if (this.htmlrows.length > 1 && str_IsStringEmpty(this.htmlrows[this.htmlrows.length-1]))
			this.htmlrows.splice(this.htmlrows.length-1,1);

		var idHash = this.htmlrows.idHash = [];
		var posHash = this.htmlrows.posHash = [];
		for(var i=0, iMax = ids&&ids.length||0 ; i<iMax; i++ ){
			idHash[posHash[i] = ids[i].text] = i;
		}
	}
	,GetXSLTransformer : function(col)
	{
		if (!this.transformer)
		{
			var itemQuery = "//" + col.GetItemName();
			var spliter = this.enableLazyRendering == true? this.spliter : "";
			var templResult = "";
			var templGroupItems = "";
			var templGroupItem = this.GetGroupItemTemplate();
			var templGrouping = "";
			var templNDTGroupItem = "";
			if (!str_IsStringEmpty(templGroupItem))
			{
				templGroupItems = "<xsl:variable name=\"v_Items\" select=\"~0\" />".format(itemQuery);
				templGroupItem = this.PrepareItemTemplate(templGroupItem, itemQuery, "group");
				templGrouping = "<xsl:variable name=\"v_GroupID\" select=\"./@GroupID\" /><xsl:variable name=\"v_Pos\" select=\"position()-1\" /><xsl:if test=\"$v_Pos = -1 or not($v_Items[$v_Pos]/@GroupID = $v_GroupID)\"><xsl:apply-templates select=\".\" mode=\"group\"/>~0</xsl:if>".format(spliter);
				templNDTGroupItem = this.GetNoDataTextGroupItemTemplate();
				if (!str_IsStringEmpty(templNDTGroupItem))
					templNDTGroupItem = this.PrepareItemTemplate(templNDTGroupItem, itemQuery+"[@EmptyItem]");
			}
			var templItem = this.PrepareItemTemplate(this.GetItemTemplate(),itemQuery + "[not(@selected) or not(@selected='true')]");
			var templSelItem = this.PrepareItemTemplate(this.GetSelectedItemTemplate(),itemQuery + "[@selected='true']");
			
			var templMain ="<xsl:template match=\"/\">~3<xsl:for-each select=\"~0\">~1 ~2</xsl:for-each></xsl:template>";
			var templWithSeparator = "<xsl:choose><xsl:when test=\"not (position()=1)\"><span sep='true'>~0~2</span>~1</xsl:when><xsl:otherwise>~2~1</xsl:otherwise></xsl:choose>";
			var templWithoutSeparator = "~1~0";
			
			var templCall = "<xsl:apply-templates select=\".\"/>";
			if (this.enableAlternate)
				templCall = "<xsl:choose>" +
								"<xsl:when test=\"position() mod 2 = 0\">" +
									"<xsl:apply-templates select=\".\">" +
										"<xsl:with-param name=\"p_alternate\">even_row</xsl:with-param>" +
									"</xsl:apply-templates>" +
								"</xsl:when> " +
								"<xsl:otherwise>" +
									"<xsl:apply-templates select=\".\">" +
										"<xsl:with-param name=\"p_alternate\">not_even_row</xsl:with-param>" +
									"</xsl:apply-templates>" +
								"</xsl:otherwise>" +
							"</xsl:choose>";
			
			var templRow = str_IsStringEmpty(this.GetItemsSeparator()) ? templWithoutSeparator.format(spliter, templCall) : templWithSeparator.format(this.GetItemsSeparator(), spliter, templCall);
			
			templResult += templMain.format(itemQuery, templGrouping, templRow, templGroupItems);
			templResult += templItem;
			templResult += templSelItem;
			templResult += templGroupItem;
			templResult += templNDTGroupItem;
			
			templResult = this.GetItemTemplate().replace(/<xsl:template[\s\S]*<\/xsl:template>/ig, templResult);
			
			this.transformer = new Xml.XslTransformer(templResult);
		}
		return this.transformer;
	}
	,PrepareItemTemplate : function(templ, itemQuery,  mode)
	{
		if (!str_IsStringEmpty(templ))
		{
			templ = templ.match(/<xsl:template[\s\S]*<\/xsl:template>/ig)[0];
			templ = templ.replace("<xsl:template match=\"/\">", "<xsl:template match=\"~0\" ~1 >".format(itemQuery, str_IsStringEmpty(mode) ? "" : "mode='"+mode+"'"));
			templ = templ.replace(new RegExp("(select=\")//([^\"]*\" />)", "gi"), "$1$2");
		}
		return templ;
	}
	,GetFirstItem : function()
	{
		return this.GetItemByID(this.firstItemID);
	}
	,GetItem : function(xItem)
	{
		return this.GetItemByID(this.CreateItemRenderer(xItem, xItem.GetIndex()>0).GetRenderedID());
	}
	,GetItemByID : function(rendererID)
	{
		if (!str_IsStringEmpty(rendererID))
			return $(rendererID);
		return null;
	}
	,GetItemIndex : function(xItem)
	{
		var item = this.GetItem(xItem);
		if (!item) return -1;
		if (typeof(item.rowIndex) != "undefined" && str_IsStringEmpty(this.GetGroupItemTemplate()))
			return item.rowIndex;
		var i=0;
		while(item.previousSibling != null)
		{
			item = item.previousSibling;
			if (item.getAttribute == null || (item.getAttribute("isGroupRow") == null && item.getAttribute("isHeaderRow") == null))
				++i;
		}
		return i;
	}
	,GetRealItemIndex : function(xItem)
	{
		var idx = xItem.GetIndex();
		if (!str_IsStringEmpty(this.GetGroupItemTemplate()))
		{
			var grid = xItem.GetGroupID();
			var firstObj = this.GetFirstItem();
			if (firstObj != null && firstObj.parentElement != null)
			{
				var childs = firstObj.parentElement.childNodes;
				if (childs.length < idx)
					idx = childs.length;
				else
				{
					var tmp = idx;
					for(var i=0; i < childs.length; i++)
					{
						idx = i;
						if (childs[i].getAttribute("isGroupRow") == null)
							tmp --;
						if (tmp ==0)	
						{
							break;
						}
					}
				}
			}
		}
		return idx;
	}
	,KeyDown : function(keyCode,dataSet,xItem)
	{
		this.events.fireEvent("onkeypressed", keyCode, dataSet, xItem);
	}
	,GetItemsSeparator : function()
	{
		if (!str_IsStringEmpty(this.itemsSeparator))
			return this.itemsSeparator;
		return null;
	}
	,CreateItemRenderer : function(xItem, needrendsep)
	{
		var renderer = (xItem != null && xItem.IsSelected())?this.GetSelectedItemRenderer():this.GetItemRenderer();
		if (needrendsep == true)
			renderer.SetSeparator(this.GetItemsSeparator());
		else
			renderer.SetSeparator(null);
		renderer.SetCustomData(xItem);
		return renderer;
	}
	,GetItemRenderer : function()
	{
		if (this.itemRenderer != null)
		{
			this.itemRenderer.id=null;
			this.itemRenderer.obj=null;
			return this.itemRenderer;
		}
		this.itemRenderer = new UI.XmlTemplateRenderer(null, null, this.GetItemTemplate(), null)
		this.itemRenderer.renderType = "outerHTML";
		return this.itemRenderer;
	}
	,GetSelectedItemRenderer : function()
	{
		if (this.selectedItemRenderer != null)
		{
			this.selectedItemRenderer.id=null;
			this.selectedItemRenderer.obj=null;
			return this.selectedItemRenderer;
		}
		this.selectedItemRenderer = new UI.XmlTemplateRenderer(null, null, this.GetSelectedItemTemplate(), null)
		this.selectedItemRenderer.renderType = "outerHTML";
		return this.selectedItemRenderer;
	}
	,MoveItem : function(oldidx, newidx)
	{
		var firstObj = this.GetFirstItem();
			if (firstObj && firstObj.parentElement)
			{
				var parent = firstObj.parentElement;
				if (parent.childNodes.length <= oldidx)
					return false;
				
				var child = parent.removeChild(parent.childNodes[oldidx]);
				if (newidx >= parent.childNodes.length)
					parent.insertBefore(child);
				else
					parent.insertBefore(child, parent.childNodes[newidx]);
				
				if (this.htmlrows != null && this.htmlrows.length > oldidx)
					this.htmlrows = this.htmlrows.move(oldidx, newidx);
				
				return true;
			}
		return false;	
	}
	,OnDataSetLoading : function()
	{
		UI.QueueRenders.GetQueueRenders().Delete(this.timeFunc);	
	}
	,OnRenderComplete : function()
	{
		this.events.fireEvent("onrendercomplete", this);
		if (!this.GetFirstItem()) this.SetHtmlIfEmpty(this.GetNoDataText());
	}
	,OnItemChanged : function(xItem)
	{
		var realtobj = null;
		var idx = this.GetItemIndex(xItem);
		if (idx != -1 && idx != xItem.GetIndex())
		{
			this.MoveItem(idx, xItem.GetIndex());
			realtobj = this.GetFirstItem();
		}
		idx = xItem.GetIndex();
		
		var renderer = this.CreateItemRenderer(xItem, idx>0);
		var oldobj = this.GetItemByID(renderer.GetRenderedID());
		var olddisp = null;
		if (oldobj != null && !str_IsStringEmpty(this.GetGroupItemTemplate()))
			olddisp = oldobj.style.display;
		renderer.Render();
		if (renderer.obj != null && olddisp != null)
			renderer.obj.style.display = olddisp;
		
		if (this.htmlrows != null)
		{
			var htmlidx = 0;
			if(str_IsStringEmpty(this.GetGroupItemTemplate()))
				htmlidx = idx;
			else
			{
				var item = renderer.obj;
				while(item = item.previousSibling)
					if (item.getAttribute("isHeaderRow") == null)
						++htmlidx;
			}
			if(this.htmlrows.length > htmlidx)
				this.htmlrows[htmlidx] = renderer.GetRenderedHTML();
		}
		
		if (this.onkeydownobj != null && xItem.IsSelected())
		{
			try {this.obj.setActive();}
			catch(e){}
		}
		this.ReAlternate(realtobj);	
	}
	,OnItemDeleted : function(xItem)
	{
		var hasSeparator = this.GetItemsSeparator() != null;
		var idx = this.GetItemIndex(xItem);
		var obj = this.GetItem(xItem);
		if (hasSeparator == true )
		{
			if (obj.parentElement.getAttribute("sep") == 'true')
				obj = obj.parentElement;
			else if (obj.nextSibling != null)
				obj.parentElement.replaceChild(obj.nextSibling.children[0], obj.nextSibling);
		}
		if (obj == null)
			return;
		var realtobj = obj.nextSibling;
		this.DeleteChildren(obj, true);
		dom_RemoveNode(obj, true);
		this.htmlrows.remove(idx);
		this.ReAlternate(realtobj);
		this.SetHtmlIfEmpty(this.GetNoDataText());
		if (xItem.GetIndex() == 0 && this.GetDataSource() != null && this.GetDataSource().GetCount() > 0)
			this.firstItemID = this.CreateItemRenderer(this.GetDataSource().GetByIndex(0), false).GetRenderedID();
	}
	,OnItemAdded : function(xItem)
	{
		var firstObj = this.GetFirstItem();
		if (firstObj == null)
		{
			this.Render();
			return;
		}
		var newObj = DOMObjectFactory.CreateElement(firstObj.tagName);
		var childNode = null;
		var idx = this.htmlrows.length;
		if (xItem.GetIndex() != null && firstObj.parentElement.childNodes.length > xItem.GetIndex() )
		{
			idx = this.GetRealItemIndex(xItem);
			childNode = firstObj.parentElement.childNodes[idx];
		}
		firstObj.parentElement.insertBefore(newObj,childNode);
		var renderer = this.CreateItemRenderer(xItem, true);
		renderer.obj = newObj;
		renderer.Render();	
		this.htmlrows.insert(renderer.GetRenderedHTML(), idx);
		this.ReAlternate(childNode != null ? childNode.nextSibling : firstObj.parentElement.childNodes[firstObj.parentElement.childNodes.length - 1]);
		this.events.fireEvent("onrendercomplete", this);
	}
	,ReAlternate : function (obj)
	{
		if (this.enableAlternate && obj != null)
		{
			//TODO : VK - must be implemented.
		}
	}
});

DeclareClass("UI.TCRMergerBase", null,{
	constructor: function(sourceRows, renderer){
		this.sourceRows = sourceRows;
		this.Renderer = renderer;
		this.parentObj = renderer.GetFirstItem().parentElement;
	}
	,InsertRow: function(row, insertBefore){
		this.Renderer.AddHTMLRow(this.parentObj.firstChild, this.parentObj, row, insertBefore);
	}	
	,MergeItems : [decl_virtual, function(newRows, startIndex, endIndex){
	
	}]
});

DeclareClass("UI.TCRDefaultMerger", "UI.TCRMergerBase",{
	MergeItems : [decl_virtual, function(newRows, tableRows, startIndex, endIndex){
		for(var i=startIndex; i < endIndex; i++){
			if (tableRows.length > i){
				if (this.sourceRows.length <= i || newRows[i] != this.sourceRows[i])
					this.Renderer.SetHTMLRow(tableRows[i], newRows[i]);
				else if (endIndex < newRows.length)
					endIndex++;
			}
			else
				this.InsertRow(newRows[i]);
		}
		
		// Remove useless rows after the hidden rendering
		if(endIndex >= newRows.length && tableRows != null)
			for(var j=tableRows.length-1; j >= endIndex; j--)
				dom_RemoveNode(tableRows[j], true);
		return endIndex;
	}]
});

DeclareClass("UI.TCRExtendedMerger", "UI.TCRMergerBase",{
	InsertRow: function(insertBefore){
		var row = this.tmpTable.firstChild;
		if(insertBefore)
			this.parentObj.insertBefore(row,insertBefore);
		else
			this.parentObj.insertBefore(row);
		UI.SpecialRenderer.Render(row);
	}
	,CreateDomTmp: function(items){
		var span = DOMObjectFactory.CreateElement("span");  
		span.innerHTML = "<table>" + items.join("") + "</table>";
		this.tmpTable = span.firstChild.firstChild;
	}
,GenerateMergeActions: function(newRows, currentRows){
		StartTimeLog("GenerateMergeActions", "Alerts");
		var shiftIndex =0, OldPosition = 0;
		var actions = [];
		var insertrows = [];
		var delCnt=0, insCnt=0, ovrCnt=0;
		for(var i= 0, iMax = newRows.length; i < iMax; i++){
			var oldRowPos = this.sourceRows.idHash == null ? null : this.sourceRows.idHash[newRows.posHash[i]];
			if(oldRowPos == null){
				actions.push({action:'i', idx:i});
				insertrows.push(newRows[i]); //insert
				shiftIndex++;
				insCnt++;
				continue;
			}
			if(OldPosition < oldRowPos ){
				for(var j = OldPosition; j<oldRowPos; j++){
					actions.push({action:'d', idx: j + shiftIndex}); //remove
					shiftIndex--;
					delCnt++;
				}
			}
			
			if(this.sourceRows[oldRowPos] != newRows[i]){
				actions.push({action:'o', idx:i}); //overwrite
				ovrCnt++;
			}
			
			OldPosition = oldRowPos+1;
		}
		
		// Number of nodes need to be remove at the end of list
		actions.RemoveLastNItems = this.sourceRows.length - OldPosition;
		delCnt += actions.RemoveLastNItems;
		if(insertrows.length>0){
			this.CreateDomTmp(insertrows);
		}
		EndTimeLog();
		LogInfo("Delete actions = ~0; Insert actions = ~1; Overwrite actions = ~2".format(delCnt, insCnt, ovrCnt), "Alerts");
		return actions;
	}
	,MergeItems : [decl_virtual, function(newRows, tableRows, startIndex, endIndex){

		if(!this._mergeActions){
			// Generate llist of actions to merge
			this._mergeActions = this.GenerateMergeActions(newRows);
			this.itemsDiff =0;
		}
		//Detect number of actions to execute
		//var stepsLeft = (newRows.length - startIndex)/(endIndex-startIndex);
		//var actionsToExec = (this._mergeActions.length + this._mergeActions.RemoveLastNItems)/ stepsLeft;
		var actionsToExec = endIndex - startIndex;
		
		var actionIndex = 0;
		while( actionIndex < actionsToExec ){
			var item = this._mergeActions.shift();
			if(item)
				if(item.action == 'i'){ // insert
					this.InsertRow(tableRows[item.idx]);
					this.itemsDiff++;
					actionIndex++;
				}
				else if(item.action == 'd'){
					dom_RemoveNode(tableRows[item.idx], true); // delete
					this.itemsDiff--;
					actionIndex++
				}else{
					this.Renderer.SetHTMLRow(tableRows[item.idx], newRows[item.idx]);
					actionIndex++;
				}

			if((item && this.itemsDiff>0 || item==null) && this._mergeActions.RemoveLastNItems>0){
				dom_RemoveNode(tableRows[tableRows.length-1], true);
				this.itemsDiff--;
				actionIndex++;
				this._mergeActions.RemoveLastNItems--;
			}
			if(item == null && this._mergeActions.RemoveLastNItems == 0){
				endIndex = newRows.length;
				break;
			}
		}
		if(this.tmpTable != null && this.tmpTable.rows.length == 0)
			this.tmpTable = null;
		return endIndex;
	}]
});

DeclareClass("UI.UpDownSelector", null,
{
	constructor : function (renderer)
	{
		this.renderer = renderer;
		this.isattached = false;
		this.OnKeyDownHandler = this.CreateCallback(this.OnKeyDown);
	}
	,Attach : function()
	{
		if (this.renderer && this.renderer != null && this.renderer.obj && this.renderer.obj != null)
		{
			dom_attachEventForObject(this.renderer.obj, "keydown", this.OnKeyDownHandler);
			this.isattached = true;
		}
	}
	,Dispose : function()
	{
		dom_detachEventForObject(this.renderer.obj, "keydown", this.OnKeyDownHandler);
		this.renderer = null;
	}
	,OnKeyDown : function()
	{
		if (this.renderer != null)
		{
			var ds = this.renderer.dsRef.GetDataSource();
			if (ds != null)
			{
				var curritem = ds.GetSelectedItemCopy();				
				this.renderer.KeyDown(event.keyCode,ds,curritem);
				if (curritem != null)
					this.OnKeyDownInternal(ds,curritem);
			}
		}
	}
	,OnKeyDownInternal : [decl_virtual, function(ds,curritem)
	{
		if (event.keyCode == 40 || event.keyCode == 38)
		{
			var idx = ds.GetIndexById(curritem.GetItemID());
			if( event.keyCode == 40	)
				++idx;
			else
				--idx;
			if (idx < 0 || idx > ds.GetCount())
				return;
			var aid = ds.GetIdByIndex(idx);
			if (aid != null)
			{
				data_MarkItemSelected(ds.name, aid, true, true);
				var row = this.renderer.GetItem(ds.Get(aid));
					if (row && row != null)
						dom_scrollIntoView(row, event.keyCode == 38);
				
				event.cancelBubble = true;
				event.returnValue = false;
			}
		}
	}]
});

DeclareClass("UI.PopupUpDownSelector", "UI.UpDownSelector",
{
	constructor : function (renderer)
	{
		this.base(renderer);
	}
	,OnKeyDownInternal : [decl_virtual, function(ds,curritem)
	{
		if (event.keyCode == 40 || event.keyCode == 38)
		{					
			var idx = ds.GetIndexById(curritem.GetItemID());
			if( event.keyCode == 40	)
				++idx;
			else
				--idx;
			if (idx >= 0 && idx < ds.GetCount())
			{
				var aid = ds.GetIdByIndex(idx);
				if (aid != null)
					data_MarkItemSelected(ds.name, aid, true, true);
			}
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}]
});

DeclareClass("UI.ShiftSelector", null,
{
	constructor : function (renderer)
	{
		this.renderer = renderer;
		this.isattached = false;
		this.ds = renderer.dsRef.GetDataSource();
	}
	,Attach : function()
	{
		if (this.renderer && this.renderer.obj)
		{
			dom_attachEventForObject(this.renderer.obj, "keydown", this.OnKeyDownHandler = this.OnKeyDown.bind(this));
			dom_attachEventForObject(this.renderer.obj, "click", this.OnMouseClickHandler = this.OnMouseClick.bind(this));
			dom_attachEventForObject(this.renderer.obj, "dblclick", this.OnMouseDblClickHandler = this.OnMouseDblClick.bind(this));
			this.isattached = true;
		}
	}
	,Dispose : function()
	{
		dom_detachEventForObject(this.renderer.obj, "keydown", this.OnKeyDownHandler);
		dom_detachEventForObject(this.renderer.obj, "click", this.OnMouseClickHandler);
		dom_detachEventForObject(this.renderer.obj, "dblclick", this.OnMouseDblClickHandler);
		this.renderer = this.ds = null;
	}
	,StartSelection: [decl_virtual, function(startIndex, exclusive, isDblClick)
	{
		this.selectionTimeout = this.selectionTimeoutFunc = null;
		if(isDblClick && this.ds.GetByIndex(startIndex).IsSelected())
			return;
		if(exclusive)
			this.ds.ClearSelection();
		//this.ds.SelectItemById(this.ds.GetIdByIndex(startIndex), true, exclusive);
		data_MarkItemSelected(this.ds.name, this.ds.GetIdByIndex(startIndex), true, exclusive);
		this.StartIndex = this.LastMoveIndex = startIndex;
	}]
	,ProcessSelection: [decl_virtual, function(currentIndex)
	{
		if(currentIndex == this.LastMoveIndex)
			return;	
		for(var i=Math.min(currentIndex, this.LastMoveIndex); i<=Math.max(currentIndex, this.LastMoveIndex);i++)
		{
			var select = (currentIndex-this.LastMoveIndex)*(i-this.StartIndex)>=0;
			if(i == this.StartIndex || select && i==this.LastMoveIndex || !select && i==currentIndex)
				continue;
			//this.ds.SelectItemById(this.ds.GetIdByIndex(i), !this.ds.GetByIndex(i).IsSelected(), false);
			data_MarkItemSelected(this.ds.name, this.ds.GetIdByIndex(i), !this.ds.GetByIndex(i).IsSelected(), false)
		}
		this.LastMoveIndex = currentIndex;
	}]
	,GetIndexFromElement : function(obj)
	{
		if(obj != this.renderer.obj)
		{
			var id;
			while(!(id = obj.getAttribute("specialitemid")) && obj.parentElement != this.renderer.obj)
				obj = obj.parentElement;
			if(id)
				return this.ds.GetIndexById(id);
		}
		return null;
	}
	,OnKeyDown : function()
	{
		if (this.renderer != null && (event.keyCode == 40 || event.keyCode == 38) && this.LastMoveIndex!=null)
		{
			this.ForceSelection();
			var index = this.LastMoveIndex+(event.keyCode == 40?1:-1);
			if (index < 0 || index >= this.ds.GetCount())
				return;
			if(event.shiftKey && this.StartIndex!=null)
				this.ProcessSelection(index);
			else
				this.StartSelection(index, true);
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}
	,ForceSelection: function(isDblClick)
	{
		if(this.selectionTimeout)
		{
			window.clearInterval(this.selectionTimeout);
			this.selectionTimeoutFunc(isDblClick);
		}
	}
	,OnMouseClick : function()
	{
		if(event.srcElement != this.renderer.obj && (event.detail==null || event.detail<2))
		{
			this.ForceSelection();
			var clickedIndex = this.GetIndexFromElement(event.srcElement);
			if(clickedIndex!=null){
				if(event.shiftKey && this.StartIndex!=null)
					this.ProcessSelection(clickedIndex);
				else
					this.selectionTimeout = window.setTimeout(this.selectionTimeoutFunc = this.StartSelection.bind(this, clickedIndex, false), 200);
			}
		}
	}
	,OnMouseDblClick : function()
	{
		this.ForceSelection(true);
	}
});

DeclareClass("UI.ShiftRerenderSelector", "UI.ShiftSelector",
{
	StartSelection: [decl_virtual, function(startIndex, exclusive, isDblClick)
	{
		this.base.StartSelection(startIndex, exclusive, isDblClick);
		this.ds.ChangeStatus(new dynamicStatusInfo(DE_STATUS_COMPLETE, ""));
	}]
	,ProcessSelection: [decl_virtual, function(currentIndex)
	{
		this.base.ProcessSelection(currentIndex);
		this.ds.ChangeStatus(new dynamicStatusInfo(DE_STATUS_COMPLETE, ""));
	}]
});

// Utils
function ui_CreateScriptLinkHtml(name, script, showTooltip, toolTip, className, encodeHTML, href)
{
	var lnkObj = DOMObjectFactory.CreateTempDOMObject("a");
	lnkObj.setAttribute("href", href ? href : "#"); 
	
	if (encodeHTML) 
		lnkObj.setInnerText(name);
	else 
		lnkObj.setInnerHTML(name);
		
	lnkObj.setAttribute("onclick", script + ";return false");
	
	if (showTooltip) 
		lnkObj.setAttribute("title", str_IsStringEmpty(toolTip) ? name : toolTip);
	if (className) 
		lnkObj.setAttribute("class", className);
		
	return lnkObj.getOuterHTML();
}

function ui_CreateScriptLinkHtmlCancelBubble(name, script, showTooltip, toolTip, className, encodeHTML, href)
{
	var lnkObj = DOMObjectFactory.CreateTempDOMObject("a");
	lnkObj.setAttribute("href", href ? href : "#"); 
	
	if (encodeHTML) 
		lnkObj.setInnerText(name);
	else 
		lnkObj.setInnerHTML(name);
		
	lnkObj.setAttribute("onclick", "try{window.event.cancelBubble=true;}catch(e){}" + script + ";return false;");
	
	if (showTooltip) 
		lnkObj.setAttribute("title", str_IsStringEmpty(toolTip) ? name : toolTip);
	if (className) 
		lnkObj.setAttribute("class", className);
		
	return lnkObj.getOuterHTML();
}

function ui_CreateScriptLinkHtmlWithImage(script, showTooltip, toolTip, className, imageFileName, href, relatedCount)
{
	var result = ["<a"];
	var pushAttribute = function(name, value)
	{
		result.push(" ");
		result.push(name)
		result.push("=\"");
		result.push(cmn_htmlEncode(value));
		result.push("\"")
	}
	pushAttribute("href", href||"#");	
	pushAttribute("onclick", "try{window.event.cancelBubble=true;}catch(e){}" + script + ";return false;");
	if(showTooltip)
		pushAttribute("title", toolTip);
	if (className) 
		pushAttribute("class", className);

	result.push(">("+relatedCount+")<img");
	if (className) 
		pushAttribute("class", className);
	pushAttribute("src", cmn_GetImageUrl(imageFileName));
	result.push("/></a>")
	return result.join("");
}


function ui_CreateScriptLinkHtmlDisabled(name, script, showTooltip, toolTip, className, encodeHTML, href, isDisable)
{
	var lnkObj = DOMObjectFactory.CreateTempDOMObject("a");
	lnkObj.setAttribute("href", href ? href : "#"); 
	if(isDisable!=null)
	{
		if(BrowserInfo.IsIE())
			lnkObj.setAttribute("disabled", "1"); 
		else
			lnkObj.setStyleAttribute("color", "d6d7d9");
	}
	
	if (encodeHTML) 
		lnkObj.setInnerText(name);
	else 
		lnkObj.setInnerHTML(name);
		
	if(isDisable==null)
		lnkObj.setAttribute("onclick", script + ";return false");
	
	if (showTooltip) 
		lnkObj.setAttribute("title", str_IsStringEmpty(toolTip) ? name : toolTip);
	if (className) 
		lnkObj.setAttribute("class", className);
		
	return lnkObj.getOuterHTML();
}

var currQueueRenders = null;
DeclareClass("UI.QueueRenders", null,
{
	constructor : function ()
	{
		this.timerId = -1;
		this.timeout = 5;
		this.queue = [];
	}
	,isStarted : function()
	{
		return this.timerId != -1;
	}
	,StartTimer : function()
	{
		var thisObj = this;
		this.timerId = window.setInterval(function(){thisObj.Process(thisObj);}, this.timeout);
	}
	,StopTimer : function()
	{
		if (this.isStarted())
		{
			this.timerId = window.clearInterval(this.timerId);
			this.timerId = -1;
		}	
	}
	,Process : function(thisObj)
	{
		var func = thisObj.queue.shift();
		if (typeof(func) == "function")
			func();
		if (thisObj.queue.length == 0)
			thisObj.StopTimer();
	}
	,Add : function(func)
	{
		this.queue.push(func);
		if (this.isStarted() == false)
			this.StartTimer();
	}
	,Delete : function(func)
	{
		for (var i=0; i< this.queue.length; i++)
			if(this.queue[i] == func)
			{
				this.queue.splice(i,1);	
				if (this.queue.length == 0)
					this.StopTimer();
				return true;
			}
		return false;
	}
	,Clear : function()
	{
		this.queue = [];
		this.StopTimer();
	}
	,GetQueueRenders : [decl_static, function()
	{
		if (!currQueueRenders) currQueueRenders = new UI.QueueRenders();
		return currQueueRenders;
	}]
});
DeclareNamespace("UI");

DeclareEnum("UI.ControlState",
{	
	UNINITIALIZED: 0,
	INITIALIZED: 1,
	PRERENDERED: 2,
	RENDERED: 3	
});

DeclareEnum("UI.RenderType",
{	
	HTML: 0,
	DOMCREATION: 1	
});

DeclareEnum("UI.UpdateStatus",
{	
	FULL_REFRESH:			0,
	CHILDREN_REFRESH:		1,
	NOUPDATE:				2	
});

DeclareEnum("UI.HtmlTag",
{	
	Span: "span",
	Div: "div",
	Table: "table",
	Tr: "tr",
	Td: "td",
	P: "p",
	A: "a",
	Image: "img",
	Input: "input",
	Label: "label",
	BR: "br",
	Button : "button",
	Select: "select",
	TBody: "tbody",
	Option: "option",
	TextArea: "textarea" 
});

DeclareEnum("UI.Controls.ElementsToDisable",
{	
	INPUT: "INPUT",
	A 	 : "A"
});

DeclareClass("UI.HTMLWriter", null, 
{
	constructor: function(o)
	{
		this.renderer = new UI.SimpleRenderer(o);
		this.data = [];
	}
	,Write : function(s/*,s1,s2...*/)
	{
		for(var i=0; i<arguments.length; i++)
			this.data.push(arguments[i]);
	}
	,Flush : function()
	{
		var html = this.data.join("");
		this.renderer.SetObjectInnerHtml(html);
		return html;
	}
});

DeclareClass("UI.ControlFilter", null,
{
	constructor: function() { this.When = []; }
	,__SetApplyStages: function(/*stages*/)
	{
		for(var i=0; i<arguments.length; i++)
			this.When[arguments[i]] = true;
	}
	,Init: [decl_virtual, function(data)	{ }]
	,Apply : [decl_virtual, function(ctl, stage){ }]
	,Dispose :[decl_virtual, function()	{ }]
});

DeclareClass("UI.ControlVisibleStateManager", null,
{
	constructor: function() 
	{ 
		this.__collection = []; 
		this.__addedctrls = "";
	}
	,IsEmpty : function()
	{
		if (this.__addedctrls == "")
			return true;
	}
	,IsExist : function(ctl)
	{
		if (this.IsEmpty()) return false;
		var reg = new RegExp(ctl.GetClientID() + ">", "ig");
		return reg.test(this.__addedctrls);
	}
	,Add : function(ctl)
	{	
		if (!this.IsExist(ctl))
		{
			this.__collection[ctl.GetClientID()] = ctl;
			this.__addedctrls += ctl.GetClientID() + ">";
		}
	}
	,Delete : function(ctl)
	{
		if (this.__collection[ctl.GetClientID()] != null)
			delete(this.__collection[ctl.GetClientID()]);
		this.__addedctrls = this.__addedctrls.replace(ctl.GetClientID() + ">", "");
	}
	,ReportToChildren : function(pctl, v)
	{
		if (this.IsEmpty()) 
			return;
		var reg = new RegExp(pctl.GetClientID() + "[^>]+", "ig");		
		var res = this.__addedctrls.match(reg);
		if (res != null && res.length > 0)
		{
			for(var i=0; i < res.length; i++ )
			{
				var ctl = this.__collection[res[i]];
				if (ctl != null)
					ctl.OnParentVisibleStateChange(v);
			}
		}
	}
	,Dispose : function()
	{
		this.__collection = null; 
		this.__addedctrls = "";	
	}
});

DeclareClass("UI.ControlProcessorTask", "Utils.SchedulerTask", 
{
	constructor : function(ctl)
	{
		this.base();
		this.__newTaskPosition = 0;
		this.__internalTasks = [];
		this.AsyncRenderingEnabled = false;
	}
	,IsExpired : [decl_virtual, function()
	{
		//return true;
		return this.base.IsExpired();
		//return false;
	}]	
	,ExecuteTask : function()
	{
		while (this.__internalTasks.length > 0)
		{
			var tsk = this.__internalTasks.shift();
			this.__newTaskPosition = 0;
			var old = this.AsyncRenderingEnabled;
			this.AsyncRenderingEnabled = tsk.AsyncRenderingEnabled;
			tsk.Execute();
			this.AsyncRenderingEnabled = old;
			if (this.IsExpired())
				break;
		}
		if (this.__internalTasks.length == 0)
			this.Complete();
	}	
	,__PostInitTask : function(ctl)	
	{
		ctl.Init();
	}
	,__PostPreRenderTask : function(ctl)	
	{
		ctl.__ApplyFilters("PreRender");
		ctl.PreRender();
		ctl.GetClientID();
	}
	,__ProcessRequestTask : function(ctl)	
	{
		ctl.ProcessRequest();
	}
	,__PostUpdateTask : function(ctl)	
	{
		ctl.__ApplyFilters("PostUpdate");
		ctl.__ProcessControlLifeCycle(ctl.ParentControl ? ctl.ParentControl.__controlState : null);	
	}
	,__DoProcessStageTask : function(ctl, num, writer)
	{
		if((num - ctl.__controlState > 1) || (num <= ctl.__controlState) || ctl.__StageInProcess)
			return false;		
		ctl.__StageInProcess = true;
		switch (num)
		{
			case UI.ControlState.INITIALIZED:
				if (ctl.__initialVisibleState == null)
					ctl.__initialVisibleState = ctl.__visible;
				ctl.__ApplyFilters("PreInit");
				if (!ctl.__visible)
					break;
				if (ctl.__createData)
					ctl.ProcessCreateData(ctl.__createData);
				ctl.__controlState = num;
				for (var i = 0; i < ctl.__controls.length; i++)
					this.ProcessStage(ctl.__controls[i],UI.ControlState.INITIALIZED);
				this.__RunCustomTask(ctl,this.__PostInitTask);
				break;
			case UI.ControlState.PRERENDERED: 
				ctl.__controlState = num;
				for (var i = 0; i < ctl.__controls.length; i++)
					this.ProcessStage(ctl.__controls[i],UI.ControlState.PRERENDERED);
				this.__RunCustomTask(ctl,this.__PostPreRenderTask);
				break;
			case UI.ControlState.RENDERED:
				if (!ctl.__visible) 	// if control is not visible then we skip rendering stage
					break;				// when the control become visible it will be rendered
				if (writer == null)
					ctl.GetHostObject();
				ctl.__controlState = num;
				ctl.__Render(writer);
				break;
		}
		ctl.__StageInProcess = false;
		return true;
	}
	,__DoAddControlTask : function(ctl,o)
	{
		o.ParentControl = ctl;
		o.__controlIndex = ctl.__controls.length;
		ctl.__controls.push(o);
		if(ctl.TopElement)
			o.__SetTopElement(ctl.TopElement,ctl.__processorTask);
		o.__ProcessControlLifeCycle(ctl.__controlState);
		return o;
	}
	,__AddTask : function(tsk)	
	{
		var old = this.AsyncRenderingEnabled;
		if (tsk.Control.AsyncRenderingEnabled != null)
			this.AsyncRenderingEnabled = tsk.Control.AsyncRenderingEnabled;
		if ((this.IsExpired() && this.AsyncRenderingEnabled) || tsk.Control.AsyncControlAdding)
		{	
			tsk.AsyncRenderingEnabled = this.AsyncRenderingEnabled;
			this.__internalTasks.splice(this.__newTaskPosition, 0, tsk);
			this.__newTaskPosition++;
			if (this.IsDetached())
				Utils.Scheduler.AddTask(this);
		}
		else
			tsk.Execute();
		this.AsyncRenderingEnabled = old;
		return true;
	}
	,__RunCustomTask : function(ctl, func)	
	{
		this.__AddTask({Processor:this,Control:ctl, Handler: func, Execute: function(){this.Handler(this.Control);}});
	}
	,AddControl : function(ctl, child)
	{
		if (ctl.AsyncControlAdding == true)
		{
			var curTask = this.__newTaskPosition;
			this.__newTaskPosition = this.__internalTasks.length; 
			this.__AddTask({Processor:this,Control:ctl, ChildControl: child,
				 Execute: function(){this.Processor.__DoAddControlTask(this.Control, this.ChildControl);} });
			this.__newTaskPosition = curTask;
		}
		else
			this.__DoAddControlTask(ctl,child);
		return child;
	}
	,ProcessStage : function(ctl, num, writer)
	{
		if (ctl.__StageInProcess)
			return false;
		this.__AddTask({Processor:this,Control:ctl, State: num, Writer: writer,
			 Execute: function(){this.Processor.__DoProcessStageTask(this.Control, this.State, this.Writer);} });
		return true;
	}
	,ProcessRequest : function(ctl)
	{
		this.__RunCustomTask(ctl,this.__ProcessRequestTask);
	}
	,ProcessUpdate : function(ctl)
	{
		ctl.__ApplyFilters("Update");
		var stat = ctl.Update();
		switch (stat)
		{
			case UI.UpdateStatus.CHILDREN_REFRESH:
				for (var i = 0, item; item = ctl.__controls[i]; i++){
					if(item.__navFilter && !item.__navFilter.NeedProcess()){
						continue;
					}
					if (ctl.AsyncControlUpdating != true)
						this.__ProcessRequestTask(item);
					else
						this.ProcessRequest(item);
				}
			case UI.UpdateStatus.NOUPDATE:
				if (ctl.AsyncControlUpdating != true)
					this.__PostUpdateTask(ctl);
				else
					this.__RunCustomTask(ctl,this.__PostUpdateTask);
				return true;
		}
		return false;
	}
});


DeclareClass("UI.Control", null, 
{
	constructor: function()
	{
		this.__writer = null;
		this.__controls = [];
		this.__visible = true;
		this.__controlState = UI.ControlState.UNINITIALIZED;
		this.__attributes = [];
		this.__styleAttributes = [];
		this.__autoIDCount = 0;
		this.__clientID = null;
		this.__createData = null;
		this.__eventContainer = new cmn_EventContainer();
		this.__filters = [];
		this.__controlIndex = 0;
		this.__kwKey = null;
		this.__actvManager = null;
		this.Listeners = new Utils.EventListenersManager(this);
	
		// the following fields intended to be public
		this.ID = null;		
		this.TopElement = null;
		this.ParentControl = null;
		this.ParentElement = null;
		this.HostElement = null;
		this.UpdateRule = UI.UpdateStatus.CHILDREN_REFRESH;
		this.CustomProperties = {};
		this.AsyncRenderingEnabled = null;
		this.HaveVSManager = false;
	}
	,GetRenderType : function() {return UI.RenderType.DOMCREATION;}
	,GetTagName : function() {return UI.HtmlTag.Span;}
	,IsVisible : function() 
	{
		var v = this.__visible, h = this.HostElement;
		if (v && h) return h.offsetWidth != 0 || h.offsetHeight != 0;
		return v; 
	}
	,GetControlState : function() { return this.__controlState; }
	,GetVisibleState : function() { return this.__visible; }
	,SetVisibleState : function(v)
	{
		var previousState = this.IsVisible();
		this.__visible = v;
		this.SetStyleAttribute("display", v ? '' : 'none');
		if (v && this.ParentControl && this.ParentControl.__controlState == UI.ControlState.RENDERED)
		{
			// SCH: If we set control to visible state then we must
			// to make sure that it is in state synchronized with parent
			this.__ProcessControlLifeCycle(this.ParentControl.__controlState);
		}		
		if (previousState != v && previousState != this.IsVisible())
			this.FireEvent("onvisiblechange", v);
		if (this.TopElement != null && this.TopElement.ui_vsmanager != null && previousState != v){
			this.TopElement.ui_vsmanager.ReportToChildren(this, v);	
		}
	}
	,OnParentVisibleStateChange : function(v)
	{
		if ( (v && this.__visible && this.IsVisible()) || (!v && this.__visible ) )
			this.FireEvent("onvisiblechange", v);
	}
	,KeywordsAttach : function(keywords, isExec, exObj)
	{
		this.KeywordsDetach();
		this.__actvManager = isExec == true? new Utils.UIControlActivityManagerEx(this, exObj) : new Utils.UIControlActivityManager(this, exObj);
		this.__kwKey = GlobalKeywordsManager.Add(this.__actvManager, keywords);
	}
	,KeywordsDetach : function()
	{
		if (this.__kwKey != null)
			GlobalKeywordsManager.Delete(this.__kwKey);
		if (this.__actvManager != null)
			this.__actvManager.Dispose();
		this.__kwKey = null;
		this.__actvManager = null;
	}
	,GetAttribute: function(attributeName) { return this.__attributes[attributeName]; }
	,SetAttribute: function(attributeName, value) { 
		this.__attributes[attributeName] = value; 
		if(this.HostElement) 
			if(attributeName.toLowerCase()=="class")
					this.HostElement.className = value;
				else		
					this.HostElement.setAttribute(attributeName, value); 
	}
	,GetStyleAttribute: function(attributeName) { return this.__styleAttributes[attributeName]; }
	,SetStyleAttribute: function(attributeName, value) { if(this.__styleAttributes[attributeName] == value)return; this.__styleAttributes[attributeName] = value; if(this.HostElement) this.HostElement.style[attributeName] = value; }
	,GetCssClass : function() {return this.GetAttribute("class");}
	,SetCssClass : function(cls) { this.SetAttribute("class", cls); }
	,ApplyClass : function UI_Control_ApplyCSSClass(className) {
		if (this.HostElement) {
			var obj = new dom_DOMObject(this.HostElement);
			obj.applyClass(className);
			this.__attributes["class"] = obj.Obj().className;
		}
		else
		{	
			var classes = str_IsStringEmpty(this.__attributes["class"]) ? "" : this.__attributes["class"].split(' ');
			if (classes.indexOf(className) == -1) {
				this.__attributes["class"] = (this.__attributes["class"] + " " + className).trim();
			}
		}
	}
	,RemoveClass : function UI_Control_ApplyCSSClass(className) {
		if (this.HostElement) {
			var obj = new dom_DOMObject(this.HostElement);
			obj.removeClass(className);
			this.__attributes["class"] = obj.Obj().className;
		}
	}
	,GetWidth : function() {return this.GetStyleAttribute("width");}
	,SetWidth : function(val) { this.SetStyleAttribute("width", val); }
	,GetHeight: function() {return this.GetStyleAttribute("height");}
	,SetHeight: function(val) { this.SetStyleAttribute("height", val); }
	,GetIDPrefix : function()
	{
		if(!this.__clientID)
		{
			if(!this.ID)
				this.ID = "ctl" + (this.ParentControl?(this.ParentControl.__autoIDCount++)+"n":"");
			this.__clientID = (this.ParentControl?(this.ParentControl.GetIDPrefix()+ '_'):"") + this.ID;
		}
		return this.__clientID;
	}
	,GetHostObject : function()
	{
		if (this.HostElement != null)
			return this.HostElement;
		this.CreateHostObject();
		return this.HostElement;
	}
	,CreateHostObject : function()
	{
		var tagName = this.GetTagName()||UI.HtmlTag.Div;
		var elem = DOMObjectFactory.CreateElement(tagName);
		
		if (!str_IsStringEmpty(this.ID))
			elem.id = this.GetClientID();
		
		var attributes = this.__attributes;		
		for(var key in attributes)
			if (attributes.hasOwnProperty(key) && attributes[key]!=null)
				if(key.toLowerCase()=="class")
					elem.className = attributes[key];
				else
					elem.setAttribute(key, attributes[key]);
		
		attributes = this.__styleAttributes;
		for(var key in attributes)
			if (attributes.hasOwnProperty(key) && attributes[key]!=null)
				elem.style[key] = attributes[key];
		
		this.HostElement =  elem;
		if(this.ParentControl) {
			this.ParentControl.__InsertControlHost(this, this.__controlIndex)
		} else {
			this.GetParentElement().appendChild(this.HostElement);
		}
	}
	,GetParentElement: function UI_Control_GetParentElement() {
		var el = null;
		if(this.ParentElement) {
			el = this.ParentElement;
		} else {
			if (this.ParentControl != null) {
				el = this.ParentControl.GetHostObject();
			} else {
				el = this.TopElement;
			}
		}
		return el;		
	}
	,__InsertControlHost: function UI_Control_InsertControl(child, index) {
		
		var parent = child.GetParentElement();
		
		if (child.HostElement) {
			var nextElement = null;
			for(var i = index+1, length = this.__controls.length; i < length; i++)
			{				
				var element = this.__controls[i];
				if(element.HostElement && element.ParentElement == child.ParentElement )
				{
					nextElement = element.HostElement;
					break;
				}
			}
			parent.insertBefore(child.HostElement, nextElement);	
		}
	}
	,GetClientID : function()
	{
		if (this.TopElement == null)
			return "";
		return this.GetIDPrefix();
	}
	,Init : [decl_virtual, function()
	{
	}]
	,AMLoad : [decl_virtual, function(txt, params)
	{
	}]
	,PreRender : [decl_virtual, function()
	{
	}]
	,Update :[decl_virtual, function(writer)
	{
		return this.UpdateRule;
	}]
	,Render :[decl_virtual, function(writer)
	{
		for (var i = 0; i < this.__controls.length; i++)
			this.__controls[i].__processorTask.ProcessStage(this.__controls[i],UI.ControlState.RENDERED, writer);
	}]
	,ProcessCreateData :[decl_virtual, function(data)
	{
		if(data.getAttribute("Visible")=="false")
			this.SetVisibleState(false);
		var height = data.getAttribute("Height");
		if (height != null) {
			this.SetHeight(height);
		}
		var cssClass = data.getAttribute("CssClass");
		if(cssClass)
			this.SetCssClass(cssClass);
		var ctls = data.selectSingleNode("Controls");
		if (ctls && ctls.childNodes)
		{
			for (var i = 0; i < ctls.childNodes.length; i++)
				this.AddControl(UI.Control.LoadControlTemplate(ctls.childNodes[i]));
		}
	}]
	,RenderControl : function(writer)
	{
		if (this.GetRenderType() == UI.RenderType.HTML) {
			if (typeof(writer.Write) != "function") {
				this.HostElement  = writer;
				writer = new UI.HTMLWriter(writer);				
			}
			this.__processorTask.ProcessStage(this,UI.ControlState.RENDERED, writer);
			writer.Flush();
		} else {
			this.ParentElement = writer;
			this.__processorTask.ProcessStage(this,UI.ControlState.RENDERED);
		}
	}
	,AddControl : function(o)
	{
		if (this.GetRenderType() == UI.RenderType.HTML && o.GetRenderType() == UI.RenderType.DOMCREATION)
		{
			ReportError("DOMCreation controls cannot be inserted into HTML controls");
			return;
		}
		if (!this.__processorTask)
			this.__processorTask = new UI.ControlProcessorTask(this);

		this.__processorTask.AddControl(this,o);
		return o;
	}
	,MoveControl: function UI_Control_MoveControl(oldIndex, newIndex) {
		var _this = this;
		var length = this.__controls.length;
		if ( (oldIndex >= 0 && oldIndex <= length) 
			&& (newIndex >= 0 && newIndex <= length)
			&& oldIndex != newIndex) {

			var newParent = this.__controls[newIndex].ParentElement;
			var control = this.__controls.splice(oldIndex, 1)[0];
			this.__controls.splice(newIndex, 0, control);
			
			for (var i= Math.min(oldIndex, newIndex), max = Math.max(oldIndex, newIndex); i <= max; i++) {
				this.__controls[i].__controlIndex = i;
			}			
			
			Utils.Conveyer.Run(this.__MoveCell.bind(this, control, newParent),
								this.__MoveStandard.bind(this, control, newParent));
		}
	}
	,InsertControl: function(ctl, idx)
	{
		this.AddControl(ctl);
		this.MoveControl(this.__controls.length-1, idx);
		return ctl;
	}
	,RemoveControl: function(o)
	{
		o.Dispose();
		var index = this.__controls.indexOf(o);
		this.__controls.remove(index);
		for (var i= index; i< this.__controls.length; i++) 
				this.__controls[i].__controlIndex = i;
	}
	,__MoveStandard : function UI_Control_MoveStandard(control, parent) {
		control.ParentElement = null;

		if (parent!= null) {
			control.ParentElement = parent;				
		}
		
		if (control.GetControlState() == UI.ControlState.RENDERED) {
			var parent = control.HostElement.parentNode;
			var element = parent.removeChild(control.HostElement);	
			this.__InsertControlHost(control, control.__controlIndex)						
		}
		return true;
	} 
	,__MoveCell : function UI_Control_MoveCell(control, parent) {
		if ((control.ParentElement && control.ParentElement.tagName == "TD") 
			&& (parent && parent.tagName == "TD") 
			&& parent.childNodes.length == 1 
			&& control.ParentElement.childNodes.length == 1) {
			
				// move an entire TD element
				var cellIndex = parent.cellIndex;
				var srcTR = control.ParentElement.parentNode;
				srcTR.deleteCell(control.ParentElement);				
				
				dstTR = parent.parentNode;
				var cell = dstTR.insertCell(cellIndex);
				dstTR.replaceChild(control.ParentElement, cell);
				return true;
		}
		return false;		
	}
	,ControlsCount : function()
	{
		return this.__controls.length;
	}
	,Dispose :[decl_virtual, function()	
	{
		this.KeywordsDetach();
		for (var i = 0; i < this.__controls.length; i++)
			this.__controls[i].Dispose();
		this.__processorTask = null;

		if (this.Listeners != null)
		this.Listeners.Dispose();

		this.Listeners = null;
		this.__createData = null;
			
		if (this.HaveVSManager)
		{
			this.TopElement.ui_vsmanager.Dispose();
			this.TopElement.ui_vsmanager = null;;
		}
		if (this.HostElement)
			dom_RemoveNode(this.HostElement, true);
		this.HostElement = null;
	}]
	,ProcessRequest : function()
	{	
		if (!this.__processorTask)
			this.__processorTask = new UI.ControlProcessorTask(this);

		if (this.__controlState <= UI.ControlState.RENDERED && this.__controlState != UI.ControlState.UNINITIALIZED)
			if (this.__processorTask.ProcessUpdate(this)) return;
		
		var endState = this.ParentControl ? this.ParentControl.__controlState : null;
		// full update section
		if(this.__initialVisibleState != null)
			this.__visible = this.__initialVisibleState;		
		if (this.__controlState != UI.ControlState.UNINITIALIZED)
		{
			for (var i = 0; i < this.__controls.length; i++)
				this.__controls[i].Dispose();
			this.__controls = [];
		}
		this.__removeLocker();
		this.__controlState = UI.ControlState.UNINITIALIZED;
		if (this.HostElement != null)
			new dom_DOMObject(this.HostElement).removeAllChildrens();
		this.__ProcessControlLifeCycle(endState);
	}	
	,AttachEvent: function(evtname, func)
	{ 
		var res = this.__eventContainer.attachEvent(evtname, func); 
		if (evtname == "onvisiblechange" && this.TopElement.ui_vsmanager != null)
			this.TopElement.ui_vsmanager.Add(this);
		return res;
	}
	,DetachEvent: function(evtname, id)
	{
		var res = this.__eventContainer.detachEvent(evtname, id); 
		if (evtname == "onvisiblechange" && this.TopElement.ui_vsmanager != null && this.__eventContainer.getEventsCount(evtname) == 0)
			this.TopElement.ui_vsmanager.Delete(this);
		return res;
	}
	,FireEvent	: function(evtname /*params[] called params*/){ return this.__eventContainer.fireEvent.apply(this.__eventContainer, arguments);}

	// Internal methods	
	,__SetTopElement: function(obj,proc)
	{
		this.TopElement = obj;
		this.__processorTask = proc;
		for (var i = 0; i < this.__controls.length; i++)
			this.__controls[i].__SetTopElement(obj,proc);
	}
	,__ProcessControlLifeCycle : function(endState)
	{
		if (endState == null)
			endState = UI.ControlState.RENDERED;
		for (var i = this.__controlState + 1; i <= endState; i++)
			if (!this.__processorTask.ProcessStage(this, i)) break;		
	}
	,__Render : function(writer)
	{
		switch (this.GetRenderType())
		{
			case UI.RenderType.HTML:
				if (writer == null) {	// create HTML writer here
					this.__writer = writer = new UI.HTMLWriter(this.GetHostObject());
				} 
				var hasID = !this.__writer && !str_IsStringEmpty(this.ID);
				if (this.GetTagName() != null)
				{
					writer.Write("<", this.GetTagName());
					if (!str_IsStringEmpty(this.ID))
						writer.Write(" id=\"", this.GetClientID(), "\" ");
					
					var attributes = this.__attributes;
					for(var key in attributes)
						if (attributes.hasOwnProperty(key) && attributes[key]!=null )
							writer.Write(key, "=\"", attributes[key], "\" ");

					var hasStyle = false;
					attributes = this.__styleAttributes;
					for(var key in attributes)
						if (attributes.hasOwnProperty(key) && attributes[key]!=null){
							if(!hasStyle)
								writer.Write("style=\"");
							hasStyle = true;
							writer.Write(key, ":", attributes[key], "; ");
						}
					if(hasStyle)
						writer.Write("\" ");
					writer.Write(">");
				}
				this.Render(writer);
				if (this.GetTagName() != null)
					writer.Write("</", this.GetTagName(), ">");
				if (this.__writer != null) {
					this.__writer.Flush();
					this.__writer = null;
				}
				break;
			case UI.RenderType.DOMCREATION:
				this.Render(writer);
				break;
		}
		
		if (this.IsLocked()) {
			this.Lock();
		}
	}
	,AddFilter: function(filter){
		this.__filters.push(filter);
		if(filter.IsInstanceOf(UI.NavigationFilter))
			this.__navFilter = filter;
	}
	,RemoveFilter: function(filter){ this.__filters.removeItem(filter); }
	,__ApplyFilters : function(stage, params)
	{
		for (var i = 0, item; item = this.__filters[i]; i++)
			if (item.When[stage]){				
				item.Apply(this,stage, params);	
			}
	}
	,__ApplyFiltersByType : function(type, params)
	{
		for (var i = 0, item; item = this.__filters[i]; i++)
			if (item.IsInstanceOf(type))
				item.Apply(this, null, params);
	}
// Static methods
	,LoadControl : [decl_static, function(ctlname, obj, params)
	{
		var ctl;
		var ctlId = '_'+obj.id;
		if (ctlname == "__CREControl__")
		{
			var data = eval(params+"()");			
			ctl = UI.Control.LoadControlTemplate(data.GetFirstChild(), ctlId);
			ctl.__processorTask = new UI.ControlProcessorTask(ctl);

			// SCH: May be use more smart attaching on navigation events.
			ctl.Listeners.AddObjectListener(nav_events, "onnavigationchange", ctl.ProcessRequest);
		}
		else
		{
			ctl = eval("new " + ctlname + "();");
			ctl.ID = ctlId;
		}
		ctl.__SetTopElement(obj);
		ctl.TopElement.ui_vsmanager = new UI.ControlVisibleStateManager();
		ctl.HaveVSManager = true;
			
			
		//for UI.Controls.ServerControlContainer control
		var parentEl = obj.parentElement
		while(parentEl && parentEl.getAttribute && !parentEl.getAttribute("server_container"))
			parentEl = parentEl.parentElement		
		if(parentEl && parentEl.getAttribute)
			ctl.TopHierarchyControl = parentEl.getAttribute("server_container");
			
		return ctl;
	}]
	,LoadControlTemplate : [decl_static, function(node, id)
	{
		var ctlname = node.getAttribute("ControlName");
		if (str_IsStringEmpty(ctlname))
			return null;
		var ctl = eval("new " + ctlname + "();");
		if (!str_IsStringEmpty(id))
			ctl.ID = id;
		var async = node.getAttribute("AsyncRenderingEnabled");
		if (async == "true") ctl.AsyncRenderingEnabled = true;
		else if (async == "false") ctl.AsyncRenderingEnabled = false;
		
		
		if (node.getAttribute("AsyncControlAdding") == "true")
			ctl.AsyncControlAdding = true;
		
		ctl.__createData = node.selectSingleNode("CreateData");
		var flt = node.selectSingleNode("ClientFilters");
		if (flt && flt.childNodes)
		{
			for (var i = 0; i < flt.childNodes.length; i++)
			{
				var fl = eval("new " + flt.childNodes[i].getAttribute("Processor") + "()");
				fl.Init(flt.childNodes[i], ctl);
				ctl.AddFilter(fl);
			}
		}
		return ctl;
	}]
	
	,IsLocked : function UI_Control_IsLocked() {
		return this.__isLocked;
	}
	
	,Lock : function UI_Control_Lock() {
		if (this.HostElement && !this.IsLocked()) {
			var tagName = this.HostElement.tagName.toLowerCase();
			if (tagName == UI.HtmlTag.Div || tagName == UI.HtmlTag.Span) {
			
				this.HostElement.position = this.HostElement.currentStyle.position;
				this.HostElement.style.position = "relative";
				
				this.__locker = DOMObjectFactory.CreateDOMObject(UI.HtmlTag.Div, false, this.HostElement);				
				this.__locker.applyClass("locker");
				this.__isLocked = true;
				
				var elements = Array.getFrom(this.HostElement.all).filter(function(el) { 
					return (el.tagName && el.tagName in UI.Controls.ElementsToDisable &&
						typeof(el.tabIndex) != "undefined")	});
				
				elements.map(function(el) {
						el._tabIndex = el.tabIndex;
						el.tabIndex = -1; 
				});
			}
		}
	}
	
	,Unlock : function UI_Control_Unlock() {
		if (this.HostElement && this.IsLocked()) {
			if (this.HostElement.position) {
				this.HostElement.style.position = this.HostElement.position;
			}
			this.__removeLocker();
			this.__isLocked = false;
			
			var elements = Array.getFrom(this.HostElement.all).filter(function(el) { 
				return (el.tagName && el.tagName in UI.Controls.ElementsToDisable &&
					typeof(el._tabIndex) != "undefined") });

			elements.map(function(el) { el.tabIndex = el._tabIndex;	});
		}
	}
	
	,__removeLocker : function() {
		if (this.__locker) {
			this.__locker.removeNode(true);
			this.__locker = null;
		}
	}	
	
	,Disable : function UI_Control_Disable(state) {
		if (this.HostElement) {
			var elements = Array.getFrom(this.HostElement.all).filter(function(el) {
				return (el.tagName && el.tagName in UI.Controls.ElementsToDisable &&
					typeof(el.disabled) != "undefined") });
				
			elements.map(function(el) {	el.disabled = state; });				
		}
	}
});

DeclareNamespace("UI");
DeclareNamespace("UI.Controls");
DeclareNamespace("UI.DOMControls");

DeclareEnum("UI.CheckBoxStates", {	
	UNCHECKED: 0,
	PARTIALCHECKED: 1,
	CHECKED: 2
});

DeclareEnum("UI.Controls.ItemBarDirection", {	
	VERTICAL: 0,
	HORIZONTAL: 1
});

DeclareEnum("UI.Controls.ItemBarAlign", {	
	LEFT: 0,
	RIGHT: 1,
	TOP : 2,
	BOTTOM : 3	
});

DeclareClass("UI.Controls.ItemBarBase", "UI.Control", {
	constructor : function(barDirection) {
		this.base();		
		this.itemBarItems = [];
		this.itemBarDirection = (barDirection == null ? UI.Controls.ItemBarDirection.HORIZONTAL : barDirection);
		this.SetAttribute("cellSpacing", 0);
		this.SetAttribute("cellPadding", 0);
	}
	,GetTagName : function() {
		return UI.HtmlTag.Table;
	}
	,AddItem : function(ctl, align, css) {
		this.AddControl(ctl);
		this.itemBarItems.push({Item: ctl, Align: align, Css: css});
	}
	,Render :[decl_virtual, function(writer) {
		var row = this.HostElement.insertRow(), separatorIndex = 0, cell = row.insertCell(), 
			ibaRight = UI.Controls.ItemBarAlign.RIGHT, ibaBottom = UI.Controls.ItemBarAlign.BOTTOM, 
			ibdVertical = UI.Controls.ItemBarDirection.VERTICAL;
		
		if (this.itemBarDirection == UI.Controls.ItemBarDirection.HORIZONTAL)
			cell.style.width = "100%";
		else
			cell.style.height = "100%";
		cell.noWrap = true;		
		
		for (var i = 0, ic = this.itemBarItems.length; i < ic; i++) {
			var align = this.itemBarItems[i].Align;
			var index = (align != ibaRight && align != ibaBottom) ? separatorIndex++ : -1;

			if (this.itemBarDirection == ibdVertical) {
				row = this.HostElement.insertRow(index);
				cell = row.insertCell();
			}
			else
				cell = row.insertCell(index);						
			cell.noWrap = true;
			if (this.itemBarItems[i].Css)
				cell.className = this.itemBarItems[i].Css;
			this.itemBarItems[i].Item.RenderControl(cell);
		}			
	}]
});

DeclareClass("UI.Controls.ScriptLink", "UI.Control", {
	constructor : function(name, script, showTooltip, toolTip, className, encodeHTML, imgSrc, imgWidth, imgHeight) {
		this.base();
		this.name = encodeHTML == true ? cmn_htmlEncode(name) : name;
		this.script = script;
		this.showTooltip = showTooltip
		this.toolTip = str_IsStringEmpty(toolTip) ? name : toolTip;
		this.imgSrc = imgSrc;
		this.imgWidth = imgWidth;
		this.imgHeight = imgHeight;
		if (!str_IsStringEmpty(className))
			this.SetCssClass(className);
		this.txtNode = null;
	}
	,GetTagName : function() {
		return UI.HtmlTag.A;
	}
	,Render :[decl_virtual, function(writer) {
		this.HostElement.setAttribute("href", "#"); 
		if (!str_IsStringEmpty(this.imgSrc)) {
			var img = DOMObjectFactory.CreateElement(UI.HtmlTag.Image);				
			img.setAttribute("src", this.imgSrc);
			if (!str_IsStringEmpty(this.imgWidth))
				img.setAttribute("width", this.imgWidth);
			if (!str_IsStringEmpty(this.imgHeight))
				img.setAttribute("height", this.imgHeight);
			img.setAttribute("border", "0");
			this.HostElement.appendChild(img);
		}
		this.HostElement.onclick = (typeof(this.script)=="string") ? new Function(this.script + ";return false") : this.script;
		if (this.showTooltip)
			this.HostElement.setAttribute("title", this.toolTip);
		this.txtNode = document.createTextNode(this.name)
		this.HostElement.appendChild(this.txtNode);
	}]
	,Dispose : [decl_virtual, function() 
	{
		this.txtNode = null;
		this.base.Dispose();
	}]
	,SetName : function(name)
	{
		this.name = name;
		if (this.txtNode != null)
			this.txtNode.nodeValue = name;
	}
	,SetScript : function(script)
	{
		this.script = script;
		if (this.HostElement != null)
			this.HostElement.onclick = (typeof(this.script)=="string") ? new Function(this.script + ";return false") : this.script;
	}
});

DeclareClass("UI.Controls.Button", "UI.Control", {
	constructor : function(title, script, className) { 
		this.base();
		this.title = title;
		this.script = script;
		if (!str_IsStringEmpty(className))
			this.SetCssClass(className);
	}
	,GetTagName : function() {
		return UI.HtmlTag.Button;
	}
	,Render :[decl_virtual, function(writer) {
		this.HostElement.setAttribute("type","BUTTON");
		this.HostElement.onclick = (typeof(this.script)=="string") ? new Function(this.script + ";return false") : this.script;
		this.HostElement.appendChild(document.createTextNode(this.title));
	}]
	,ProcessCreateData :[decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		this.title = data.getAttribute("Title");		
		this.script = data.getAttribute("Action");		
	}]
});
//---------------UI.DOMControls.Control-----------------
DeclareClass("UI.DOMControls.Control", null, {
	constructor : function() {
		this.parent = null;
		this.visible = true;
		this.attributes = [];
	}
	,GetTagName : function() { 
		return UI.HtmlTag.Span; 
	}
	,Obj : function() { 
		return (this.parent) ? this.parent : this.Render(DOMObjectFactory.CreateElement(this.GetTagName())); 
	}
	,Render : [decl_virtual, function(parent) {
		if (!this.parent) this.parent = parent;
		if (this.cssClass) this.parent.className = this.cssClass;
		this.parent.style.display = this.visible ? "" : "none";
		for(var attr in this.attributes)
			if(this.attributes.hasOwnProperty(attr))
				this.parent.setAttribute(attr, this.attributes[attr]);
		return this.parent;	
	}]
	,SetCssClass : function(cssClass) {
		this.cssClass = cssClass;
		if (this.parent)
			this.parent.className = this.cssClass;
	}
	,AttachEvent : function(evtname, func) {
		dom_attachEventForObject(this.Obj(), evtname, func);
	}
	,DetachEvent : function(evtname, func) {
		dom_detachEventForObject(this.Obj(), evtname, func);
	}
	,SetVisibleState : function(v) {
		if (this.visible != v) {
			this.visible = v;
			if (this.parent)
				this.parent.style.display = this.visible ? "" : "none";
		}
	}
	,SetAttribute: function(attributeName, value){
		this.attributes[attributeName] = value;
		if(this.parent)
			this.parent.setAttribute(attributeName, value);
	}
	,Dispose: [decl_virtual, function(parent) {
		this.parent = null;
	}]
});
//---------------UI.DOMControls.Text-----------------
DeclareClass("UI.DOMControls.Text", "UI.DOMControls.Control", {
	constructor : function(text, isHTML) {
		this.base();
		this.text = text;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.textNode = document.createTextNode(this.text);
		this.parent.appendChild(this.textNode);
		return this.parent;
	}]
	,SetText : function(text) {
		this.text = text;
		if (this.textNode != null)
			this.textNode.nodeValue = text;
	}
	,GetText : function() { 
		return this.text; 
	}
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		this.textNode = null;
	}]
});
//---------------UI.Controls.Text-----------------
DeclareClass("UI.Controls.Text", "UI.Control", {
	constructor : function(text) { 
		this.base();
		this.domObj = new UI.DOMControls.Text(text);
	}
	,Render :[decl_virtual, function(writer) {
		this.base.Render(writer);
		this.domObj.Render(this.HostElement);
		this.Listeners.AddDOMListener(this.HostElement, "click", this.OnClick);
	}]
	,SetText : function(text) { 
		this.domObj.SetText(text); 
	}
	,GetText : function() { 
		return this.domObj.GetText(); 
	}
	,OnClick: function(e) { 
		this.FireEvent("onclick", e, this, this.GetText()); 
	}
});

DeclareClass("UI.DOMControls.LiteralControl", "UI.DOMControls.Control", {
	constructor : function(html) {
		this.base();
		this.html = html;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.parent.innerHTML = this.html;
		return this.parent;
	}]
	,SetHTML : function(html)
	{
		this.html = html;
		if (this.parent)
			this.parent.innerHTML = this.html;
	}
});

DeclareClass("UI.DOMControls.Link", "UI.DOMControls.Control", {
	constructor : function(text, href, onclick) {
		this.base();
		this.text = text;
		this.href = href;
		this.onclick = onclick;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.parent.appendChild(document.createTextNode(this.text));
		this.parent.setAttribute("href", this.href);
		if (typeof(this.onclick) == "string")
			this.parent.setAttribute("onclick", this.onclick);
		else if (typeof(this.onclick) == "function")
			this.AttachEvent("click", this.onclick);
		return this.parent;
	}]
	,GetTagName : function() {
		return UI.HtmlTag.A;
	}
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		this.onclick = null;
	}]
});

DeclareClass("UI.DOMControls.Button", "UI.DOMControls.Control", {
	constructor : function(text, onclick) {
		this.base();
		this.text = text;
		this.onclick = onclick;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.parent.appendChild(document.createTextNode(this.text));
		if (typeof(this.onclick) == "string")
			this.parent.setAttribute("onclick", this.onclick);
		else if (typeof(this.onclick) == "function")
			this.AttachEvent("click", this.onclick);
		return this.parent;
	}]
	,GetTagName : function() {
		return UI.HtmlTag.Button;
	}
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		this.onclick = null;
	}]
});

DeclareClass("UI.DOMControls.TextArea", "UI.DOMControls.Control", {
	constructor : function(defaultVal, rows, cssClass) {
		this.base();
		this.defaultVal = defaultVal;
		this.__maxLength = null;
		this.__rows = rows;
		this.curr_value = defaultVal;
		if (cssClass)
			this.SetCssClass(cssClass);
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.__SetInputValue();
		if (this.__maxLength != null)
			this.parent.maxLength = this.__maxLength;
		if (this.__rows != null)
			this.parent.rows = this.__rows;
		return this.parent;
	}]
	,GetTagName : function() {
		return UI.HtmlTag.TextArea;
	}
	,__SetInputValue: function() {
		if (this.parent)
			this.parent.value = this.curr_value;
	}
	,SetValue : function(val) {
		this.curr_value = val;
		this.__SetInputValue();
	}
	,GetValue : function() {
		if (this.parent)
			return this.parent.value;
		return this.curr_value;
	}
	,SetMaxLength : function(maxLength) {
		this.__maxLength = maxLength;
		if (this.parent)
			this.parent.maxLength = this.__maxLength;
	}
});

DeclareClass("UI.DOMControls.Div", "UI.DOMControls.Control", {
	constructor : function(content) {
		this.base();
		this.content = content;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.parent.appendChild(this.content.Obj());
		return this.parent;
	}]
	,GetTagName : function() {
		return UI.HtmlTag.Div;
	}
	,Dispose: [decl_virtual, function() {
		this.base.Dispose();
		this.content = null;
	}]
});

//---------------UI.DOMControls.Text-----------------
DeclareClass("UI.DOMControls.InputControl", "UI.DOMControls.Control", {
	constructor : function(defaultVal, cssClass) {
		this.base();
		this.defaultVal = defaultVal;
		this.__maxLength = null;
		this.curr_value = defaultVal;
		if (cssClass)
			this.SetCssClass(cssClass);
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.__SetInputValue();
		if (this.__maxLength != null)
			this.parent.maxLength = this.__maxLength;
		this.parent.setAttribute("type","text");
		return this.parent;
	}]
	,GetTagName : function() {
		return UI.HtmlTag.Input;
	}
	,__SetInputValue: function() {
		if (this.parent)
			this.parent.value = this.curr_value;
	}
	,SetValue : function(val) {
		this.curr_value = val;
		this.__SetInputValue();
	}
	,GetValue : function() {
		if (this.parent)
			return this.parent.value;
		return this.curr_value;
	}
	,SetMaxLength : function(maxLength) {
		this.__maxLength = maxLength;
		if (this.parent)
			this.parent.maxLength = this.__maxLength;
	}
});

DeclareClass("UI.Controls.InputControl", "UI.Control", {
	constructor : function(defaultVal, onEnterPress) {
		this.base();
		this.domObj = new UI.DOMControls.InputControl(defaultVal);
		this.onEnterPress = onEnterPress;
	}
	,GetTagName : function() {
		return this.domObj.GetTagName();
	}
	,Render :[decl_virtual, function(writer) {
		this.base.Render(writer);
		this.domObj.Render(this.HostElement);
		this.Listeners.AddDOMListener(this.HostElement,"keydown",this.OnKeyDown);
		this.Listeners.AddDOMListener(this.HostElement,"blur",this.OnBlur);
		this.Listeners.AddDOMListener(this.HostElement,"focus",this.OnFocus);
	}]
	,SetValue : function(val) {
		this.domObj.SetValue(val);
	}
	,GetValue : function() {
		return this.domObj.GetValue();
	}
	,OnKeyDown : function(e) {
		if (this.onEnterPress != null && e.keyCode == "13") {
			if (typeof(this.onEnterPress) == "function")
				this.onEnterPress(e);
			else
				eval(this.onEnterPress);
			return false;
		}
		this.FireEvent("onkeydown", this, e.keyCode, this.GetValue());
	}
	,OnBlur: function(e) {
		this.FireEvent("onblur", e, this);
	}
	,OnFocus: function(e) {
		this.FireEvent("onfocus", e, this);
	}
	,SetMaxLength : function(maxLength) {
		this.domObj.SetMaxLength(maxLength);
	}
});

DeclareClass("UI.Controls.LiteralControl", "UI.Control", {
	constructor: function(HTML) {
		this.base();
		this.HTML = HTML;
	}
	,GetRenderType: function() {
		return UI.RenderType.HTML;
	}
	,GetTagName: function() {
		return null;
	}
	,Render: [decl_virtual, function(writer) {
		writer.Write(this.HTML);
	}]
	,ProcessCreateData :[decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		this.HTML = data.getAttribute("Html");		
	}]
});

DeclareClass("UI.Controls.DropDown", "UI.Control", {
	constructor : function() {
		this.base();
		this.dropDownItems = [];		
		this.dropDownObject = null;
		this.SelectedValue = null;		
		this.__selectedIdx = 0;
		this.PopupMaxHeight = 400;
		this.SetCssClass("ddBlock");
		this.isReadOnly = true;
		
		this.__dropDown = null;
		this.__popup = null;
		this.__input = null;
	}
	,Dispose : [decl_virtual, function() {
		this.base.Dispose();
		this.dropDownItems = null;
		this.dropDownObject = null;
		this.__dropDown = null;
		if (this.__popup) {
			this.__popup.setAttribute("maxHeight", null);
			this.__popup = null;
		}
		this.__input = null;
	}]
	,SetReadOnly : function(bValue) {
		this.isReadOnly = bValue;
		if (this.__input)
			this.__input.readOnly = this.isReadOnly;
	}
	,SetItems : function(items) {
		if (!items) return;
		for (var i = 0, ic = items.length; i < ic; ++i)
			this.AddItem(items[i].name, items[i].value);
	}	
	,AddItem : function(name, value) {
		this.dropDownItems.push({"name":name, "value":value});
		if(this.dropDownObject)
			return this.dropDownObject.AddValue(name, value);
		return null;
	}
	,Clear : function() {
		this.dropDownItems = [];
		if(this.dropDownObject)
			this.dropDownObject.Clear();
		this.SelectedValue = null;
	}
	,SetSelectItem: function(name, value, fireevent) {
		this.SelectedValue = value;
		if(this.dropDownObject)
			this.dropDownObject.SelectItem(name, value, fireevent);
	}
	,SetSelectedValue: function(value, fireevent) {
		this.SelectedValue = value;
		if(this.dropDownObject)
			this.dropDownObject.SetValue(value, fireevent);
	}
	,Select: function(idx, fireevent) {
		if (this.dropDownItems[idx] == null) return;
		this.SelectedValue = this.dropDownItems[idx].value;
		this.__selectedIdx = idx;		
		this.__Select(idx, fireevent);
		
	}	
	,__Select : function(idx, fireevent) {
		if(this.dropDownObject)
			this.dropDownObject.Select(idx, fireevent);
	}
	,GetDisplayValue: function() { 
		return this.dropDownObject ? this.dropDownObject.GetDisplayValue() : null; 
	}
	,GetValue: function() {
		return this.dropDownObject ? this.dropDownObject.GetValue() : null; 
	}
	,__onSelect : function() {
		var oldValue = this.SelectedValue;
		this.SelectedValue = this.dropDownObject.GetValue();		
		this.FireEvent("onselected", this, this.SelectedValue, oldValue);
	}
	,Init: [decl_virtual, function() {
		this.base.Init();
		
		this.__dropDown = DOMObjectFactory.CreateElement(UI.HtmlTag.Div), 
		this.__dropDown.className = "dd";
		
		this.__popup = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		this.__popup.className = "ddDiv";
		this.__popup.setAttribute("maxHeight", this.PopupMaxHeight);
		
		var btnDiv = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		btnDiv.className = "ddBtn";
		
		var img = DOMObjectFactory.CreateElement("img");
		img.className = "ddBtnI";
		img.src = cmn_GetImageUrl("ImgUp.gif");
		btnDiv.appendChild(img);
		
		this.__input = DOMObjectFactory.CreateElement("input");
		var css = this.GetCssClass();
		this.__input.className = "ddIptRo "+ (css ? css : "");
		this.__input.readOnly = this.isReadOnly;
		
		this.__dropDown.appendChild(btnDiv);
		this.__dropDown.appendChild(this.__input);
	}]
	,Render: [decl_virtual, function(writer) {
		this.HostElement.style.display = "block";		
		
		this.HostElement.appendChild(this.__dropDown);
		this.HostElement.appendChild(this.__popup);
		
		this.dropDownObject = new tpDropDown(this.GetClientID());
		var obj = this.dropDownObject;
		for (var i = 0, ic = this.dropDownItems.length; i < ic; ++i)
			obj.AddValue(this.dropDownItems[i].name, this.dropDownItems[i].value);
			
		if (this.SelectedValue != null)
			this.SetSelectedValue(this.SelectedValue);
		else
			if(this.__selectedIdx < this.dropDownItems.length)
				this.Select(this.__selectedIdx);
				
		obj.attachEvent('onselected', this.CreateCallback(this.__onSelect));
	}]
});

DeclareClass("UI.Controls.PopupArea", "UI.Control", {
	constructor: function() {
		this.base();
		this.__AddControl = this.AddControl;
		this.AddControl = this.AddContentControl;
		this.IsShowed = false;
	}	
	,AddContentControl: function(o) {
		if(this.BehaviorObj)
			o.ParentElement = this.BehaviorObj.ContentCtrl;
		this.__AddControl(o);
	}
	,GetTagName: function() {
		return UI.HtmlTag.DIV;
	}
	,GetBehaviorObjName: function() {
		return "UI.Popuparea";
	}
	,SetMainCssClass: function(css)	{
		this.__mainCssClass = css; 
		this.SetCssClass(css);
	}
	,PreRender: [decl_virtual, function() {
		this.SetCssClass("popuparea-hide "+ this.GetCssClass());
	}]
	,Render :[decl_virtual, function(writer) {
		this.RenderContent(this.HostElement);
	}]
	,RenderContent :[decl_virtual, function(writer) {
		if(this.MinWidth)
			this.HostElement.setAttribute("minWidth", this.MinWidth);
		if(this.MaxWidth)
			this.HostElement.setAttribute("maxWidth", this.MaxWidth);
		if(this.MinHeight)
			this.HostElement.setAttribute("minHeight", this.MinHeight);
		if(this.MaxHeight)
			this.HostElement.setAttribute("maxHeight", this.MaxHeight);
		this.HostElement.setAttribute("mainCss", this.__mainCssClass);
		var contentDiv = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);		
		contentDiv.id= this.GetClientID()+"_c";
		writer.appendChild(contentDiv);
		for (var i = 0, ic = this.__controls.length; i < ic; i++)
			this.__controls[i].RenderControl(contentDiv);
		this.BehaviorObj = eval("new "+ this.GetBehaviorObjName() + "('" + this.GetClientID() + "')");
		this.BehaviorObj.CloseHandler = this.CreateCallback(this.__onHide);
	}]
	,ShowPopup: function(options) {
		if(this.BehaviorObj) {
			this.BehaviorObj.showPopupFromObject(options);
			this.IsShowed = true;
		}
	}
	,HidePopup: function() {
		if(this.BehaviorObj) {
			this.BehaviorObj.hidePopup();
			this.IsShowed = false;
		}
	}
	,GetOptions: function(){
		return this.BehaviorObj && this.BehaviorObj.__options;
	}
	,__onHide :[decl_virtual, function(){
		this.IsShowed = false; 
		this.FireEvent("hide");
	}]
});

DeclareClass("UI.Controls.BorderedPopupArea", "UI.Controls.PopupArea", {
	Render: [decl_virtual, function(writer) {
		var tabale = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		tabale.cellPadding = tabale.cellSpacing = 0;
		this.HostElement.appendChild(tabale);
		var __createRow = function(cssList) {
			var row = tabale.insertRow();
			for(var i=0; css=cssList[i]; i++)
				row.insertCell().className = css;
		}
		__createRow(['tli', 'ti', 'tri']);
		__createRow(['li', 'cnt', 'ri']);
		__createRow(['bli', 'bi', 'bri']);
		var scrollArea = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		tabale.rows[1].cells[1].appendChild(scrollArea);
		this.RenderContent(scrollArea);
		var arrow = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		arrow.className = "arrow";
		this.HostElement.appendChild(arrow);
	}]
});

DeclareClass("UI.Controls.GenericControl", "UI.Control", {
	constructor: function(tagName) {
		this.base();
		this.__TagName = tagName || UI.HtmlTag.Div;
	}
	,GetTagName: function() {
		return this.__TagName;
	}
});

DeclareClass("UI.Controls.Panel", "UI.Control", {	
	GetTagName: function() {
		return UI.HtmlTag.Div;
	}
});

DeclareClass("UI.Controls.CollapsibleControlBase", "UI.Control", {
	constructor: function(expanded) {
		this.base();
		this.Expanded = expanded;
	}
	,Init: [decl_virtual, function() {
		if (!this.Expanded)
			this.Collapse(false);
	}]
	,Collapse: [decl_virtual, function(fireevent) {
		this.Expanded = false;
		if (fireevent != false)
			this.FireEvent("collapse",this);
	}]
	,Expand: [decl_virtual, function(fireevent) {
		this.Expanded = true;
		if (fireevent != false)
			this.FireEvent("expand",this);
	}]	
});

DeclareClass("UI.Controls.CollapsibleControl", "UI.Controls.CollapsibleControlBase", {	
	GetTagName: function() {
		return UI.HtmlTag.Div;
	}
	,Init: [decl_virtual, function() {
		this.HeaderControl = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		this.ContentControl = new UI.Controls.Panel();
		this.ContentControl.SetVisibleState(this.Expanded);
		this.AddControl(this.ContentControl);		
		this.base.Init();
	}]
	,Render : [decl_virtual, function(writer) {
		this.HostElement.appendChild(this.HeaderControl);
		this.Header.RenderControl(this.HeaderControl);
		this.ContentControl.RenderControl(this.HostElement);		
	}]
	,AddUIControlToHeader: function(ui_Control) {
		this.Header = ui_Control;
		this.AddControl(this.Header);
	}
	,AddUIControlToContent: function(ui_Control) {
		this.ContentControl.AddControl(ui_Control);
	}
	,Collapse: [decl_virtual, function(fireevent) {		
		this.base.Collapse(fireevent);
		if (this.ContentControl)
			this.ContentControl.SetVisibleState(false);
	}]
	,Expand: [decl_virtual, function(fireevent) {		
		if (this.ContentControl)
			this.ContentControl.SetVisibleState(true);
		this.base.Expand(fireevent);		
	}]	
});

DeclareClass("UI.Controls.CollapsibleChildControl", "UI.Controls.CollapsibleControlBase", {
	constructor: function(expanded, collapsibleParent) {
		this.base(expanded);
		this.CollapsibleParent = collapsibleParent;
		this.ClickHandler = this.CreateCallback(this.Click);
	}
	,Init: [decl_virtual, function() {
		if (this.CollapsibleParent) {
			this.Listeners.AddObjectListener(this.CollapsibleParent, "collapse", this.Collapse);
			this.Listeners.AddObjectListener(this.CollapsibleParent, "expand", this.Expand);
		}
	}]
	,StopEvent: [decl_virtual, function() {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}]
	,Click: function() {
		this.StopEvent();
		if (this.Expanded) {
			if (this.CollapsibleParent)
				this.CollapsibleParent.Collapse();
			else
				this.Collapse();
		}
		else
		{
			if (this.CollapsibleParent)
				this.CollapsibleParent.Expand();
			else
				this.Expand();			
		}		
	}
	,Collapse: [decl_virtual, function(fireevent) {
		this.base.Collapse(fireevent);
		this.Reload();
	}]
	,Expand: [decl_virtual, function(fireevent) {
		this.base.Expand(fireevent);
		this.Reload();
	}]
	,Reload: [decl_virtual, function() {
	}]
});

DeclareClass("UI.Controls.CollapsibleCheckBoxControl", "UI.Controls.CollapsibleChildControl", {
	constructor: function(expanded, collapsibleParent, text) {
		this.base(expanded, collapsibleParent);
		this.__text = text;
	}	
	,Reload: [decl_virtual, function() {
		if(this.__checkBox)
			this.__checkBox.checked = !!this.Expanded;
	}]	
	,Render: [decl_virtual, function(writer) {
		this.__checkBox = DOMObjectFactory.CreateElement(UI.HtmlTag.Input);
		this.__checkBox.id = this.GetClientID() + "_cb";
		this.__checkBox.type = "checkbox";
		this.HostElement.appendChild(this.__checkBox);
		var label = DOMObjectFactory.CreateElement(UI.HtmlTag.Label);
		label.innerText = this.__text;
		label.htmlFor = this.__checkBox.id;
		this.HostElement.appendChild(label);
		this.Reload();
		this.Listeners.AddDOMListener(this.__checkBox, "click", this.ClickHandler);		
	}]	
	,StopEvent: [decl_virtual, function() {
	}]
});

DeclareClass("UI.Controls.CollapsibleImageControl", "UI.Controls.CollapsibleChildControl", {
	constructor: function(collapsedImage, expandedImage, expanded, collapsibleParent) {
		this.base(expanded, collapsibleParent);
		this.CollapsedImage = collapsedImage;
		this.ExpandedImage = expandedImage;
		this.SetAttribute("border", "0");
	}
	,GetTagName: function() {
		return UI.HtmlTag.Image;
	}
	,SetCollapsedImage: function(collapsedImage) {
		this.CollapsedImage = collapsedImage;
		this.Reload();
	}
	,SetExpandedImage: function(expandedImage) {
		this.ExpandedImage = expandedImage;
		this.Reload();
	}
	,Reload: function() {
		if(this.HostElement)
			this.HostElement.src = cmn_GetImageUrl(this.Expanded?this.ExpandedImage:this.CollapsedImage);		
	}
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.HostElement.style.cursor = "pointer";
		this.Reload();
		this.Listeners.AddDOMListener(this.HostElement, "click", this.ClickHandler);
	}]
});

DeclareClass("UI.Controls.CollapsibleHeaderControl", "UI.Control", {
	constructor: function(text, expanded, collapsibleParent) {
		this.base();
		this.Text = text;
		this.CollapsibleParent = collapsibleParent;
		this.Expanded = expanded;
		this.SetCssClass("tool-filter-label");
		this.ImageControl = new UI.Controls.CollapsibleImageControl("filter-collapsed.png", "filter-expanded.png",this.Expanded,this.CollapsibleParent);
		this.__textClass = "tool-filter-text";
		this.__span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		this.__image = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
	}
	,GetTagName: function() {
		return UI.HtmlTag.Div;
	}
	,Init: [decl_virtual, function() {		
		this.AddControl(this.ImageControl);
		this.__link = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
		this.__link.href = "#";
		this.Listeners.AddDOMListener(this.__link, "click", this.ImageControl.ClickHandler);
	}]
	,SetCollapsedImage: function(collapsedImage) {
		if (this.ImageControl)
			this.ImageControl.SetCollapsedImage(collapsedImage);
	}
	,SetExpandedImage: function(expandedImage) {
		if (this.ImageControl)
			this.ImageControl.SetExpandedImage(expandedImage);
	}
	,SetImages: function(collapsedImage,expandedImage) {
		this.SetCollapsedImage(collapsedImage);
		this.SetExpandedImage(expandedImage);
	}
	,SetTextCssClass: function(cssClass) {
		this.__textClass = cssClass;
		this.RepaintContent();
	}
	,SetText: function(text) {
		this.Text = text;
		this.RepaintContent();
	}
	,RepaintContent: function()
	{
		this.__span.className = this.__textClass;
		this.__span.innerText = this.Text;
	}
	,Render:[decl_virtual, function(writer) {
		this.HostElement.appendChild(this.__link);
		this.ImageControl.RenderControl(this.__image);
		this.__link.appendChild(this.__image);
		this.RepaintContent();
		this.__link.appendChild(this.__span);
		this.base.Render(writer);
	}]	
});

DeclareClass("UI.Controls.ServerControlContainer", "UI.Controls.Panel", {	
	constructor: function(ctlType) {
		this.base();
		this.__ctlType = ctlType;
		this.__delem = null;
		
		this.PersistantPostParameters = {};
		this.TopHierarchyControl = null;
		this.NoDataText = null;
		this.DataLoadText = null;
		this.workspaceModules = null;
		this.__currentParameters = new dm_QueryString();
		this.__delemInited = false;
		this.GetDataOnLoad = true;
		this.ClientDataObject = null;

		this.OnDynamicElementRegistered = null;
	}

	,AttachDynamicElement: [decl_virtual, function(dynamicElement) {
		this.Dynamic = dynamicElement;

		if (this.OnDynamicElementRegistered) 
			this.OnDynamicElementRegistered(dynamicElement);
	}]

	,OnDynamicElementRegistered : [decl_virtual, function(dynamicElement) {}]

	,SetControlType: function(ctrlType) {
		this.__ctlType = ctrlType;
		if(this.__delem)
			this.__delem.DataType = ctrlType;
	}
	,RegisterModule: function(module) {
		this.OnModuleRegistered(module);
	
		if(!this.__visibleManage){
			this.__visibleManage = true;
			this.Listeners.AddObjectListener(this, "onvisiblechange", this.OnVisibilityChange);
		}
		if(!this.workspaceModules)
			this.workspaceModules = new nav_WorkspaceModulesCollection();
		if (this.workspaceModules.GetModule(module.id) == null)
				this.workspaceModules.AddModule(module);

		this.Listeners.AddCustomListener(new Utils.ModuleEventListener(module.id, null, this.OnModuleStateChange, this.OnModuleStateChange));
	}
	,LockModules : function() {
		if(this.workspaceModules) {
			this.workspaceModules.LockAllModules();
		}
	}
	,UnlockModules : function() {
		if(this.workspaceModules) {
			this.workspaceModules.UnlockAllModules();
		}
	}
	,DeleteModule: function(id) {
		if(this.workspaceModules)
			this.workspaceModules.DeleteModule(id);
	}	
	,OnModuleStateChange: function(mod) {
		this.FireEvent("onmodulesettingschange", mod);
	}
	,OnVisibilityChange: function(visible) {
		if (!this.workspaceModules)
			return;

		if(visible)
			this.workspaceModules.ShowAllModules();
		else
			this.workspaceModules.HideAllModules();
	}
	,ClearParameters : function() {
		this.__currentParameters.Clear();
		this.__currentParameters.Load(this.PersistantPostParameters)
	}
	,AddParameter : function(name, val) {
		this.__currentParameters.Delete(name);
		this.__currentParameters.Add(name, val);
	}
	,RemoveParameter : function(name) {
		this.__currentParameters.Delete(name);	
	}
	,GetTagName : function() {
		return UI.HtmlTag.Div;
	}
	,ProcessCreateData: [decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		this.__ctlType = data.getAttribute("ControlType");
		this.NoDataText = data.getAttribute("NoDataText");
		this.DataLoadText = data.getAttribute("DataLoadText");
	}]
	,OnModuleRegistered: [decl_virtual, function(module) {

	}]
	,Render: [decl_virtual, function(writer) {
		var postPatams = [];
		for(var item in this.PersistantPostParameters)
			if (this.PersistantPostParameters.hasOwnProperty(item))
				postPatams.push(item+"="+encodeURIComponent(this.PersistantPostParameters[item]));
		if(postPatams.length>0)
			this.HostElement.setAttribute("PersistantPostParameters", postPatams.join('&'));
	
		dom_setProperty(this.HostElement, "server_control", this);
		this.HostElement.setAttribute("RootUrl", WebFrameworkConfig.RootUrl);
		this.__delem = de_attachDynamicElement(this.HostElement, false);
		this.__delem.GetDataOnLoad = this.GetDataOnLoad.toString();
		this.__delem.CombineQueries(this.__currentParameters);
		this.__delem.DataType = this.__ctlType;
		this.__delem.NoDataText = this.NoDataText;
		this.__delem.RefreshOnShow = this.RefreshOnShow&&this.RefreshOnShow.toString();
		
		if(this.DataLoadText)
			this.__delem.DataLoadText = this.DataLoadText;
		this.PreInitDelem();
		if (!this.__delemInited)
			this.__delem.Init();
	}]
	,PreInitDelem : [decl_virtual, function() {
		if (this.ClientDataObject) {
			this.__delem.AddParameter(P_SUPPORT_XML, 'true');
			this.__delem.ClientDataObject = this.ClientDataObject;
		}
	}]
	,Refresh : function(txt, defer) {
		if (this.__delem) {
			this.workspaceModules = null;
			this.__delem.CombineQueries(this.__currentParameters);
			this.__delem.Refresh(txt, defer);
		}
	}
	,RefreshWSModules: function (txt) {
		if(this.workspaceModules)
			this.workspaceModules.RefreshAllModules(txt);
	}
	,Dispose : [decl_virtual, function() {
		if(this.__delem)
			this.__delem.Dispose();
		
		if(this.HostElement)
			dom_setProperty(this.HostElement, "server_control", null);
		this.base.Dispose();
	}]
});

DeclareClass("UI.Controls.WorkspaceModuleControl", "UI.Controls.ServerControlContainer", {
	constructor: function(ctlType) {
		this.base(ctlType);
		this.__keywords = [];
		this.__supportXml = false;
		this.SearchResultsText = null;
		this.ModuleName = null;
		this.DSName = null;
		this.WorkspacePanel = null;
	}
	,SetModuleName: function(name) {
		this.ModuleName = name;
		this.AddParameter(P_MODULE_NAME, name);
	}
	,PreRender : [decl_virtual, function() {
		this.AddParameter(P_XML_DATA, "true");
	}]
	,__changeStatus: function(name, st) {
		switch (st.status){
			case DE_STATUS_COMPLETE:
				var xmlDoc = new Xml.NodeAccessor(st.statusText);
				var preferencesSection = xmlDoc.SelectSingleNode("//ModulePreferences");
				if(preferencesSection)
					this.Settings = new pref_WorkspaceModuleSettings(preferencesSection);
				var htmlSection = xmlDoc.SelectSingleNode("//Html");
				if(htmlSection){
					this.__delem.SetElementHTMLEx(htmlSection.text);
					this.DSName = htmlSection.getAttribute("DSName");
				}
				this.DSName = data_parseDataUpdateXmlInternal(this.DSName, xmlDoc.xmlDoc, this.CreateCallback(this.__parseModuleMetaInfoHandler), this.CreateCallback(this.__setStatus), this.CreateCallback(this.__setDatasetDataHandler));
				this.__supportXml = true;
				break;
			default: this.__setStatus(this.DSName, st.status, st.statusText); break;
		}
		
		this.FireEvent("onstatuschange", st.status);
		return false;
	}
	,__setStatus: function(name, status, statusText, serverErrorMsg){
			var ds = data_GetDataset(name);
			if (ds != null) {
				ds.ChangeStatus({status:status, statusText:statusText});
			}
			else if (!str_IsStringEmpty(statusText))  {
				this.__delem.SetElementHTML(statusText);
			}	
			if(status == DE_STATUS_ERROR)
				ErrorToServer(serverErrorMsg || statusText);
			return;
	}
	,__parseModuleMetaInfoHandler: function(xml){
		var mInfo = data_MetaInfoXml2Obj(xml);
		if(mInfo.MetaInfo && this.Settings){
			this.Settings.changeOptions(mInfo.MetaInfo);
			this.FireEvent("onmodulesettingschange");
		}
		return mInfo.StatusText;
	}
	,__setDatasetDataHandler: function(text, data, statusText){
		data_SetDatasetData(text, data, statusText);
	}
	,AddKeywords: function(keyword1 /*, kwd2, ...*/) {
		for(var i = 0, ic = arguments.length; i < ic; i++)
			this.__keywords.push(arguments[i]);		
	}
	,Refresh : function(txt, params) {
		params = params || {};
		if (this.__delem) {
			this.__delemInited = true;
			this.ShowSearchResultsText = this.SearchResultsText &&
					(params["pname"] == P_FILTEREXPRESSION && params["pvalue"] || !params["pname"] && this.ShowSearchResultsText );
			if(this.ShowSearchResultsText) {
				this.__changeStatus(this.GetClientID(), {status:"SEARCH_RESULT_TEXT", statusText:this.SearchResultsText});
				return;
			}
			this.__supportXml = this.__supportXml && params["supportXml"]!=false;

			if (this.ClientDataObject != null)
				this.__supportXml = 'true';

			if (params["pname"] != null)
				this.__delem.AddParameter(params["pname"], params["pvalue"]);
			this.AddParameter(P_SUPPORT_XML, this.__supportXml);
			this.__delem.CombineQueries(this.__currentParameters);
			this.__delem.Refresh(txt/*, params["skipExecution"]*/);
		}
	}
	,AMLoad : [decl_virtual, function(txt, params) {
		this.Refresh(txt, params);
	}]
	,OnVisibleChange : function(v) {
		if(!v || !this.ShowSearchResultsText)
			this.__delem.OnDisplayChange(v);
	}
	,PreInitDelem :[decl_virtual, function() {
		this.base.PreInitDelem();
		this.__delem.CustomRequestHandler = this.CreateCallback(this.__changeStatus);
		this.KeywordsAttach(this.__keywords.join(","), true, this.WorkspacePanel);
		this.Listeners.AddObjectListener(this, "onvisiblechange", this.OnVisibleChange);
	}]
	,ProcessCreateData :[decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		var kwds = data.getAttribute("Keywords");
		if(kwds)
			this.AddKeywords(kwds.split(','));
		var moduleName = data.getAttribute("ModuleName");
		if(moduleName)
			this.SetModuleName(moduleName);
	}]
});

DeclareClass("UI.Controls.MultiStateControl", "UI.Control", {	
	constructor: function(defaultState) {
		this.base();
		this.__states = [];
		this.__queue = [];
		this.__defaultState = str_IsStringEmpty(defaultState) ? UI.CheckBoxStates.UNCHECKED : defaultState;
		this.__currentState = this.__defaultState;		
	}
	,GetTagName : function() {
		return UI.HtmlTag.Span;
	}
	,RegisterState :  [decl_virtual, function(code,css,selectable) {
		this.__queue[code] = this.__states.length;
		this.__states.push({Code: code, Css: css, Selectable: selectable});		
	}]
	,GetState : function() {
		return this.__currentState;
	}
	,SetState : [decl_virtual, function(state) {
		if (this.__currentState == state) return;
		this.__currentState = state;
		this.Paint();
	}]
	,__GetNextState : function(selectable) {
		var idx = this.__GetRange();
		if (str_IsStringEmpty(idx))
			return null;
		idx++;
		if (!selectable) {
			if (idx == this.__states.length)
				idx = 0;
		}
		else
		{
			var len = this.__states.length;
			var step = 0;
			var start = (idx == len ? 0 : idx);
			idx = null;
			for (var i = start; i < len;)
			{
				if (this.__states[i].Selectable)
				{
					idx = i;
					step = len;
					i = len;
				}
				else
				{
					step++;
					if (step == len - 1)
					{
						idx = i;
						step = len;
						i = len
					}
					else
					{
						i++;
						if (i == len) i = 0;
					}					
				}
			}
		}
		if (idx == null) return null;
		return this.__states[idx];
	}
	,__GetRange : function() {
		var idx = this.__queue[this.__currentState];
		if (str_IsStringEmpty(idx))
			idx = this.__queue[this.__defaultState];
		return idx;
	}
	,__GetCurrentState : function() {
		var idx = this.__GetRange();
		if (str_IsStringEmpty(idx))
			return null;
		return this.__states[idx];
	}
	,Paint : [decl_virtual, function() {
		var objState = this.__GetCurrentState();
		if (!objState) {
			this.SetVisibleState(false);
			return;
		}
		if (!this.IsVisible())
			this.SetVisibleState(true);
		if (this.HostElement)
			this.HostElement.className = objState.Css;		
	}]
	,Click : function() {
		var objState = this.__GetNextState(true);
		if (objState)
			this.OnClick(objState.Code);
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}	
	,OnClick :[decl_virtual, function(state) {
		this.SetState(state);
		this.FireEvent("click",this,this.__currentState);
	}]
	,Render :[decl_virtual, function(writer) {
		this.base.Render();
		this.HostElement.innerHTML = "&nbsp;";
		this.Listeners.AddDOMListener(this.HostElement,"click",this.Click);
		this.Paint();
	}]
});

DeclareClass("UI.Controls.Label", "UI.Control", {
	constructor: function(text) {
		this.base();
		this.__text = text;
	}
	,GetTagName : function() {
		return UI.HtmlTag.Span;
	}
	,Render : [decl_virtual, function(writer) {
		this.HostElement.innerText = this.__text;
	}]
});
//---------------UI.DOMControls.Image-------------
DeclareClass("UI.DOMControls.Image", "UI.DOMControls.Control", {
	constructor : function(image, cssClass) {
		this.base();
		this.image = image;
		this.SetCssClass(cssClass);
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		this.parent.src = cmn_GetImageUrl(this.image);
		return this.parent;
	}]
	,GetTagName : function() { return UI.HtmlTag.Image; }
	,SetImage : function(image) {
		this.image = image;
		if (this.parent)
			this.parent.src = cmn_GetImageUrl(image); 
	}
});
//---------------UI.Controls.Image-------------
DeclareClass("UI.Controls.Image", "UI.Control", {
	constructor: function(image, height, width) {
		this.base();
		this.domObj = new UI.DOMControls.Image(image);
		this.SetWidth(width);
		this.SetHeight(height);
	}
	,GetTagName : function() { return this.domObj.GetTagName(); }
	,SetImage : function(image) { this.domObj.SetImage(image); }
	,Render : [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.domObj.Render(this.HostElement);
		this.Listeners.AddDOMListener(this.HostElement, "click", this.OnClick);
	}]
	,OnClick: function(e) { this.FireEvent("onclick", e, this);	}
});

//---------------UI.DOMControls.Td-------------
DeclareClass("UI.DOMControls.Td", "UI.DOMControls.Control", {
	constructor : function() {
		this.base();
		this.args = (arguments.lenght = 1 && arguments[0] instanceof Array) ? arguments[0] : arguments;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		if (this.colSpan) this.parent.colSpan = this.colSpan;
		if (this.rowSpan) this.parent.rowSpan = this.rowSpan;
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			this.parent.appendChild(args[i].Obj());
		return this.parent;
	}]
	,GetTagName : function() { return UI.HtmlTag.Td; }
	,SetColSpan : function(val) {
		this.colSpan = val;
		if (this.parent)
			this.parent.colSpan = this.colSpan;
	}
	,SetRowSpan : function(val) {
		this.rowSpan = val;
		if (this.parent)
			this.parent.rowSpan = this.rowSpan;
	}
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			args[i].Dispose();
	}]
});
//---------------UI.DOMControls.Tr-------------
DeclareClass("UI.DOMControls.Tr", "UI.DOMControls.Control", {
	constructor : function() {
		this.base();
		this.args = (arguments.lenght = 1 && arguments[0] instanceof Array) ? arguments[0] : arguments;
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			this.parent.appendChild(args[i].Obj());
		return this.parent;
	}]
	,GetTagName : function() { return UI.HtmlTag.Tr; }
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			args[i].Dispose();
	}]
});
//---------------UI.DOMControls.Table-------------
DeclareClass("UI.DOMControls.Table", "UI.DOMControls.Control", {
	constructor : function() {
		this.base();
		this.args = (arguments.lenght = 1 && arguments[0] instanceof Array) ? arguments[0] : arguments;
		this._border = this._cellPadding = this._cellSpacing = 0;
		this._width = "100%";
	}
	,Render : [decl_virtual, function(parent) {
		this.base.Render(parent);
		var tbody = DOMObjectFactory.CreateElement(UI.HtmlTag.TBody);
		this.parent.border = this._border;
		this.parent.cellPadding = this._cellPadding;
		this.parent.cellSpacing = this._cellSpacing;
		this.parent.style.width = this._width;
		this.parent.appendChild(tbody);
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			tbody.appendChild(args[i].Obj());
		return this.parent;
	}]
	,GetTagName : function() { return UI.HtmlTag.Table; }
	,SetBorder: function(value) { 
		this._border = value;
		if (this.parent)
			this.parent.border = this._border;
	}
	,SetCellPadding: function(value) { 
		this._cellPadding = value;
		if (this.parent)
			this.parent.cellPadding = this._cellPadding;
	}
	,SetCellSpacing: function(value) { 
		this._cellSpacing = value;
		if (this.parent)
			this.parent.cellSpacing = this._cellSpacing;
	}
	,SetWidth: function(val) { 
		this._width = val;
		if (this.parent)
			this.parent.style.width = this._width;
	}
	,Dispose: [decl_virtual, function(parent) {
		this.base.Dispose();
		for (var i = 0, args = this.args, ic = args.length; i < ic; ++i)
			args[i].Dispose();
	}]
});

DeclareClass("UI.Controls.MultiStateCheckBox", "UI.Control", {
	constructor: function(defaultstate, text, css) {
		this.base();
		this.__mscontrol = new UI.Controls.MultiStateControl(defaultstate);
		this.__text = text;
		this.__css = css;
	}
	,GetTagName : function() {
		return UI.HtmlTag.Div;
	}
	,Init : [decl_virtual, function() {
		this.AddControl(this.__mscontrol);
		this.AddControl(new UI.Controls.Label(this.__text));
		this.SetCssClass(this.__css);
	}]
	,RegisterState :  function(code, css, selectable) {
		this.__mscontrol.RegisterState(code,css,selectable);
	}
	,AttachEvent : function(evnt, handler) {
		this.__mscontrol.AttachEvent(evnt, handler);
	}
	,SetState : [decl_virtual, function(state) {
		this.__mscontrol.SetState(state);
	}]
});

DeclareClass("UI.Controls.DoubleStateControl", "UI.Controls.MultiStateControl", {
	constructor: function(defaultState, checkedCss, uncheckedCss) {
		this.base(defaultState);
		this.__checkedCss = str_IsStringEmpty(checkedCss)? "box-checked" : checkedCss;
		this.__uncheckedCss = str_IsStringEmpty(uncheckedCss)? "box-default" : uncheckedCss;
	}
	,Init :[decl_virtual, function() {
		this.base.Init();
		this.RegisterState(UI.CheckBoxStates.UNCHECKED,this.__uncheckedCss,true);
		this.RegisterState(UI.CheckBoxStates.CHECKED,this.__checkedCss,true);
	}]
});

DeclareClass("UI.Controls.TripleStateCheckBox", "UI.Controls.MultiStateCheckBox", {	
	Init :[decl_virtual, function() {
		this.base.Init();
		this.RegisterState(UI.CheckBoxStates.UNCHECKED,"box-default",true);
		this.RegisterState(UI.CheckBoxStates.PARTIALCHECKED,"box-mixed",false);
		this.RegisterState(UI.CheckBoxStates.CHECKED,"box-checked",true);
	}]
});

DeclareClass("UI.Controls.WorkspacePanel", "SiteLayout.ModulePanel", {
	constructor: function() {
		this.base();
		this.wsModule = null;
		this.wsMoreLink = null;
		this.wsPopup = null;
		this.wsPopupModule = null;
		this.moreLink = null;
	}
	,ProcessCreateData :[decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		this.HeaderText = data.getAttribute("HeaderText");
		this.HeaderCssClass = data.getAttribute("HeaderCssClass");
		this.ContentCssClass = data.getAttribute("ContentCssClass");
		this.FooterCssClass = data.getAttribute("FooterCssClass");
		this.ControlType = data.getAttribute("ControlType");
		this.Keywords = data.getAttribute("Keywords");
		this.ModuleName = data.getAttribute("ModuleName");
		this.Collapsed = data.getAttribute("Collapsed");
		if(this.Collapsed)
			this.Collapsed = this.Collapsed=="true";
	}]
	,Init :[decl_virtual, function() {
		this.base.Init();
		if(this.Collapsed){
			this.HeaderText = "<div class='"+this.HeaderCssClass+"'>"+ this.HeaderText + "</div>";
			this.HeaderCssClass = "";
		}
		if(this.ControlType){
			if(!this.wsModule){
				this.wsModule = new UI.Controls.WorkspaceModuleControl(this.ControlType);
				this.wsModule.WorkspacePanel = this;
				this.AddContentControl(this.wsModule);
				this.Listeners.AddObjectListener(this.wsModule, "onmodulesettingschange", this.OnSettingsChange);
			}
		}
		if(this.ContentCssClass)
			this.__GetContentControl().SetCssClass(this.ContentCssClass);
		if(this.Keywords)
			this.wsModule.AddKeywords(this.Keywords.split(','));
		if(this.ModuleName)
			this.wsModule.SetModuleName(this.ModuleName);
		if(this.FooterCssClass)
			this.__GetFooterControl().SetCssClass(this.FooterCssClass);
	}]
	,Render :[decl_virtual, function(writer) {
		if(this.Collapsed!=null){
			this.Collapsed = !this.Collapsed;
			this.OnCollapseChange();
		}
		
		this.base.Render(writer);
		
		if(this.Collapsed!=null)
			this.Listeners.AddDOMListener(this.HostElement.firstChild, "click", this.OnCollapseChange);
	}]
	,OnCollapseChange: function(){
		this.SetHeaderCss(this.Collapsed?"hdr-expanded":"hdr-collapsed");
		if(this.ContentControl)
			this.ContentControl.SetVisibleState(this.Collapsed);
		if(this.FooterControl)
			this.FooterControl.SetVisibleState(this.Collapsed);
		this.Collapsed = !this.Collapsed;
	}
	,OnSettingsChange: function() {
		var prefs = this.wsModule.Settings;
		if(!this.wsPopup &&  prefs.getHasNextPage() == "true" && prefs.getExtraItemsCount() > 0 )
			this.CreateMoreLink(this.wsModule.ModuleName);
		(function(ctl){
			ctl.__ApplyFilters("PreferenceChange", prefs);
			for(var i=0, j=ctl.__controls.length; i<j; i++)
					arguments.callee(ctl.__controls[i]);
		})(this);
	}
	,CreateMoreLink: function(moduleName) {
		this.moreLink = new SiteLayout.LeftMenuItem();
		this.moreLink.Title = "more...";		
		this.moreLink.SetCssClass("lmodule-more");
		this.Listeners.AddObjectListener(this.moreLink, "click", this.__onMoreClick);
		this.AddContentControl(this.moreLink);		
		this.wsPopupModule = new UI.Controls.WorkspaceModuleControl(this.wsModule.__ctlType);
		if(this.Keywords)
			this.wsPopupModule.AddKeywords(this.Keywords.split(','));
		this.wsPopupModule.PersistantPostParameters[P_PARENT_MODULE_NAME] = moduleName;
		this.wsPopupModule.SetVisibleState(false);
		
		this.wsPopup = new UI.Controls.BorderedPopupArea();
		this.Listeners.AddObjectListener(this.wsPopup, "hide", this.__onHidePopup);
		this.wsPopup.SetMainCssClass("border-popup");
		this.wsPopup.MaxWidth = 215; this.wsPopup.MinWidth = 215;  this.wsPopup.MinHeight = 30; this.wsPopup.MaxHeight = 300;
		this.wsPopup.AddControl(this.wsPopupModule);
		this.AddContentControl(this.wsPopup);
		
		var filter = new UI.ModulePreferenceFilter();
		filter.Param = "HasNextPage"; filter.Value = "true"; filter.Operation = "==";
		filter.Init();
		this.moreLink.AddFilter(filter);
	}
	,__onMoreClick: function() {
		Utils.MonitoringHelper.SetMonitoringInfo(MA_OpenMoreItems, null, 300);
		var options = new UI.PopupareaOptions(this.moreLink.HostElement);
		options.objVAlignment = UI.VAlignment.Center;
		options.objHAlignment = UI.HAlignment.Right;
		options.vAlignment = UI.VAlignment.Center;
		options.hAlignment = UI.HAlignment.Right;
		this.wsPopup.ShowPopup(options);
		this.wsPopupModule.SetVisibleState(true);
	}
	,__onHidePopup: function() {
		this.wsPopupModule.SetVisibleState(false);
	}
});
//--------------------- TPListBox ----------------------------
DeclareClass("UI.Controls.TPListBox", "UI.Control", {
	constructor : function(width, height, showToolTip, multiselect, showHorizontalScrollBar, onkeydown) {
		this.base();
		this.__cache = null;
		this.__table = null;
		this.__div = null;
		this.SetWidth(width ? width : "100%");
		this.SetHeight(height ? height : "100%");
		this.showToolTip = showToolTip==false?false:true;
		this.multiselect = multiselect==false?false:true;
		this.showHorizontalScrollBar = showHorizontalScrollBar == true?true:false;
		this.SelectionColor = "#003399";
		this.TextSelectionColor = "#FFFFFF";
		this.TextColor = "Black";
		this.sorting = true;
		this.onkeydown = onkeydown?onkeydown:"";
		
		this.__values = [];
		
		if((new dom_BrowserInfo).IsSafari())		
			this.SetCssClass("lb-tp-padding");			
		else
			this.SetCssClass("lb-tp");
			
		this.SetAttribute("cellPadding", 0);
		this.SetAttribute("cellSpacing", 0);
		this.SetAttribute("border", 0);
		this.SetAttribute("align", "left");
	}
	,GetTagName : function() { 
		return UI.HtmlTag.Table;
	}
	,Init :[decl_virtual, function() {
		this.base.Init();
		
		this.__div = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		this.__div.className = "lb-div";
		this.__div.align = "center";
		this.__div.style.width = this.GetWidth();
		this.__div.style.height = this.GetHeight();
		this.__div.style.overflowX = this.showHorizontalScrollBar ? "auto" : "hidden";
		
		this.__table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		this.__table.cellPadding = 0;
		this.__table.cellSpacing = 0;
		this.__table.border = 0;
		this.__table.setAttribute("UNSELECTABLE","on");
		this.__table.className = "lb-table";
		this.__table.setAttribute("SelectionColor",this.SelectionColor);
		this.__table.setAttribute("TextSelectionColor",this.TextSelectionColor);
		this.__table.setAttribute("TextColor",this.TextColor);		
		this.__div.appendChild(this.__table);
	
		this.__BuildTable();
	}]
	,Render : [decl_virtual, function(writer) {
		this.base.Render(writer);
		
		this.HostElement.multiselect = "true";
		this.HostElement.setAttribute("ShowToolTip",this.showToolTip);
		this.HostElement.setAttribute("Sorting",this.sorting);
		this.HostElement.setAttribute("multiselect",this.multiselect);	
		this.Listeners.AddDOMListener(this.HostElement, "keydown", this.OnKeyDown);
		
		var row = this.HostElement.insertRow();
		var cell = row.insertCell();
		cell.appendChild(this.__div);
	}]
	,IsSorted : function() {
		return this.sorting;
	}
	,OnKeyDown : function() {
		tplb_KeyDown(this.onkeydown, event);
	}
	,GetValueByName : function(name) {
		for (var i = 0, v = this.__values, ic = v.length; i < ic; ++i)
			if (v[i].name == name)
				return v[i].value;
		return null;
	}
	,IndexOf: function(value) {
		for (var i = 0, v = this.__values, ic = v.length; i < ic; ++i)
			if (v[i].value == value)
				return i;
		return -1;		
	}
	,__AddValue: function(name, value, index, onlyUnique) {
		if (name == "") return false;
		var iov = this.IndexOf(value);
		var v = this.__values;
		if (onlyUnique == true && iov > -1) {
			if (v[iov].name != name) {
				v[iov].name = name;
				this.__BuildTable();
			}
			return false;
		}
		var pos = (index == null) ? -1 : index;
		if (pos == -1)
			v[v.length] = {"name":name, "value":value};
		else
		{
			for (var i = 0, len = v.length, ic = len - pos; i < ic; ++i) {
				var idx = len-i;
				v[idx] = v[idx-1];
			}
			v[pos] = {"name":name, "value":value};
		}
		return true;
	}
	,AddValue : function(name, value, index, onlyUnique) {
		var res = this.__AddValue(name, value, index, onlyUnique);
		if (res && this.__IsInitialized()) {
			var table = this.__table, position = (index == null) ? -1 : index; 
			var tr = table.insertRow(position);
			this.Listeners.AddDOMListener(tr, "mousedown", this.__OnMouseSelect);
			tr.UNSELECTABLE = "on";
			
			var tdName = tr.insertCell();
			tdName.style.paddingLeft = "2px";
			tdName.UNSELECTABLE = "on";
			tdName.noWrap = "on";
			tdName.innerText = name ;
			if (this.showToolTip)
				tdName.title = name;
				
			var tdValue = tr.insertCell();
			tdValue.style.display = "none";
			tdValue.innerText = value;
		}
		return res;
	}
	,AddValues: function(values, onlyUnique, dispAttr, sorted) {
		if (!dispAttr) dispAttr = "name";
		if (typeof(sorted) == "undefined") sorted = true;
		var isChanged = false;
		for (var i = 0, ic = values.length; i < ic; ++i){
			var name = values[i][dispAttr];
			if (this.__AddValue(name, values[i].value, sorted?this.GetSortedIndex(name):-1, onlyUnique))
				isChanged = true;
		}
		if (isChanged)
			this.__BuildTable();
	}
	,__BuildTable: function() {
		if (!this.__IsInitialized()) return;
		var table = this.__table.firstChild;
		if(table == null || table.tagName.toLowerCase()!="tbody")
			table = this.__table;
		
		while (table.rows.length > 0)
			table.deleteRow(0);
			
		for (var i = 0, v = this.__values, ic = v.length; i < ic; ++i) {
			var tr = document.createElement("tr");
			this.Listeners.AddDOMListener(tr, "mousedown", this.__OnMouseSelect);
			tr.UNSELECTABLE = "on";
		
			var tdName = document.createElement("td");
			tdName.style.paddingLeft = "2px";
			tdName.noWrap = "on";
			tdName.UNSELECTABLE = "on";
			
			var name = v[i].name;
			tdName.innerText = name;
			if(this.showToolTip)
				tdName.title = name;

			var tdValue = document.createElement("td");
			tdValue.style.display = "none";
			tdValue.innerText = v[i].value;
			
			tr.appendChild(tdName);
			tr.appendChild(tdValue);
			table.appendChild(tr);
		}
	}
	,DelByValue : function(value) {
		var res = [], isChanged = false;
		for (var i = 0, j = 0, v = this.__values, ic = v.length; i < ic; ++i) {
			if (v[i].value == value) {
				isChanged = true;
				continue;
			}
			res[j++] = this.__values[i];
		}
		this.__values = res;
		if (isChanged && this.__IsInitialized()) {
			var table = this.__table;
			for (var i = 0, r = table.rows; i < r.length; ++i) {
				if (r[i].children[1].outerText == value)
					table.deleteRow(i--);
			}
		}
	}
	,DelValue : function(name, value) {
		var res = [], isChanged = false;
		for (var i = 0, j = 0, v = this.__values, ic = v.length; i < ic; ++i) {
			if (v[i].name == name && v[i].value == value) {
				isChanged = true;
				continue;
			}
			res[j++] = this.__values[i];
		}
		this.__values = res;
		if (isChanged && this.__IsInitialized()) {
			var table = this.__table;
			for (var i = 0, r = table.rows; i < r.length; ++i) {
				if (r[i].children[1].outerText == value && r[i].children[0].outerText == name)
					table.deleteRow(i--);
			}
		}
	}
	,__OnMouseSelect : function() {
		event.returnValue = false;
		tplb_div = this.__div;
		
		if(this.__table.rows.length == 0)
			return false;
			
		tplb_div.focus();	
		tplb_UnselectAll(this.__table, event);
		
		if(event.shiftKey)
			tplb_ShiftSelection(this.__table, event);
		else if(event.ctrlKey)
			tplb_Selection(event.srcElement.parentElement);
		else
			tplb_Select(event.srcElement.parentElement);	
			
		tplb_div.tplb_last_element = event.srcElement.parentElement;	
		tplb_StartSelection(event);	
		
		return false;
	}
	,LoadFromCache : function(cache) {
		this.__cache = cache;
		this.__LoadFromCache();
		this.__BuildTable();
	}
	,MoveSelectRows : function(dest, onlyUnique) {
		onlyUnique = (typeof(onlyUnique) != "undefined" ? onlyUnique : false);
		var table = this.__table;
		var res = [];
		if (table.rows.length < 1) return res;
		var numRows = table.rows.length, isSelected = false;
		for (var i = 0, j = 0; i < numRows; i++)
		{
			var r = table.rows[i]; 
			if (r.is_selected == true)
			{
				isSelected = true;
				var text = r.children[0].outerText;
				if (dest.AddValue(text, r.children[1].outerText, dest.GetSortedIndex(text), onlyUnique)) {
					res[j++] = {"text":text,"value":r.children[1].outerText};
				}
			}
		}
		if (isSelected) {
			this.DeleteSelected();
			tplb_ClearSelections(dest);
			if (tplb_div != null)
				tplb_div.tplb_last_element = null;
		}
		return res;
	}	
	,Clear : function() {
		this.__values = [];
		if (this.__IsInitialized()) {
			var table = this.__table;
			if (table.rows.length == 0) return;
			tplb_div = table.parentElement;		
			tplb_div.tplb_start_index = null;
			tplb_div.tplb_last_element = null;
			for (var i = 0; i < table.rows.length; i++)
				table.deleteRow(i--);
		}
	}
	,MoveAllRows : function(dest) {
		if (dest) {
			for (var i = 0, v = this.__values, ic = v.length; i < ic; ++i)
			{
				var name = v[i].name;
				dest.AddValue(name, v[i].value, dest.GetSortedIndex(name));
			}
		}
		this.Clear();
		if (tplb_div != null)
			tplb_div.tplb_last_element = null;
	}
	,DeleteSelected : function() {
		var table = this.__table;
		for (var i = table.rows.length-1, row; i>=0; i--) {
			row=table.rows[i];
			if (row.is_selected == true)
				this.DelValue(row.children[0].outerText, row.children[1].outerText);
		}
	}
	,GetSortedIndex : function(text) {
		text = text && text.toLowerCase();
		if (this.__values.length==0 || this.__values[this.__values.length - 1].name.toLowerCase() <= text) return -1;
		var top = 0, bottom = this.__values.length - 1;
		while(top < bottom) {
			if (bottom - top == 1)
				return (this.__values[top].name.toLowerCase() > text)? top : bottom;
			var tmp = top + Number(((bottom - top) >> 1).toFixed(0));
			if (this.__values[tmp].name.toLowerCase() > text)
				bottom = tmp;
			else
				top = tmp;			
		}
		return top;
		
	}
	,SelectItemByIndex : function(index) {
		if(index<this.__table.rows.length)
			this.__table.rows[index].is_selected = true;
	}	
	,UnselectItemByIndex : function(index) {
		if(index<this.__table.rows.length)
			this.__table.rows[index].is_selected = false;
	}		
	,GetSelectedItems : function() {
		var table = this.__table, res = [];
		if (this.__IsInitialized())
			for (var i = 0, ic = table.rows.length; i < ic; ++i) {
				var r = table.rows[i]; 
				if (r.is_selected == true)
					res.push({"text":r.children[0].outerText,"value":r.children[1].outerText});
			}
		return res;
	}
	,GetItems : function() {
		var res = [];
		for (var i = 0, v = this.__values, ic = v.length; i < ic; ++i)
			res.push({"text":v[i].name,"value":v[i].value});
		return res;
	}
	,GetItemCount : function() {
		return this.__values.length;
	}
	,GetSelectedItemCount : function() {
		var table = this.__table, res = 0;
		if (this.__IsInitialized()) {
			for (var i=0, r = table.rows, ic=r.length; i<ic; ++i)
				if (r[i].is_selected == true)
					++res;
		}
		return res;
	}
	,SetSelectedScript : function(script) {
		if (!str_IsStringEmpty(script))
			this.SetAttribute("OnSelected", script);
	}
	,__IsInitialized : function() {
		return this.__table && this.__table.rows;
	}
	,__LoadFromCache : function() {
		var cache = this.__cache;
		if (!cache) return;
		var ic = cache.length;
		if (ic > 0) {
			if (typeof(cache[0]) == "object") 
				for(var i=0; i<ic; ++i)
					this.__AddValue(cache[i]["text"], cache[i]["value"]);
			else 
				for(var i=0; i<ic; ++i)
					this.__AddValue(cache[i], cache[i]);
		}
	}
});
//--------------------- TextBoxSpan -------------------------------
DeclareClass("UI.Controls.TextBoxSpan", null, 
{
	constructor: function(text, css)
	{
		this.text = text;
		this.css = css;
	}
});
//--------------------- TextBoxRow -------------------------------
DeclareClass("UI.Controls.TextBoxRow", null, 
{
	constructor: function(arTextBoxSpan, css)
	{
		this.arTextBoxSpan = arTextBoxSpan;
		this.css = css;
	}
});
//--------------------- TextBox -------------------------------
DeclareClass("UI.Controls.TextBox", "UI.Control", 
{
	constructor: function(arTitles, arFooters, width, height)
	{
		this.base();
		this.arTitles = arTitles;
		this.arFooters = arFooters;
		this.textArea = new UI.Controls.TextArea(width, height);
		this.stringValue = null;
		this.wordValue = [];
	}
	,Dispose: [decl_virtual, function() 
	{
		this.wordValue = null;
		this.base.Dispose();
	}]
	,GetTagName: function() 
	{ 
		return UI.HtmlTag.Div; 
	}
	,SetStringValue: function(value, fireEvent) 
	{
		if (typeof(value)=="undefined") return;
		if (this.stringValue != value)
		{
			fireEvent = typeof(fireEvent) != "undefined" ? fireEvent : true;
			this.stringValue = value;
			//var res = [], ar = this.stringValue.split(',');
			var res = [], ar = this.stringValue.match(/\w+|\"[^\"]*\"/ig);
			if(ar==null)
				ar = [];
			for (var i = 0, ic = ar.length; i<ic; ++i)
			{
				var v = ar[i].trim();
				if (v != "")
					res[res.length] = v;				
			}
			if (this.wordValue.length != res.length)
			{
				this.wordValue = res;
				if (fireEvent)
					this.FireEvent("onchange", this.wordValue);
				return;	
			}
			else
			{
				for (var i = res.length - 1; i >= 0; --i)
				{
					if (this.wordValue[i] != res[i])
					{
						this.wordValue = res;
						if (fireEvent)
							this.FireEvent("onchange", this.wordValue);
						return;
					}					
				}				
			}						
		}
	}
	,Init: [decl_virtual, function() 
	{
		this.Listeners.AddObjectListener(this.textArea, "onblur", this.OnBlur);
		this.SetStringValue(this.textArea.value);
		this.AddControl(this.textArea);
	}]
	,Render : [decl_virtual, function() 
	{
		var rows = [];
		
		if (this.arTitles)
		{
			for (var i = 0, ic = this.arTitles.length; i < ic; ++i)
			{
				var textBoxRow = this.arTitles[i];
				
				var arTextBoxSpan = textBoxRow.arTextBoxSpan;
				var texts = [];
				
				if (arTextBoxSpan)
				{
					for (var j = 0, jc = arTextBoxSpan.length; j < jc; ++j)
					{
						var text = arTextBoxSpan[j].text;
						var css = arTextBoxSpan[j].css; 
					
						var textCtr = new UI.DOMControls.Text(text);
						textCtr.SetCssClass(css);
						texts[texts.length] = textCtr;
					}
				}
				 
				var title = new UI.DOMControls.Tr(new UI.DOMControls.Td(texts));
				title.SetCssClass(textBoxRow.css);
				
				rows[rows.length] = title;
			}
		}
		
		var td = new UI.DOMControls.Td();
		rows[rows.length] = new UI.DOMControls.Tr(td);
		
		if (this.arFooters)
		{
			for (var i = 0, ic = this.arFooters.length; i < ic; ++i)
			{
				var textBoxRow = this.arFooters[i];
				
				var arTextBoxSpan = textBoxRow.arTextBoxSpan;
				var texts = [];
				if (arTextBoxSpan)
				{
					for (var j = 0, jc = arTextBoxSpan.length; j < jc; ++j)
					{
						var text = arTextBoxSpan[j].text;
						var css = arTextBoxSpan[j].css; 
					
						var textCtr = new UI.DOMControls.Text(text);
						textCtr.SetCssClass(css);
						texts[texts.length] = textCtr;
					}
				}
				 
				var title = new UI.DOMControls.Tr(new UI.DOMControls.Td(texts));
				title.SetCssClass(textBoxRow.css);
				
				rows[rows.length] = title;
			}
		}
		
		var table = new UI.DOMControls.Table(rows);
		table.SetCellSpacing(2);
		this.HostElement.appendChild(table.Obj());
		
		this.textArea.RenderControl(td.Obj());
	}]
	,OnBlur: function(value) 
	{
		this.SetStringValue(this.textArea.GetValue());
		return true;
	}
	,GetValue: function() 
	{
		return this.wordValue;
	}
	,SetText: function(value, fireEvent) 
	{
		this.SetStringValue(value, fireEvent)
		if (this.textArea)
			this.textArea.SetValue(value, fireEvent);
	}
	,Clear: function(fireEvent) 
	{
		fireEvent = typeof(fireEvent) != "undefined" ? fireEvent : true;
		if (this.textArea)
			this.textArea.SetValue('', fireEvent);
		this.SetStringValue('', fireEvent);
	}
});
//--------------------- TextArea -------------------------------
DeclareClass("UI.Controls.TextArea", "UI.Control", {
	constructor : function(width, height) {
		this.base();
		this.currentValue = "";
		this.currentFireEvent = true;
		this.SetWidth(width);
		this.SetHeight(height);
	}
	,GetTagName : function() { 
		return UI.HtmlTag.TextArea; 
	}
	,Render : [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.Listeners.AddDOMListener(this.HostElement, "blur", this.OnBlur);
		this.Listeners.AddDOMListener(this.HostElement, "keydown", this.OnKeyDowm);
		
		this.SetTextAreaValue();
	}]
	,OnBlur: function() {
		this.FireEvent("onblur", this.HostElement.value);
	}
	,OnKeyDowm: function() {
		this.FireEvent("onkeydown", this.HostElement.value);
	}	
	,GetValue: function() {
		return this.HostElement.value;
	}
	,SetTextAreaValue: function() {
		if (this.HostElement) {
			this.HostElement.value = this.currentValue;
			this.currentFireEvent = typeof(this.currentFireEvent) != "undefined" ? this.currentFireEvent : true;
			if (this.currentFireEvent)
				this.FireEvent("onblur", this.HostElement.value);
		}
	}
	,SetValue: function(value, fireEvent) {
	    this.currentValue = value;
		this.currentFireEvent = fireEvent;
		this.SetTextAreaValue();
	}
});
//--------------------- CheckBox -------------------------------
DeclareClass("UI.Controls.CheckBox", "UI.Control", {
	constructor : function(title, value, checked) {
		this.base();
		this.title = title;
		this.value = (typeof(value) != "undefined")? value : null;
		this.checked = (typeof(checked) != "undefined")? checked : false;
		this.isInit = true;
		this.inp = null;
		this.lab = null;
	}
	,Dispose: [decl_virtual, function() {
		this.inp = null;
		this.lab = null;
		this.base.Dispose();
	}]
	,GetTagName : function() { 
		return UI.HtmlTag.Div; 
	}
	,Render : [decl_virtual, function(writer) {
		this.base.Render(writer);
		
		this.inp = DOMObjectFactory.CreateElement(UI.HtmlTag.Input);
		this.inp.type = "checkbox";
		this.HostElement.appendChild(this.inp);
		this.Listeners.AddDOMListener(this.inp, "click", this.OnClick);
		this.inp.checked = this.checked;
		this.OnClick();
		this.isInit = false;
		
		this.lab = DOMObjectFactory.CreateElement(UI.HtmlTag.Label);
		this.lab.innerText = this.title;
		this.lab.forHtml = this.inp.id;
		this.lab.className = "cb-label";
		this.Listeners.AddDOMListener(this.lab, "click", this.OnLabelClick);
		this.HostElement.appendChild(this.lab);
	}]
	,IsChecked : function() {
		return this.inp ? this.inp.checked : this.checked
	}
	,GetValue : function() {
		return this.value; 
	}
	,SetChecked: function(bValue) {
		this.checked = bValue;
		if (this.inp)		
			this.inp.checked = this.checked;		
		this.OnClick();
	}
	,OnClick : function() {
		this.FireEvent("onclick", this.IsChecked(), this.GetValue(), this.isInit);	
	}
	,OnLabelClick : function() {
		this.inp.checked = !this.inp.checked;
		this.OnClick();
	}
});
//--------------------- RadioButton -------------------------------
DeclareClass("UI.Controls.RadioButton", "UI.Control", {
	constructor : function(title, value, checked) {
		this.base();
		this.title = title;
		this.value = value;
		this.name = "";
		this.id = "";
		this.inp = null;
		this.checked = !checked?false:true;
		this.lab = null;
		this.panel = null;
	}
	,Dispose: [decl_virtual, function() {
		this.lab = null;
		this.panel = null;
		this.inp = null;
		this.base.Dispose();
	}]
	,GetTagName : function() { 
		return UI.HtmlTag.Div; 
	}
	,Init: [decl_virtual, function() {
		this.inp = DOMObjectFactory.CreateElement(UI.HtmlTag.Input, false, null, this.name);
		this.inp.id = this.id;
		this.inp.type = "radio";
		this.Listeners.AddDOMListener(this.inp, "click", this.OnClick);
		
		this.lab = DOMObjectFactory.CreateElement(UI.HtmlTag.Label);
		this.lab.innerText = this.title;
		this.lab.htmlFor = this.id;
		this.lab.className = "rb-label";
	}]
	,Render : [decl_virtual, function(writer) {
		this.base.Render(writer);
		
		this.HostElement.appendChild(this.inp);
		if (this.panel) {
			if (this.panel.isInit == false)
				this.inp.checked = this.checked;
			else
				if (this.panel.radioButtonValue == this.value)
					this.inp.checked = true;
		}
		else
			this.inp.checked = this.checked;
					
		this.FireEvent("onclick", true, true);
		
		this.HostElement.appendChild(this.lab);
	}]
	,IsChecked : function() {
		return true && this.inp.checked;
	}
	,SetChecked: function(bValue, fireEvent) {
		if (!this.inp) return;
		fireEvent = (typeof(fireEvent) != "undefined") ? fireEvent : true; 
		var curChecked = true && this.inp.checked;
		if (curChecked != bValue)
		{
			this.inp.checked = bValue;
			this.FireEvent("onclick", fireEvent, false);
		}
	}
	,GetValue : function() {
		return this.value; 
	}
	,OnClick : function() {
		this.FireEvent("onclick", true, false);	
	}
	,SetTitle: function(title) {
		if (this.lab)
			this.lab.innerText = title; 
	}
});
//--------------------- GroupBoxPanel ---------------------------
DeclareClass("UI.Controls.GroupBoxPanel", "UI.Control", {
	constructor : function(ctrl, id) {
		this.base();
		this.ctrl = ctrl;
		this.id = id;
		this.radioButtons = [];
		this.radioButtonValue = null;
		this.isInit = false;
		this.SetCssClass("gbp-panel");
	}
	,Dispose: [decl_virtual, function(){
		this.ctrl = null;
		this.radioButtons = null;
		this.base.Dispose();
	}]
	,GetTagName : function() { 
		return UI.HtmlTag.Div; 
	}
	,Init :[decl_virtual, function() {
		for (var i = 0, ic = this.ctrl.length; i < ic; ++i) {
			var c = this.ctrl[i].control;
			if (c.IsInstanceOf(UI.Controls.RadioButton)) {
				c.name = this.id + "_rb";
				c.id = c.name + i;
				c.panel = this;
				this.radioButtons[this.radioButtons.length] = c;
				this.Listeners.AddObjectListener(c, "onclick", this.OnRadioButtonClick);
			}
		}
		for (var i = 0, ic = this.ctrl.length; i < ic; ++i)
			this.AddControl(this.ctrl[i].control);
	}]
	,Render : [decl_virtual, function() {
		var ar = [], arTd = [];
		for (var i = 0, ic = this.ctrl.length; i < ic; ++i) {
			var td = new UI.DOMControls.Td();
			if (this.ctrl[i].css)
				td.SetCssClass("gbp-row " + this.ctrl[i].css);
			else
				td.SetCssClass("gbp-row");
			arTd[i] = td;
			ar[i] = new UI.DOMControls.Tr(td);
		}
		this.HostElement.appendChild(new UI.DOMControls.Table(ar).Obj());
		for (var i = 0, ic = this.ctrl.length; i < ic; ++i) 
			this.ctrl[i].control.RenderControl(arTd[i].Obj());
	}]
	,OnRadioButtonClick : function(fireEvent, isInit) {
		if (isInit == true && this.isInit == true) return;
		for (var i = 0, ic = this.radioButtons.length; i < ic; ++i) {
			if (this.radioButtons[i].IsChecked() == true) 
			{
				if (this.radioButtonValue != this.radioButtons[i].GetValue()) 
				{
					this.radioButtonValue = this.radioButtons[i].GetValue();
					this.FireEvent("onrbvalchange", fireEvent);
				}
				break;
			}
		}			
	}
	,GetRadioButtonValue : function() {
		return this.radioButtonValue;
	}
	,SelectRadioButtonByValue: function(value, fireEvent) {
		if (this.radioButtonValue != value) {
			this.isInit = true;
			this.radioButtonValue = value;
			fireEvent = (typeof(fireEvent)!="undefined")?fireEvent:true;
			this.FireEvent("onrbvalchange", fireEvent);
		}
		for (var i = 0, ic = this.radioButtons.length; i < ic; ++i) {
			if (this.radioButtons[i].GetValue() == value) {
				this.radioButtons[i].SetChecked(true, false);
				return;
			}
		}
	}
	,SetRadioButtonTitles: function(arTitles) {
		if (this.radioButtons) {
			for (var i = 0, ic = arTitles.length; i < ic; ++i) {
				var rb = this.radioButtons[i];
				if (rb) rb.SetTitle(arTitles[i]);		
			}
		}			
	}
});
//--------------------- GroupBox ---------------------------
DeclareClass("UI.Controls.GroupBox", "UI.Control", {
	constructor : function(id, title, width, height, ctr) {
		this.base();
		this.title = title; 
		
		this.SetWidth((typeof(width)!="undefined" && width != null)?width:"auto");
		this.SetHeight((typeof(height)!="undefined" && height != null)?height:"auto");
		this.SetCssClass("hw100p");
		this.ctr = ctr;
		this.table = null;
		
		this.id = id;
		
		this.groupBoxPanel = null;
		this.header = null;
		
		this.isRadioButtonInitializing = true;
		
		this.curr_value = null;
		this.curr_fireEvent = true;
		this.curr_lock = false;
	}
	,Dispose: [decl_virtual, function() {
		this.groupBoxPanel = null;
		this.header = null;
		this.base.Dispose();
	}]
	,SetGroupBoxLock: function() {
		if (this.curr_lock)
			this.Lock();
		else
			this.Unlock();
	}
	,SetLock: function(value) {
		this.curr_lock = value;
		this.SetGroupBoxLock();
	}
	,GetTagName : function() { 
		return UI.HtmlTag.Div; 
	}
	,Init :[decl_virtual, function() {
		this.base.Init();
		
		this.groupBoxPanel = new UI.Controls.GroupBoxPanel(this.ctr, this.id);
		this.Listeners.AddObjectListener(this.groupBoxPanel, "onrbvalchange", this.OnRadioButtonChange);
		this.SetRadioButtonValue();
		this.AddControl(this.groupBoxPanel);
	}]
	,Render : [decl_virtual, function(writer) {
		var tdPanel = new UI.DOMControls.Td();
		var contentRow = new UI.DOMControls.Tr(tdPanel);
		contentRow.SetCssClass("h100p");
		
		this.table = new UI.DOMControls.Table(
			new UI.DOMControls.Tr(new UI.DOMControls.Td(new UI.DOMControls.Text(this.title))), 
			contentRow
		);
		
		this.table.SetCssClass("h100p");
		this.table.SetCellSpacing(2);
		
		this.HostElement.appendChild(this.table.Obj());
		
		this.groupBoxPanel.RenderControl(tdPanel.Obj());
		
		this.SetGroupBoxLock();
	}]
	,OnRadioButtonChange : function(fireEvent) {
		fireEvent=(typeof(fireEvent)!="undefined")?fireEvent:true;
		if (fireEvent)
			this.FireEvent("onrbvaluechange", this.GetRadioButtonValue(), this.isRadioButtonInitializing);
		this.isRadioButtonInitializing = false;
	}
	,GetRadioButtonValue : function() {
		return this.groupBoxPanel.GetRadioButtonValue();
	}
	,SetRadioButtonValue: function() {
		if (this.groupBoxPanel)
			this.groupBoxPanel.SelectRadioButtonByValue(this.curr_value, this.curr_fireEvent);
	}
	,SelectRadioButtonByValue: function(value, fireEvent) {
		this.curr_value = value;
		this.curr_fireEvent = fireEvent;
		this.SetRadioButtonValue();
	}
	,fireEvent: function(isInitializing) {
		isInitializing=(typeof(isInitializing)!="undefined")?isInitializing:this.isRadioButtonInitializing;
		this.FireEvent("onrbvaluechange", this.GetRadioButtonValue(), isInitializing);
	}
	,SetRadioButtonTitles: function(arTitles) {
		if (this.groupBoxPanel)
			this.groupBoxPanel.SetRadioButtonTitles(arTitles);
	}
});
//--------------------- TPCalendar ---------------------------
DeclareClass("UI.Controls.TPCalendar", "UI.Control", {
	constructor: function() {
		this.base();
		this.monthTitle = null;
		this.selDate = new Date();
		this.curYear = this.GetSelYear();
		this.curMonth = this.GetSelMonth();
		this.today = new Date();
		this.todayY = this.today.getFullYear();
		this.todayM = this.today.getMonth();
		this.todayD = this.today.getDate();
		this.todayText = null;
		this.__rows = [];
		this.__texts = [];
		this.__cells = [];
		this.__CurrCell = null;
	}
	,Dispose: [decl_virtual, function() {
		this.rows = null;
		this.selDate = null;
		this.texts = null;
		this.cells = null;
		this.today = null;
		this.CurrCell = null;
		this.monthTitle = null;
		this.todayText = null;
		this.base.Dispose();
	}]
	,OnClickTable: function(e) {
		e.cancelBubble = true;
		e.returnEvent = false;
		return false;
	}
	,GetTagName: function() { 
		return UI.HtmlTag.Table; 
	}
	,GoMonth: function(inc) {
		var len = date_monthNames.length;
		var curDate = this.GetSelDate();
		
		if (this.curMonth + inc > len - 1) {
			this.curMonth = 0; 
			++this.curYear;
		}
		else if (this.curMonth + inc < 0) {
			this.curMonth = 11; 
			--this.curYear;
		}
		else 
			this.curMonth = this.curMonth + inc;
		
		var d = new Date(this.curYear, this.curMonth, 1), dayInMonth = d.getDaysInMonth();
		curDate = (dayInMonth < curDate) ? dayInMonth : curDate;
		this.selDate = new Date(this.curYear, this.curMonth, curDate);
		this.FireEvent("onmonthchange", d);			
		this.__FillCalendar();
	}
	,OnPrevMonth: function(e, sender) {
		this.GoMonth(-1);
		return this.OnClickTable(e);
	}
	,OnNextMonth: function(e, sender) {
		this.GoMonth(1);
		return this.OnClickTable(e);
	}
	,__SelectDate: function(date, i, j) {
		this.selDate = date;
		this.__FillCell(i, j, date.getFullYear(), date.getMonth(), date.getDate(), 
			this.GetSelYear(), this.GetSelMonth(), this.GetSelDate());
		this.FireEvent("onselectdate", this, date);
	}
	,__OnDayClick: function(e) {
		var sender = e.srcElement;
		this.__SelectDate(sender.Date, sender.i, sender.j);
		return this.OnClickTable(e);
	}
	,OnToDayClick: function(e, sender) {
		this.SetDate(this.today);
		this.FireEvent("onselectdate", this, this.today);
		return this.OnClickTable(e);
	}
	,Init: [decl_virtual, function() {
		this.SetCssClass("cal-t");

		var img = new UI.DOMControls.Image("arrow-left-small-green.gif", "cal-mlci");
		var tdMonthLeft = new UI.DOMControls.Td(img);
		tdMonthLeft.SetCssClass("cal-mlc");
		tdMonthLeft.AttachEvent("click", this.CreateCallback(this.OnPrevMonth));
		
		this.monthTitle = new UI.DOMControls.Text("");
		this.monthTitle.AttachEvent("click", this.CreateCallback(this.OnMonthTitleClick));
		var tdMonthMiddle = new UI.DOMControls.Td(this.monthTitle);
		tdMonthMiddle.SetCssClass("cal-mmc");
		
		img = new UI.DOMControls.Image("arrow-right-small-green.gif", "cal-mrci");
		var tdMonthRight = new UI.DOMControls.Td(img);
		tdMonthRight.SetCssClass("cal-mrc");
		tdMonthRight.AttachEvent("click", this.CreateCallback(this.OnNextMonth));
		
		var trMonth = new UI.DOMControls.Tr(tdMonthLeft, tdMonthMiddle, tdMonthRight);
		trMonth.SetCssClass("cal-mr");
		
		var tblMonth = new UI.DOMControls.Table(trMonth);
		tblMonth.SetCssClass("cal-mt");
		
		var cell = new UI.DOMControls.Td(tblMonth);
		cell.SetColSpan("7");
		var row = new UI.DOMControls.Tr(cell);
		this.__rows[this.__rows.length] = row;
		
		var cells = [];
		
		var tdText = new UI.DOMControls.Text(date_dayNames[0].substr(0,1));
		cells[0] = new UI.DOMControls.Td(tdText);
		cells[0].SetCssClass("cal-drh");
		
		for (var i = 1; i < 6; ++i) {
			tdText = new UI.DOMControls.Text(date_dayNames[i].substr(0,1));
			cells[i] = new UI.DOMControls.Td(tdText);
			cells[i].SetCssClass("cal-dr");
		}
		
		tdText = new UI.DOMControls.Text(date_dayNames[6].substr(0,1));
		cells[6] = new UI.DOMControls.Td(tdText);
		cells[6].SetCssClass("cal-drh");
		
		row = new UI.DOMControls.Tr(cells);
		this.__rows[this.__rows.length] = row;
		
		for (var i = 0; i < 6; ++i) {
			var cells = [];
			this.__texts[i] = [];
			this.__cells[i] = [];
			for (var j = 0; j < 7; ++j) {
				var text = new UI.DOMControls.Text("");
				this.__texts[i][j] = text;
				var cell = new UI.DOMControls.Td(text);
				cell.SetCssClass("cal-r");
				cell.AttachEvent("click", this.CreateCallback(this.__OnDayClick));
				this.__cells[i][j] = cell;
				cells[j] = cell;
			}
				
			row = new UI.DOMControls.Tr(cells);
			this.__rows[this.__rows.length] = row;
		}
		
		this.todayText = new UI.DOMControls.Text("Today: " + this.today.ToString("ddd, " + Utils.GeneralPreferences.GetDateFormat()));
		cell = new UI.DOMControls.Td(this.todayText);
		cell.AttachEvent("click", this.CreateCallback(this.OnToDayClick));
		cell.SetCssClass("cal-ttc");
		cell.SetColSpan("7");
		row = new UI.DOMControls.Tr(cell);
		this.__rows[this.__rows.length] = row;
				
		this.__FillCalendar();
	}]
	,Update: [decl_virtual, function() {
		if (this.todayText)
			this.todayText.SetText("Today: " + this.today.ToString("ddd, " + Utils.GeneralPreferences.GetDateFormat()));
		return this.base.Update();
	}]
	,GetSelMonth: function() {
		return this.selDate.getMonth();
	}
	,GetSelYear: function() {
		return this.selDate.getFullYear();
	}
	,GetSelDate: function() {
		return this.selDate.getDate();
	}
	,GetSelDay: function() {
		return this.selDate.getDay();
	}
	,GetSelected: function() {
		return this.selDate;
	}
	,OnMonthTitleClick: function(e, sender, text) {
		var firstDate = new Date(this.curYear, this.curMonth, 1), 
			fdDate = firstDate.getDate(), 
			fdMonth = firstDate.getMonth(), 
			fdYear = firstDate.getFullYear(); 
		
		for (var i = 0; i < 6; ++i) {
			for (var j = 0; j < 7; ++j) {
				var dt = this.__texts[i][j].Obj().Date;
				if (dt.getDate() == fdDate && dt.getMonth() == fdMonth && dt.getFullYear() == fdYear) {
					this.__SelectDate(dt, i, j);
					return this.OnClickTable(e);
				}
			}
		}
		return this.OnClickTable(e);
	}
	,IncDay: function(year, month, date) {
		var d = new Date(year, month, date, 12);
		return floorDate(new Date(d.getTime() + 86400000));//86400000=24*3600000
	}
	,DecDay: function(year, month, date) {
		var d = new Date(year, month, date, 12);
		return floorDate(new Date(d.getTime() - 86400000));
	}
	,__FillCell: function(i, j, forYear, forMonth, forDate, selYear, selMonth, selDate) {
		var cell = this.__cells[i][j], text = this.__texts[i][j];
		
		if (forDate != selDate || forMonth != selMonth) {
			if (this.curMonth == forMonth)
				text.SetCssClass((j != 0 && j != 6) ? "cal-udt" : "cal-udth");
			else 
				text.SetCssClass((j != 0 && j != 6)? "cal-uamdt" : "cal-uamdth");
		} 
		else 
		{
			if (this.__CurrCell) {
				var currCellMonth = this.__CurrCell.Obj().Date.getMonth();
				var currCellJ = this.__CurrCell.Obj().j;
				if (this.curMonth != currCellMonth)
					this.__CurrCell.SetCssClass((j != 0 && j != 6) ? "cal-uamdt" : "cal-uamdth");
				else
					this.__CurrCell.SetCssClass((currCellJ != 0 && currCellJ != 6) ? "cal-udt" : "cal-udth");
				
			}
			text.SetCssClass((j != 0 && j != 6)?"cal-stt":"cal-stth");
			this.__CurrCell = text;
		}
		
		if (forDate == this.todayD && forMonth == this.todayM && forYear == this.todayY) 
			cell.SetCssClass("cal-stc");
		else
			cell.SetCssClass("cal-r");
	}
	,__FillCalendar : function() {
		if (!this.__texts[0]) return;
		
		var selM = this.GetSelMonth(), selY = this.GetSelYear(), title = date_monthNames[selM] + " " + selY, 
			firstDate = new Date(selY, selM, 1), day = firstDate.getDay(), startrow = startcell = 0,
			sY = this.GetSelYear(), sM = this.GetSelMonth(), sD = this.GetSelDate();
			
		this.monthTitle.SetText(title);
		
		if (day == 0) {
			startrow = 1;
			startcell = 7;
		}
		else 
			startcell = day;
			
		var date = floorDate(firstDate);
		if (startrow == 0) {
			for (var j = startcell; j < 7; j++)
			{
				var fY = date.getFullYear(), fM = date.getMonth(), fD = date.getDate();
				
				var txt = this.__texts[startrow][j].Obj(), 
					obj = this.__cells[startrow][j].Obj();
				
				this.__texts[startrow][j].SetText(fD);
				txt.Date = obj.Date = date;
				txt.i = obj.i = startrow;
				txt.j = obj.j = j;
				
				this.__FillCell(startrow, j, fY, fM, fD, sY, sM, sD);
				date = this.IncDay(fY, fM, fD);
			}
			startrow++;
		}
		
		for (var i = startrow; i < 6; ++i) {
			for (var j = 0; j < 7; ++j) {
				var fY = date.getFullYear(), fM = date.getMonth(), fD = date.getDate();
				
				var txt = this.__texts[i][j].Obj(), 
					obj = this.__cells[i][j].Obj();
				this.__texts[i][j].SetText(fD);
				txt.Date = obj.Date = date;
				txt.i = obj.i = i;
				txt.j = obj.j = j;
				
				this.__FillCell(i, j, fY, fM, fD, sY, sM, sD);
				date = this.IncDay(fY, fM, fD);
			}
		}

		date = floorDate(firstDate);
		for (var j = startcell-1; j >= 0; --j) {
			var fY = date.getFullYear(), fM = date.getMonth(), fD = date.getDate();
			date = this.DecDay(fY, fM, fD);
			fY = date.getFullYear(), fM = date.getMonth(), fD = date.getDate();
			
			var txt = this.__texts[0][j].Obj(), 
				obj = this.__cells[0][j].Obj();
			this.__texts[0][j].SetText(fD);
			txt.Date = obj.Date = date;
			txt.i = obj.i = 0;
			txt.j = obj.j = j;

			this.__FillCell(0, j, fY, fM, fD, sY, sM, sD);
		}
	}
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.HostElement.border = this.HostElement.cellSpacing = 0;
		var tbody = DOMObjectFactory.CreateElement(UI.HtmlTag.TBody);
		for (var i = 0; i < this.__rows.length; ++i)
			tbody.appendChild(this.__rows[i].Obj());
		this.HostElement.appendChild(tbody);
		this.Listeners.AddDOMListener(this.HostElement, "click", this.OnClickTable);		
	}]
	,SetDate: function(date) {
		this.selDate = date;
		if (this.curMonth != this.GetSelMonth() || this.curYear != this.GetSelYear()) {
			this.curYear = this.GetSelYear();
			this.curMonth = this.GetSelMonth();
			this.__FillCalendar();
			return;
		}
		var fdDate = this.GetSelDate(), fdMonth = this.GetSelMonth(), fdYear = this.GetSelYear();
		for (var i = 0; i < 6; ++i) {
			if (!this.__texts[i]) return;
			for (var j = 0; j < 7; ++j) {
				var dt = this.__texts[i][j].Obj().Date;
				if (dt.getDate() == fdDate && dt.getMonth() == fdMonth && dt.getFullYear() == fdYear) {
					this.__FillCell(i, j, fdYear, fdMonth, fdDate, fdYear, fdMonth, fdDate);
					return;
				}
			}
		}
	}
});
//--------------------- TPDateSelector ---------------------------
DeclareClass("UI.Controls.TPDateSelector", "UI.Control", {
	constructor: function(width, cssDiv, cssInput, cssImage) {
		this.base();
		this.width = width;
		this.cssInput = (typeof(cssInput) != "undefined" && cssInput != null)? cssInput : "ds-i";
		this.cssImage = (typeof(cssImage) != "undefined" && cssImage != null)? cssImage : "ds-img";
		this.cssDiv = (typeof(cssDiv) != "undefined" && cssDiv != null)? cssDiv: "ds-div";
		this.input = null;
		this.calendar = null;
		this.poparea = null;
		this.curr_Date = new Date();
		this.curr_FireEvent = true;
	}
	,Dispose: [decl_virtual, function() {
		this.poparea = null;
		this.calendar = null;
		this.base.Dispose();
	}]
	,GetTagName : function() {
		return UI.HtmlTag.Div; 
	}
	,Init: [decl_virtual, function() {
		this.base.Init();
		
		this.SetWidth(this.width);
		this.SetCssClass(this.cssDiv);
		
		this.input = new UI.DOMControls.InputControl("");
		this.input.SetCssClass(this.cssInput);
		this.input.AttachEvent("blur", this.CreateCallback(this.OnBlurInput));
		this.input.AttachEvent("focus", this.CreateCallback(this.OnFocusInput));
		
		this.calendar = new UI.Controls.TPCalendar();
		this.calendar.SetVisibleState(false);
		this.Listeners.AddObjectListener(this.calendar, "onselectdate", this.OnSelectDate);
		this.SetCalendarDate();
		
		this.poparea = new UI.Controls.PopupArea();
		this.poparea.MaxWidth = this.width;
		this.poparea.MinWidth = this.width;
		this.poparea.AddContentControl(this.calendar);
		
		this.AddControl(this.poparea);
		
		this.SetCalendarDate();
	}]
	,Render : [decl_virtual, function() {
		var img = new UI.DOMControls.Image("calendar-icon.gif", this.cssImage);
		img.AttachEvent("click", this.CreateCallback(this.OnClick));
		
		var td_input = new UI.DOMControls.Td(this.input);
		td_input.SetCssClass("ds-itd");
		
		var td_calendar = new UI.DOMControls.Td();
		td_calendar.SetColSpan("2");
		
		this.HostElement.appendChild(
			new UI.DOMControls.Table(
				new UI.DOMControls.Tr(td_input, new UI.DOMControls.Td(img)),
				new UI.DOMControls.Tr(td_calendar)
			).Obj()
		);
		
		this.poparea.RenderControl(td_calendar.Obj());
	}]
	,OnFocusInput: function() { this.input.SetValue(this.curr_Date.ToString(Utils.GeneralPreferences.GetDateFormat())); }
	,OnBlurInput: function() {
		var dt = new Date().Parse(this.input.GetValue(), Utils.GeneralPreferences.GetDateFormat());
		if (dt == 'NaN') dt = this.curr_Date;
		if (dt.getFullYear() > 9999) dt.setFullYear(9999);
		if (dt.getFullYear() < 1800) dt.setFullYear(1800);
		var fe = (this.curr_Date != dt)?true:false;
		this.curr_Date = dt;
		this.input.SetValue(this.curr_Date.ToString("ddd, " + Utils.GeneralPreferences.GetDateFormat()));
		if (this.calendar) this.calendar.SetDate(this.curr_Date);
		if (fe) this.FireEvent("onchangedate", this, this.curr_Date);
	}
	,OnClick: function(e, sender) {
		if (this.calendar) {
			this.calendar.SetVisibleState(true);
			this.calendar.SetDate(this.curr_Date);	
		}
		this.poparea.ShowPopup(new UI.PopupareaOptions(this.input.Obj()/*.HostElement*/));
	}
	,GetValue: function() { return this.curr_Date.ToString("ddd, " + Utils.GeneralPreferences.GetDateFormat()); }
	,OnSelectDate: function(sender, date) {
		this.poparea.HidePopup();
		this.SetDate(date, true);
	}
	,GetDate: function() { return this.curr_Date; }
	,SetCalendarDate: function() {
		if (this.input) this.input.SetValue(this.curr_Date.ToString("ddd, " + Utils.GeneralPreferences.GetDateFormat()));
		if (this.calendar) this.calendar.SetDate(this.curr_Date);	
	}
	,SetDate: function(date, fireEvent) {
		if (date.getFullYear() > 9999) date.setFullYear(9999);
		if (date.getFullYear() < 1800) date.setFullYear(1800);
		var fe = (this.curr_Date != date) ? true : false;
		this.curr_Date = date;
		this.curr_FireEvent = fireEvent;
		this.SetCalendarDate();
		if (fe && fireEvent)
			this.FireEvent("onchangedate", this, this.curr_Date);
	}
});

//--------------------------------------------- TablePanel controls ---------------------------------------------------------//

DeclareClass("UI.Controls.TablePanelCell", "UI.Control", 
{
	GetTagName : function() 
	{
		return UI.HtmlTag.Td;
	}
	,GetRow : function()
	{
		if (this.ParentControl.IsInstanceOf(UI.Controls.TablePanelRow))
			return this.ParentControl;
		return null;
	}
	,SetRowSpan : function(val)
	{
		this.SetAttribute("rowSpan", val);
	}
	,SetColSpan : function(val)
	{
		this.SetAttribute("colSpan", val);
	}
	,GetRowSpan : function(val)
	{
		return this.GetAttribute("rowSpan");
	}
	,GetColSpan : function()
	{
		return this.GetAttribute("colSpan");
	}
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		if (data != null)		
		{	
			this.base.ProcessCreateData(data);
			
			var width = data.getAttribute("Width");
			if (width)
				this.SetWidth(width);
	
			var rowSpan = data.getAttribute("RowSpan");
			if (rowSpan)
				this.SetRowSpan(rowSpan);
			
			var colSpan = data.getAttribute("ColSpan");
			if (colSpan)
				this.SetColSpan(colSpan);
		
		}
	}]
});

DeclareClass("UI.Controls.TablePanelRow", "UI.Control", 
{
	GetTagName : function() 
	{
		return UI.HtmlTag.Tr;
	}
	,GetCells : function()
	{
		return this.__controls;
	}
	,GetTable : function()
	{
		if (this.ParentControl.IsInstanceOf(UI.Controls.TablePanelBody))
			return this.ParentControl;
		return null;
	}
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		if (data != null)		
		{	
			this.base.ProcessCreateData(data);
			var cells = data.selectNodes("Cell");
			if (cells != null)
			{
				for (var i=0; i < cells.length; i++)
				{
					cellData = cells[i];
					cellData.setAttribute("ControlName", "UI.Controls.TablePanelCell");
					var cell = UI.Control.LoadControlTemplate(cellData);
					cell.CellIndex = i;
					this.AddControl(cell);
				}
			}
		}
	}]
});

DeclareClass("UI.Controls.TablePanelBody", "UI.Control", 
{
	GetTagName : function() 
	{
		return "TBody";
	}
	,GetRows : function()
	{
		return this.__controls;
	}
});
	
DeclareClass("UI.Controls.TablePanel", "UI.Control", 
{
	GetTagName : function() 
	{
		return UI.HtmlTag.Table;
	}
	,SetCellPadding : function(val)
	{
		this.SetAttribute("cellPadding", val);
	}
	,SetCellSpacing : function(val)
	{
		this.SetAttribute("cellSpacing", val);
	}
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		if (data != null)		
		{	
			this.base.ProcessCreateData(data);
			         
			var cellPadding = data.getAttribute("CellPadding");
			cellPadding = cellPadding != null ? cellPadding : "0";
			this.SetCellPadding(cellPadding);
			
			var cellSpacing = data.getAttribute("CellSpacing");
			cellSpacing = cellSpacing != null ? cellSpacing : "0";
			this.SetCellSpacing(cellSpacing);
			
			var width = data.getAttribute("Width");
			width = width != null ? width : "100%";
			this.SetWidth(width);
			
			var height = data.getAttribute("Height");
			height = height != null ? height : "100%";
			this.SetHeight(height);
			
			var rows = data.selectNodes("Row");
			if (rows != null)
			{
				var tbody = new UI.Controls.TablePanelBody();
				this.AddControl(tbody);
				for (var i=0; i < rows.length; i++)
				{
					rowData = rows[i];
					rowData.setAttribute("ControlName", "UI.Controls.TablePanelRow");
					var row = UI.Control.LoadControlTemplate(rowData);
					row.RowIndex = i;
					tbody.AddControl(row);
				}
			}
		}
	}]
});

//--------------------------------------------- UI.Controls.TrendsGraphic ---------------------------------------------------------//

//abstract
DeclareClass("UI.Controls.TrendsGraphic", "UI.Controls.Panel", {
	constructor : function() { 
		this.base();
        this.SetMetrics(240, 85);
        this.imageLoaded = false;
		this.visible = false;
		this.advancedSearch = false;
	}
	/*
	,Update :[decl_virtual, function(writer)
	{
		var ac = srch_advGetCurrentAdvancedSearch();


        if (ac)
		{
			this.ContentControl.SetVisibleState(false);
			this.OnSearchXmlLoad(ac.GetXml());
		}
		return this.base.Update(writer)
	}]    */

	,SetMetrics : function(chartWidth, chartHeight)
	{
		this.chartWidth = chartWidth;
		this.chartHeight = chartHeight;
		
		if (this.img)
		{
			this.img.width = chartWidth;
			this.img.height = chartHeight;
		}
	}

	,Render :[decl_virtual, function(writer) {
		var host = this.ContentControl.GetHostObject();
		host.style.backgroundColor = "#ffffff";
		host.style.padding = "15px 7px 7px 0px";
		host.style.paddingTop = "15px";
		host.setAttribute("align", "center");

		this.img = DOMObjectFactory.CreateElement("img");
		this.img.style.borderStyle = "none";
		this.img.style.verticalAlign = "middle";
		this.img.onload = this.CreateCallback(this.OnChartImageLoaded);

		host.appendChild(this.img);
	}]
	
	,Init : [decl_virtual, function(writer){
		this.ContentControl = new UI.Controls.Panel();
		this.ContentControl.SetVisibleState(false);
		this.AddControl(this.ContentControl);
		this.base.Init();
	}]

	,Refresh : function()
	{
		this.imageLoaded = false;
		new httpcmd_GetTrendsGraphic(this.searchXml, this.searchId, this.chartWidth, this.chartHeight, this.CreateCallback(this.OnTrendsGraphicLoaded));
	}

	//----------------
	// Events
	//----------------

	,OnSearchXmlLoad : function(searchXml)
	{
		this.searchXml = searchXml;
		this.Refresh();
	}

	,OnTrendsGraphicLoaded : function(imageUrl)
	{
		this.img.src = unescape(imageUrl);
	}

	,OnChartImageLoaded : function()
	{
		this.imageLoaded = true;
		this.TryToShow();
	}

	//--------------
	// Helpers
	//--------------

	,TryToShow : function()
	{
		if (this.visible && this.imageLoaded)
		{
			this.ContentControl.SetVisibleState(true);
		}
	}

	,Show : function()
	{
		this.visible = true;
		this.TryToShow();
	}

	,Hide : function()
	{
		this.visible = false;
		this.ContentControl.SetVisibleState(false);
	}

});

DeclareClass("UI.Controls.HomePageTrendsGraphic", "UI.Controls.TrendsGraphic", {

	SetLayout : function(homePageColumnsCount, isWideScreen) {
		var normalWidth = 240;
		var normalHeight = 85;

		if (isWideScreen) {
			normalWidth = 270;
			normalHeight = 85;
		}

		var chartWidth = (normalWidth * 3) / homePageColumnsCount;
		var chartHeight = normalHeight + (18 / homePageColumnsCount);
		this.SetMetrics(chartWidth, chartHeight);
	}

	//----------------------
	// SearchXml preparation
	//----------------------

	,InitBySearchId : function(searchId) {
		var show = (GeneralPreferences.EnableTrendsOnOtherPages == 'true');

		if (show)
			new httpcmd_GetSearchXml(searchId, this.CreateCallback(this.OnSearchXmlLoad));
	}

	,InitBySearchInfo : function(searchInfo) {

//		alert(GeneralPreferences.EnableTrendsOnOtherPages);

		var show = (GeneralPreferences.EnableTrendsOnOtherPages == 'true');

		if (show)
			new httpcmd_PrepareSearchXmlForHomeSection(searchInfo, this.CreateCallback(this.OnSearchXmlLoad));
	}


});

DeclareClass("UI.Controls.SearchResultsTrendsGraphic", "UI.Controls.TrendsGraphic", {

	ProcessCreateData :[decl_virtual, function(data) {
        this.base.ProcessCreateData(data);

        var width = data.getAttribute("ChartWidth");
        var height = data.getAttribute("ChartHeight");
        this.SetMetrics(width, height);

		this.Show();

		srch_advAttachEvent("ondosearch", this.CreateCallback(this.InitByAdvancedSearch));
		this.advancedSearch = true;
	}]

	,InitByAdvancedSearch : function()
	{
		var ac = srch_advGetCurrentAdvancedSearch();

		if (ac)
		{
			this.ContentControl.SetVisibleState(false);
			this.OnSearchXmlLoad(ac.GetXml());
		}
	}

	,Render :[decl_virtual, function(writer) {
		this.base.Render(writer);

		if (this.advancedSearch == true)
		{
			this.InitByAdvancedSearch();
			this.advancedSearch = false;
		}
	}]
	

});

DeclareClass("UI.Controls.DynamicServerControl", "UI.Controls.ServerControlContainer", {
	constructor : function(controlType) {
		this.base(controlType);
		this.Dynamic = null;
		this.clear_parameters_before_loading = true;
		this.__dynamicParameters = new dm_QueryString();
	}

    ,GetDynamicParameters : function() {
        return this.__dynamicParameters;
    }

	,AttachDynamicElement: [decl_virtual, function(dynamicElement) {
		this.Dynamic = dynamicElement;
//		this.Dynamic.OnLoading = this.CreateCallback(this.OnDynamicLoading);
//		this.Dynamic.OnComplete = this.CreateCallback(this.OnDynamicComplete);
		this.Dynamic.CustomRequestHandler = this.CreateCallback(this.DynamicRequestHandler);
	}]

	,DynamicRequestHandler: [decl_virtual, function(id, data) {
		switch (data.status)
		{
			case DE_STATUS_LOADING:
				this.OnDynamicLoading(id, data);

				// Little hack: clear parameters if flag is set (default) or "clear" only parameter of command
				if(this.clear_parameters_before_loading)
					this.Dynamic.ClearParameters();
				else
				{
					if(this.workspaceModules&&this.workspaceModules.collection&&this.workspaceModules.collection.Count>0)
					{
						var cmd = this.workspaceModules.collection.GetByIndex(0).currentCommand;
						if(cmd)
						{
							this.AddDynamicParameter(cmd.name, cmd.params);
							if(cmd.params=="")
								this.Dynamic.AddParameter(cmd.name, "");
						}
					}
				}
				
				this.Dynamic.CombineQueries(this.__dynamicParameters);
				break;
			case DE_STATUS_COMPLETE:
				this.OnDynamicComplete(id, data);
				this.ClearDynamicParameters();
				break;
			case DE_STATUS_ERROR:
				this.OnDynamicError(id, data);
				this.ClearDynamicParameters();
				break;
		}

		this.Dynamic.SetElementHTMLEx(data.statusText);
	}]

	,OnDynamicLoading : [decl_virtual, function(id, data) {}]
	,OnDynamicComplete : [decl_virtual, function(id, data) {}]
	,OnDynamicError : [decl_virtual, function(id, data) {}]

	,ClearDynamicParameters : function() {
		this.__dynamicParameters.ClearInternal();
	}
	,AddDynamicParameter : function(name, val) {
		this.__dynamicParameters.Delete(name);
		this.__dynamicParameters.Add(name, val);
	}
	,RemoveDynamicParameter : function(name) {
		this.__dynamicParameters.Delete(name);
	}
});


//base chart control
DeclareClass("UI.Trends.TrendsChart", "UI.Controls.DynamicServerControl", {
	constructor : function() {
		this.base("InfoNgen.TouchPoint.Modules.Trends.Chart.ChartPanel");
		this.chartWidth = 300;
		this.chartHeight = 100;						
	}	
	,setChartWidth : function(chartWidth) {
		this.chartWidth = chartWidth;
	}
	,setChartHeight : function(chartHeight) {
		this.chartHeight = chartHeight;
	}
	,addChartDimensions : function() {
		this.AddDynamicParameter("chartWidth", this.chartWidth);
		this.AddDynamicParameter("chartHeight", this.chartHeight);		
	}
});

DeclareClass("UI.Trends.SearchResultTrendsChart", "UI.Trends.TrendsChart", {
    constructor : function() {
        GlobalTrendsEventManager.AttachEvent("onneedrefresh", this.CreateCallback(this.OnNeedRefresh));
        this.base();
				this.clear_parameters_before_loading = false;
			this.chartWidth = 130;
			this.chartHeight = 80;				
    }

    ,OnNeedRefresh : function(full_refresh) {
    	if(full_refresh)
    		this.Dynamic.ClearParameters();
			this.Dynamic.Refresh(this.Dynamic.DataLoadText);
    }

	,OnDynamicLoading : [decl_virtual, function(id, data) {
        GlobalTrendsParameters.CombineTo(this.GetDynamicParameters());
		this.AddDynamicParameter("chartPlace", "searchResult");
		this.addChartDimensions();
	}]
});

DeclareClass("UI.Trends.HomePageTrendsChart", "UI.Trends.TrendsChart", {
  constructor : function() {
      this.base();      
			this.clear_parameters_before_loading = false;
  }
	,OnDynamicLoading : [decl_virtual, function(id, data) {
		this.AddDynamicParameter("chartPlace", "homePage");
		this.addChartDimensions();
	}]
});

//base chart panel
DeclareClass("UI.Trends.TrendsChartPanel", "UI.Controls.WorkspacePanel", {
	constructor : function() {
		this.base();
//		this.DataLoadText = "Loading trends chart...";
		this.ChartControl = null;
		GlobalTrendsEventManager.AttachEvent("onneedrefresh", this.CreateCallback(this.OnNeedChangeTitle));		
		this.SearchTagsForRefresh = "";
		this.SearchID = "";
	}
	,Init :[decl_virtual, function(){
		this.base.Init();	
		this.AddSearchTags();
		this.AddContentControl(this.ChartControl);
		if(this.GetTitle()=="")
			GlobalTrendsParameters.SetInitialValues();
		this.OnNeedChangeTitle();		
	}]
	,OnNeedChangeTitle :[decl_virtual, function(){
		if(!GlobalTrendsParameters.TrendDate.GetValue()||GlobalTrendsParameters.TrendDate.GetValue().length==0)
		{
			var cur_period = GlobalTrendsParameters.Period.GetValue();
			for(c1 = 0; c1<TPTrendsDateFilterValues.length; c1++)
				if(TPTrendsDateFilterValues[c1].value==cur_period)
				{
					this.SetTitle("Trend ("+TPTrendsDateFilterValues[c1].name+"):");
					break;
				}		
		}
		else
		{
			var dtTrendsDay = new Date(Date.parse(GlobalTrendsParameters.TrendDate.GetValue()));
			this.SetTitle("Trend ("+dtTrendsDay.getFullYear()+"-"+(dtTrendsDay.getMonth()>=9 ? (dtTrendsDay.getMonth()+1) : "0"+(dtTrendsDay.getMonth()+1))+"-"+(dtTrendsDay.getDate()>=10 ? dtTrendsDay.getDate() : "0"+dtTrendsDay.getDate())+"):");
		}
	}]	
	,Update :[decl_virtual, function(writer){
		this.OnNeedChangeTitle();		
		return this.base.Update(writer);
//		return UI.UpdateStatus.FULL_REFRESH;
	}]
	,AddParameter : function(name, value) {
		this.ChartControl.AddDynamicParameter(name, value);
		if(name==P_SEARCH_TAGS)
			this.SearchTagsForRefresh = value;
		if(name==P_SEARCH_ID)
			this.SearchID = value;			
	}

	,Show : function() {
		this.ChartControl.SetVisibleState(true);
	}
	,Hide : function() {
		this.ChartControl.SetVisibleState(false);
	}
	,Refresh : function() {
		if (this.ChartControl.Dynamic) {
			this.AddSearchTags();
			this.ChartControl.Dynamic.Refresh();
		}
	}
	,SetVisible : function(visible) {
		this.ChartControl.SetVisibleState(visible);
	}
	,SetTitle : function(title) {		
		this.ChangeTitle(title);		
	}	
	,AddSearchTags : function() {
		if(this.SearchTagsForRefresh!="")
			this.ChartControl.AddDynamicParameter(P_SEARCH_TAGS, this.SearchTagsForRefresh);
		if(this.SearchID!="")
			this.ChartControl.AddDynamicParameter(P_SEARCH_ID, this.SearchID);		
	}	
});

DeclareClass("UI.Trends.SearchResultChartPanel", "UI.Trends.TrendsChartPanel", {
   constructor : function() {
		this.base();
		this.ChartControl = new UI.Trends.SearchResultTrendsChart();
   }
	,SetTitle : function(title) {		
		this.ChangeTitle(title);
		this.HeaderText = title;
	}	   
});

DeclareClass("UI.Trends.HomePageChartPanel", "UI.Trends.TrendsChartPanel", {
	constructor : function() {
		this.base();
		this.ChartControl = new UI.Trends.HomePageTrendsChart();
	}
	,Init :[decl_virtual, function(){
		this.base.Init();
		this.Hide();
	}]
});

DeclareClass("UI.Controls.UpdatePart", null, {
	constructor : function(partId, renderFunction){
		this.partId = partId;
		this.renderFunction = renderFunction;
		this.uiControl = null;
	}
});

DeclareClass("UI.Controls.UpdateControl", "UI.Controls.Panel", {
	constructor : function(){
		this.base();
		this.parts = new Array();
		this.updatedParts = new Array();
	}

	,AddUpdatePart : function(renderFunction) {
		var updatePart = new UI.Controls.UpdatePart(this.partId, renderFunction);
		this.parts.push(updatePart);
		return updatePart;
	}

	,SetUpdatedParts : function(/*params parts[]*/){
		this.updatedParts = new Array();
		for(var i = 0; i < arguments.length; i++)
			this.updatedParts.push(arguments[i]);
	}

	,Init : [decl_virtual, function(writer) {
		this.base.Init(writer);

		for (var i = 0; i < this.parts.length; i++) {
			var updatePart = this.parts[i];
			var control = new UI.Controls.Panel();
			updatePart.uiControl = control;
			this.AddControl(control);
		}

	}]

	,Render :[decl_virtual, function(writer) {
		this.base.Render(writer);

		for (var i = 0; i < this.updatedParts.length; i++) {
			var updatePart = this.updatedParts[i];
			updatePart.renderFunction(updatePart.uiControl);
		}
	}]
});

DeclareNamespace("UI");

DeclareClass("UI.NavigationFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data, ctl)
	{
		this.ctl = ctl;
		this.__filter = data.getAttribute("QueryFilter");
		this.__SetApplyStages("PreInit","Update");
	}]
	,Apply : [decl_virtual, function(ctl, stage)
	{
		var visibleState = this.IsVisible();
		ctl.SetVisibleState(visibleState);
		ctl.UpdateRule = visibleState?UI.UpdateStatus.CHILDREN_REFRESH:UI.UpdateStatus.NOUPDATE;
	}]
	,IsVisible: function(){
		if(!this.func)
			this.func = new Function("return " + this.__filter);
		return this.func();
	}
	,NeedProcess: function(){
		return this.ctl.__visible == true || this.IsVisible();
	}
	
});

DeclareClass("UI.ContentEmptyFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{	
		this.__SetApplyStages("PostUpdate", "PreRender");
	}]
	,Apply : [decl_virtual, function(ctl, stage)
	{
		var isVisible = false;
		var controls = ctl.GetContentControls?ctl.GetContentControls():ctl.__controls;
		for(var i=0, item; item = controls[i]; i++)
			if(item.__visible){
				isVisible = true;
				break;
			}
		ctl.SetVisibleState(isVisible);
	}]
});

DeclareClass("UI.ContentCssClassFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{
		this.Groups = [];
		this.__firstCss = data.getAttribute("FirstElementCss");
		this.__lastCss = data.getAttribute("LastElementCss");
		this.__Css = data.getAttribute("ElementCss");
		this.__SetApplyStages("PostUpdate", "PreRender");		
		var item;
		for(var i=0; item = data.childNodes[i]; i++)
			this.Groups[item.getAttribute("GroupID")] = {"firstCss": item.getAttribute("FirstElementCss"),
															"lastCss": item.getAttribute("LastElementCss"),
															"css": item.getAttribute("ElementCss")};
	}]
	,Apply : [decl_virtual, function(ctl, stage)
	{
		var controls = ctl.GetContentControls?ctl.GetContentControls():ctl.__controls;
		
		var lastGroupID;
		var lastItem;		
		var css =[this.__firstCss];
		var subcss =[];

		for(var i=0, j=controls.length; i<j; i++)
			if(controls[i].GetVisibleState())
			{
				if(lastItem)
				{
					if(css.length==0)
						css.push(this.__Css);
						
					if(lastGroupID && this.Groups[lastGroupID])
					{
						if(lastGroupID!=controls[i].CustomProperties.GroupID)
							subcss.push(this.Groups[lastGroupID].lastCss);
						else
							if(subcss.length==0)
								subcss.push(this.Groups[lastGroupID].css);
					}
					lastItem.SetCssClass(css.concat(subcss).join(' '));
					css = []; subcss = [];
				}
				
				lastItem = controls[i];
				if(lastGroupID != lastItem.CustomProperties.GroupID)
				{
					lastGroupID = lastItem.CustomProperties.GroupID;
					if(lastGroupID && this.Groups[lastGroupID])
						subcss.push(this.Groups[lastGroupID].firstCss);
				}
			}
			
		if(lastItem)
		{
			css.push(this.__lastCss);
			if(lastGroupID && this.Groups[lastGroupID])
				subcss.push(this.Groups[lastGroupID].lastCss);
			lastItem.SetCssClass(css.concat(subcss).join(' '));
		}
	}]
});

DeclareClass("UI.SearchAlertFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{	
		this.__SetApplyStages("PreInit" , "Update");
	}]
	,Apply : [decl_virtual, function(ctl, stage)
	{
		var visibleState = true;
		
		if (srch_advGetDecimalSearchID() == 0)
			visibleState = false;
			
		ctl.SetVisibleState(visibleState);
		ctl.UpdateRule = visibleState?UI.UpdateStatus.CHILDREN_REFRESH:UI.UpdateStatus.NOUPDATE;
	}]
});

DeclareClass("UI.SearchInputCssClassFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{
		this.__SetApplyStages("PreInit","Update");
	}]
	,Apply : [decl_virtual, function(ctl, stage)
	{
		var css = "search-form ";
		var ploc = null;
		if (nav_IsNavigationEnabled()) 
			ploc = nav_currentNavInfo.GetPageLocation();
		switch(ploc)
		{
			case PID_PLMANAGEFOLDERS:
			case PID_PLMANAGEFEEDS:
			case PID_PLMANAGEBLOGS:
			case PID_PLMANAGECALENDARS:
				css += "nav_head_bg_dir";
				break;			
			default:
				css += "nav_head_bg";
				break;
		}
		ctl.SetCssClass(css);
	}]
});

DeclareClass("UI.ModulePreferenceFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data) 
	{
		this.__SetApplyStages("PreferenceChange");
		if(data)
		{
			this.Param = data.getAttribute("Param");
			this.Value = data.getAttribute("Value");			
			this.Operation = data.getAttribute("Operation")||"==";
		}
	}]
	,Apply : [decl_virtual, function(ctl, stage, preferences)
	{
		ctl.SetVisibleState( eval("preferences.getValue(this.Param)"+this.Operation+"this.Value") );
	}]
});

DeclareClass("UI.TrendsVisibilityFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{
		this.__SetApplyStages("PreInit","Update", "PreferenceChange");
	}]
	,Apply : [decl_virtual, function(ctl, stage, preferences)
	{
		var show = false;
		switch (nav_currentNavInfo.GetPageID()) {
			case PID_FEEDS:
				show = (GeneralPreferences.EnableTrendsOnOtherPages == true)
					&& nav_currentNavInfo.GetPageLocation() != PID_PLADVANCEDSEARCH
					&& nav_currentNavInfo.GetPageLocation() != PID_PLMANAGEFEEDS;
			break;
			case PID_TRENDS:
				show = nav_currentNavInfo.GetPageLocation() != PID_PLADVANCEDSEARCH;
			break;
		}
		ctl.SetVisibleState(show);
	}]
});

DeclareClass("UI.TrendsVisibilityFilterDependOnInputSearch", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)
	{
		this.__SetApplyStages("PreInit","Update", "PreferenceChange");
	}]
	,Apply : [decl_virtual, function(ctl, stage, preferences)
	{
		var show = false;
		switch (nav_currentNavInfo.GetPageID()) {
			case PID_TRENDS:
				show = nav_currentNavInfo.GetPageLocation() != PID_PLADVANCEDSEARCH && !srch_inpIsEmpty();
			break;
		}
		ctl.SetVisibleState(show);
	}]
});

DeclareClass("UI.MoveFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data, ctl)
	{
		this.Ctl = ctl;
		this.GroupID = data && data.getAttribute("GroupID");
		this.Ctl.CustomProperties.UI_MOVEFILTER_WEIGHT = this.CreateCallback(this.GetWeight);
		this.__SetApplyStages("PreferenceChange");
	}]
	,GetWeight: function()
	{
		if(this.Weight == null)
			this.Weight = this.Ctl.__controlIndex;
		return this.Weight;
	}
	,Apply : [decl_virtual, function(ctl, stage, preferences)
	{
		var isItemCountReceived = preferences.getValue("ItemCountReceived") > 0;
		var expr = isItemCountReceived?-1:1;
		if(this.Weight>=1000 && expr==1 || this.Weight<1000 && expr==-1)
			return;
		
		this.Weight = this.GetWeight() + 1000*expr;
		var index = ctl.__controlIndex + expr;
		for(; weight = ctl.ParentControl.__controls[index] && 
				ctl.ParentControl.__controls[index].CustomProperties.UI_MOVEFILTER_WEIGHT; index+=expr)
			if((weight() - this.Weight) * expr > 0)
				break;
		ctl.CustomProperties.GroupID =  isItemCountReceived?null:this.GroupID;
		ctl.ParentControl.MoveControl(ctl.__controlIndex, index-expr);
		ctl.ParentControl.__ApplyFiltersByType(UI.ContentCssClassFilter);
	}]
});

DeclareClass("UI.NotAnonymousUser", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)	{	
		this.__SetApplyStages("PreferenceChange");
	}]
	,Apply : [decl_virtual, function(ctl, stage) {		
		ctl.SetVisibleState(!IS_ANONYMOUS_USER);		
	}]
});

DeclareClass("UI.ApplicationComponentFilter", "UI.ControlFilter",
{
	Init: [decl_virtual, function(data)	{	
 		this.__SetApplyStages("PreInit","Update");
		this.Component = APP_APPLICATIONSECTIONS[data && data.getAttribute("ComponentName")];
		if(this.Component == null)
			throw "ComponentName should be property name of APP_APPLICATIONSECTIONS enum";
	}]
	,Apply : [decl_virtual, function(ctl, stage) {		
		var isVisible = (APPLICATIONCOMPONENTS & this.Component) == this.Component;
		ctl.SetVisibleState(ctl.GetVisibleState() && isVisible);
	}]
});
("UI");
DeclareNamespace("UI.Controls");
DeclareNamespace("SiteLayout");

DeclareClass("UI.Controls.EventTypesControl", "UI.Control",
{	
	constructor: function()
	{
		this.base();
		this.__table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		this.__table.className = "table-default";
		this.__table.insertRow();
		this.__groups = [];
	}
	,Init : [decl_virtual, function()
	{
		if (!TPEventGroupCache || TPEventGroupCache.length == 0) return;
		for (var i = 0, ic = TPEventGroupCache.length; i < ic; i++)
		{
			var eventGroup = TPEventGroupCache[i];
			var tscb = new UI.Controls.EventTypeCheckBox(eventGroup.code,null,eventGroup.name,eventGroup.css);
			this.AddControl(tscb);
			this.__groups.push(tscb);
		}
	}]
	,Render : [decl_virtual, function(writer)
	{
		this.HostElement.appendChild(this.__table);
		var row = this.__table.rows[0];
		var cell;
		for (var i = 0, ic = this.__groups.length; i < ic; i++)
		{
			cell = row.insertCell();
			cell.noWrap = true;
			this.__groups[i].RenderControl(cell);
		}		
	}]	
});

DeclareClass("UI.Controls.EventSubTypeControl", "UI.Control",
{	
	constructor: function(text, image, code, subcode, defaultstate)
	{
		this.base();
		this.__mscontrol = new UI.Controls.DoubleStateControl(defaultstate);
		this.__mscontrol.AttachEvent("click",this.CreateCallback(this.ChangeState));
		this.__textcontrol = new UI.Controls.Label(text);
		this.__imagecontrol = new UI.Controls.Image("EventTypesIcon/"+image,"14px","14px");
		this.__code = code;
		this.__subcode = subcode;		
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function()
	{
		this.__manager = UI.Filters.EventsTypeManager.GetInstance();
		this.AddControl(this.__mscontrol);
		this.AddControl(this.__imagecontrol);
		this.AddControl(this.__textcontrol);
		this.Listeners.AddObjectListener(this.__manager, "oneventsubtypestatuschange", this.SetState);		
	}]
	,GetState : function()
	{
		return this.__mscontrol.GetState();
	}
	,SetState : function(state)
	{
		this.__mscontrol.SetState(state);
	}
	,Render : [decl_virtual, function(writer)
	{
		this.base.Render();
		this.SetCssClass("events-type events-type-auxiliary");
		this.__mscontrol.Listeners.AddDOMListener(this.HostElement,"click", this.__mscontrol.Click);		
	}]
	,ChangeState : function(obj, state)
	{
		this.__manager.SetEventSubTypeStatus(this.__code,this.__subcode,state);
	}
	,SetState : [decl_virtual, function(subcode, state)
	{
		if (subcode == this.__subcode)
			this.__mscontrol.SetState(state);
	}]
});

DeclareClass("UI.Controls.EventSubTypesControl", "UI.Control",
{	
	constructor: function()
	{
		this.base();
		this.__table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		this.__table.className = "table-default";
		this.__subgroups = [];
		this.__searchButton = new UI.Controls.Button("Apply","UI.Filters.EventsTypeManager.GetInstance().DoSearch()","event-type-submit");
	}
	,Init : [decl_virtual, function()
	{
		if (!TPEventGroupCache || TPEventGroupCache.length == 0) return;
		var manager = UI.Filters.EventsTypeManager.GetInstance();
		for (var i = 0, ic = TPEventGroupCache.length; i < ic; i++)
		{
			var eventSubGroups = TPEventGroupCache[i].subgroups;
			var groupCode = TPEventGroupCache[i].code;
			for (var j = 0, jc = eventSubGroups.length; j < jc; j++)
			{
				var eventSubGroup = eventSubGroups[j];
				var estc = new UI.Controls.EventSubTypeControl(eventSubGroup.name,eventSubGroup.imagePath,groupCode,eventSubGroup.code,
					manager.GetEventSubTypeStatus(groupCode, eventSubGroup.code));
				this.AddControl(estc);
				this.__subgroups.push(estc);			
			}
		}
		this.AddControl(this.__searchButton);
	}]
	,Render : [decl_virtual, function(writer)
	{
		this.HostElement.style.width = "100%";
		this.__table.style.width = "100%";
		this.HostElement.appendChild(this.__table);
		var row = this.__table.rows[0];
		var count = 0;
		var row = this.__table.insertRow();
		var cell = null;
		for (var i = 0, ic = this.__subgroups.length; i < ic; i++)
		{
			if (count == 10 || cell == null)
			{
				count = 0;
				cell = row.insertCell();
				cell.vAlign = "top";				
			}
			this.__subgroups[i].RenderControl(cell);
			count++;			
		}
		this.__searchButton.RenderControl(cell);
	}]	
});

DeclareClass("UI.Controls.EventTypeCheckBox", "UI.Controls.TripleStateCheckBox",
{	
	constructor: function(code, defaultstate, text, css)
	{
		this.base(defaultstate, text, css);		
		this.__code = code;		
	}
	,Init :[decl_virtual, function()
	{
		this.base.Init();
		this.__manager = UI.Filters.EventsTypeManager.GetInstance();
		this.AttachEvent("click",this.CreateCallback(this.ChangeState));
		this.__manager.AttachEvent("oneventtypestatuschange",this.CreateCallback(this.SetState));
	}]
	,ChangeState : function(obj, state)
	{
		this.__manager.SetEventTypeStatus(this.__code,state);
	}
	,SetState : [decl_virtual, function(code,state)
	{
		if (code == this.__code)
			this.base.SetState(state);
	}]
});

DeclareClass("UI.Controls.EventsFilterBar", "UI.Controls.CollapsibleControl",
{	
	constructor: function()
	{
		this.base(false);
		this.AsyncRenderingEnabled = true;		
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.__manager = UI.Filters.EventsTypeManager.GetInstance();
		this.ContentControl.SetCssClass("tool-filter-panel");
		this.AddUIControlToHeader(new UI.Filters.EventsFilterBarHeader(this));
		this.AddUIControlToContent(new UI.Filters.EventsFilterBarContent(this));
		this.HeaderControl.style.width = "100%";//SetWidth("100%");
		this.HeaderControl.className = "module-inner";
		this.SetCssClass("module-outer module-actions");
		this.ContentControl.SetWidth("100%");
		srch_seAttachEvent("onstatechange", this.CreateCallback(this.AnalyzeSearchState));
		nav_AttachEvent("onnavigationchange", this.CreateCallback(this.AnalyzeNavigationParameters));
		this.__manager.AttachEvent("oneventtypestatuschange",this.CreateCallback(this.SearchByEventType));
		//this.__manager.AttachEvent("oneventsubtypestatuschange",this.CreateCallback(this.SearchByEventType));
	}]
	,AnalyzeSearchState : function(state)
	{
		var val = "";
		if (state != SRCH_SES_NONE)
			this.Collapse();
	}
	,AnalyzeNavigationParameters : function(state)
	{
		var sdate = nav_currentNavInfo.GetParameter(P_NAVCALENDAR_DATE);
		if (sdate != null)
			this.Collapse();
	}
	,SearchByEventType : function()
	{
		if (this.IsVisible() && !this.ContentControl.IsVisible())
			this.__manager.DoSearch();
	}
	/*,Render :[decl_virtual, function(writer)
	{
		this.base.Render(writer);
	}]*/	
});

DeclareClass("UI.Controls.FeedCategoryButton", "UI.Controls.DoubleStateControl",
{	
	constructor: function(defaultstate, checkedCss, uncheckedCss, catId, isGroup, isServer)
	{
		this.__catId = catId;
		this.__lastState = null;
		this.__isGroup = isGroup;
		this.__isServer = isServer == false ? false : true;
		this.base(defaultstate, checkedCss, uncheckedCss);		
	}
	,OnClick :[decl_virtual, function(state)
	{
		this.__lastState = state;
		if (this.__isServer)
		{
			if (!AuthorizationNeeded()) {
				this.Lock();
				this.FireEvent("lock",this,true);
				new httpcmd_FeedCategoryChangeSubscription(this.__catId, state == UI.CheckBoxStates.CHECKED, this.CreateCallback(this.OnComplete));
			}	
		}
		else
			this.OnComplete(true);
	}]
	,OnComplete : function(isOk)
	{
		if (this.__isServer)
		{
			this.Unlock();
			this.FireEvent("lock",this,false);
		}
		if (isOk)
		{
			this.SetState(this.__lastState);
			this.FireEvent("click",this,this.__currentState);
		}
		if (this.__isServer)
			nav_RefreshWorkspaceModules(KEY_FEEDCATEGORY);
	}
});

DeclareClass("UI.Controls.FeedCategoryTypeControl", "UI.Control",
{		
	constructor: function(category,isServer,subscribe)
	{
		this.__category = category;
		this.__val = this.__category.GetNodeValue(FeedCategoryItem.PN_ID);
		this.__dispval = this.__category.GetNodeValue(FeedCategoryItem.PN_DISPLAYVALUE);
		this.__groupID = this.__category.GetNodeValue(FeedCategoryItem.PN_GROUPID);
		this.__isGroup = eval(this.__category.GetNodeValue(FeedCategoryItem.PN_ISGROUP));
		this.__isUnsub = this.__category.GetNodeValue(FeedCategoryItem.PN_ISUNSUBSCRIBED) == "true";
		this.__subscribeByDefault = subscribe == true;
		this.__action = "do_inpDoSearchByFilter(SRCH_TN_FEEDCATEGORY, '"+this.__val+"', '"+this.__dispval.replace(/\'/ig,"\\\'")+"', true)";
		this.__isServer = isServer == false ? false : true;
		this.__link = null;
		this.__text = null;
		this.__btn = null;
		this.base();
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,GetCategoryID : function(){return this.__val;}
	,GetGroupID : function(){return this.__groupID;}
	,GetDisplayValue : function(){return this.__dispval;}
	,IsGroup : function(){return this.__isGroup;}
	,Init : [decl_virtual, function()
	{
		this.__text = new UI.Controls.LiteralControl(cmn_htmlEncode(this.__dispval));
		this.__text.SetCssClass("ctg-text display-inline");
		this.__text.SetStyleAttribute("fontWeight",this.__isGroup || this.__groupID == -1 ? "bold" : "normal");
		this.__btn = new UI.Controls.FeedCategoryButton(!this.__subscribeByDefault && this.__isUnsub ? UI.CheckBoxStates.UNCHECKED : UI.CheckBoxStates.CHECKED, "ctg-checked", "ctg-unchecked", this.__val, this.__isGroup, this.__isServer);
		this.Listeners.AddObjectListener(this.__btn, "click", this.CreateCallback(this.ChangeSubscribtion));
		this.Listeners.AddObjectListener(this.__btn, "lock", this.CreateCallback(this.ChangeAccess));
		this.AddControl(this.__btn);
		if (this.__isServer)
		{
			this.__link = new UI.Controls.ScriptLink(this.__dispval, this.__action, false, null, "ctg-link");
			this.__link.SetStyleAttribute("fontWeight",this.__isGroup || this.__groupID == "-1" ? "bold" : "normal");
			this.AddControl(this.__link);
		}
		else
			this.__text.SetStyleAttribute("color","#003399");
		this.AddControl(this.__text);
		this.SetCurrentState(false);
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__link = null;
		this.__text = null;
		this.__btn = null;
	}]
	,SetCurrentState : function(isText)
	{
		if (!this.__isServer) return;
		if (this.__text != null)
			this.__text.SetVisibleState(isText);
		if (this.__link != null)
			this.__link.SetVisibleState(!isText);
	}
	,ChangeSubscribtion : function()
	{
		this.FireEvent("subscriptionchanged",this.IsSubscribed(),this.IsGroup(),this.GetCategoryID(),this.GetGroupID());
	}
	,ChangeAccess : function()
	{
		this.FireEvent("accesschanged",this.__btn.IsLocked(),this.IsGroup(),this.GetCategoryID(),this.GetGroupID());
	}
	,IsSubscribed : function()
	{
		if (this.__btn)
			return this.__btn.GetState() == UI.CheckBoxStates.CHECKED;
		return !this.__isUnsub;
	}
	,IsModified : function()
	{
		return this.__isUnsub == this.IsSubscribed();
	}
	,Subscribe : function()
	{
		if (this.__btn)
			this.__btn.SetState(UI.CheckBoxStates.CHECKED);
	}
	,Unsubscribe : function()
	{
		if (this.__btn)
			this.__btn.SetState(UI.CheckBoxStates.UNCHECKED);
	}
	,Disable : function()
	{
		this.__btn.Lock();
	}
	,Enable : function()
	{
		this.__btn.Unlock();
	}
});

DeclareClass("UI.Controls.FeedCategoryTypesControl", "UI.Control",
{		
	constructor: function(isServer,subscribeAll)
	{
		this.base();
		this.__isServer = isServer == false ? false : true;
		this.__categories = null;
		this.__needFullRefresh = false;
		this.__ctrlref = {};
		this.__selectedctrlref = [];
		this.__subscribeAll = subscribeAll == true ? true : false;
		if (this.__isServer)
			this.Listeners.AddCustomListener(new Utils.SearchEventListener([SRCH_TN_FEEDCATEGORY],this.OnSearchStateChange))
		this.KeywordsAttach(KEY_NEWFEEDCATEGORY);
		this.Refresh();
	}
	,GetTagName : function() {return UI.HtmlTag.Table;}
	,Refresh : function() 
	{
		this.__statusTxt = "Loading...";
		new httpcmd_GetFeedCategories(this.CreateCallback(this.RefreshCallback));
	}
	,RefreshCallback : function(xml) 
	{
		this.__categories = Data.Helper.CreateCollectionByInfo(FeedCategoryItem, xml);
		this.__statusTxt = "There are no items to show.";
		this.__needFullRefresh = true;
		this.ProcessRequest();
	}
	,Init : [decl_virtual, function()
	{
		if (this.__categories != null && this.__categories.GetCount() > 0)
		{
			for (var i=0; i < this.__categories.GetCount(); i++)
			{
				var ctrl = new UI.Controls.FeedCategoryTypeControl(this.__categories.GetByIndex(i), this.__isServer, this.__subscribeAll);
				this.Listeners.AddObjectListener(ctrl, "subscriptionchanged", this.CreateCallback(this.ChangeSubscribtion));
				this.Listeners.AddObjectListener(ctrl, "accesschanged", this.CreateCallback(this.ChangeAccess));
				this.AddControl(ctrl);
				this.__ctrlref[ctrl.GetCategoryID()] = ctrl;
			}
		}
	}]
	,SubscribeAll : function(subscr)
	{
		subscr = subscr == false ? false : true;
		this.ChangeSubscribtion(subscr,null,null,null);
	}
	,UnsubscribeAll : function()
	{
		this.SubscribeAll(false);
	}
	,ChangeControlStates : function(type,value,isGroup,catID,groupID)
	{
		var len = this.__controls.length;
		var gSubscribed = true;
		var group = null;
		var alwaysRight = isGroup == null && catID == null && groupID == null;
		if (len > 0)
			for (var i = 0; i < len; i++)
			{
				var ctrl = this.__controls[i];
				if (isGroup || alwaysRight)
				{
					if (ctrl.GetGroupID() == groupID || alwaysRight)
					{
						switch(type)
						{
							case "subscribe":
								value ? ctrl.Subscribe() : ctrl.Unsubscribe();
								break;
							case "lock":
								value ? ctrl.Disable() : ctrl.Enable();
								break;
						}
					}
				}
				else						
				{
					if (ctrl.GetGroupID() == groupID)
					{
						if (ctrl.IsGroup())
							group = ctrl;
						switch(type)
						{
							case "subscribe":
								if (!ctrl.IsGroup())
									gSubscribed = gSubscribed && ctrl.IsSubscribed();
								break;
							case "lock":
								break;
						}
					}
				}
			}
		if (!isGroup && group)
		{
			switch(type)
			{
				case "subscribe":				
					if (!gSubscribed)
						group.Unsubscribe();
					break;
				case "lock":
					value ? group.Disable() : group.Enable();
					break;
			}
		}
	}
	,ChangeAccess : function(isLocked,isGroup,catID,groupID)
	{
		this.ChangeControlStates("lock",isLocked,isGroup,catID,groupID);
	}
	,ChangeSubscribtion : function(isSubscribed,isGroup,catID,groupID)
	{
		this.ChangeControlStates("subscribe",isSubscribed,isGroup,catID,groupID);
	}
	,AMLoad  :[decl_virtual, function()
	{
		this.Refresh();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__ctrlref = null;
	}]
	,Render : [decl_virtual, function(writer)
	{
		this.HostElement.style.width = "100%";
		
		var row = this.HostElement.insertRow();
		var limit = 3;
		for (var i = 0; i < limit; i++)
		{
			var cell = row.insertCell();
			cell.vAlign = "top";
			cell.width = (100 / limit) + "%";
		}
		
		var len = this.__controls.length;
		var countInCell = len/limit;
		var curCount = 0;
		var latestGroup = null;
		var curCell = 0;
		var tcount = 0;
		if (len > 0)
		{
			for (var i = 0; i < len; i++)
			{
				var curGroup = this.__controls[i].GetGroupID();
				var curID = this.__controls[i].GetCategoryID();
				var isGroup = this.__controls[i].IsGroup();
				if (latestGroup != null && latestGroup != curGroup && curCount != 0)
				{
					var div = DOMObjectFactory.CreateElement("div");
					div.className = "ctg-space";
					div.innerHtml = "&nbsp;"					
					row.cells[curCell].appendChild(div);
				}
				if ((curCount < countInCell || latestGroup == curGroup) && (latestGroup == curGroup || len - i > curCount))
				{
					curCount++;
					latestGroup = curGroup;
					if (!isGroup && curGroup != -1)
						this.__controls[i].SetCssClass("filter-item-directory category-directory");
					else
						this.__controls[i].SetCssClass("category-directory");
					this.__controls[i].RenderControl(row.cells[curCell]);
				}	
				else
				{
					i--;
					curCell++;
					if (curCell > limit - 1)
						curCell = 0;
					tcount = tcount < curCount ? curCount : tcount;
					curCount = 0;
					latestGroup = null;
				}
			}
			this.OnSearchStateChange();
		}
		else
			this.HostElement.insertRow().insertCell().appendChild(document.createTextNode(this.__statusTxt));		
	}]
	,Update :[decl_virtual, function(writer)
	{
		var res;
		if (this.__needFullRefresh)
			res = UI.UpdateStatus.FULL_REFRESH; 
		else
			res = UI.UpdateStatus.CHILDREN_REFRESH; 
			
		this.__needFullRefresh = false;
		return res;
	}]	
	,OnSearchStateChange : function(listener)
	{
		if (!this.__isServer) return;
		while(this.__selectedctrlref.length > 0)
			this.__selectedctrlref.pop().SetCurrentState(false);
		var tags = srch_inpGetTags(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME, SRCH_TN_FEEDCATEGORY)))
		if (tags != null && tags.length > 0)
		{
			for(var i=0; i < tags.length; i++)
			{
				var ctrl = this.__ctrlref[tags[i].selectSingleNode(SRCH_TP_VALUE).text];
				if (ctrl != null)
				{
					ctrl.SetCurrentState(true);
					this.__selectedctrlref.push(ctrl);
				}
			}
		}
	}
	,GetSubscriptions : function()
	{
		var len = this.__controls.length;
		var result = [];
		var collection = Data.Helper.CreateCollectionByInfo(FeedCategoryItem, "<FeedCategoryItemCollection/>");
		if (len > 0)
			for (var i = 0; i < len; i++)
			{
				var ctrl = this.__controls[i];
				if (!ctrl.IsModified()) continue;
				var xItem = data_createEmptyItem(FeedCategoryItem);
				xItem.SetNodeValue(FeedCategoryItem.PN_ID, ctrl.GetCategoryID());
				xItem.SetNodeValue(FeedCategoryItem.PN_DISPLAYVALUE, ctrl.GetDisplayValue());
				xItem.SetNodeValue(FeedCategoryItem.PN_ISGROUP, ctrl.IsGroup() + '');
				xItem.SetNodeValue(FeedCategoryItem.PN_GROUPID, ctrl.GetGroupID());
				xItem.SetNodeValue(FeedCategoryItem.PN_ISUNSUBSCRIBED, !ctrl.IsSubscribed() + '')
				collection.AddXmlItem(xItem.GetXml());
			}
		return collection;
	}
});

DeclareClass("UI.Controls.FeedCategoryFilterBar", "UI.Controls.CollapsibleControl",
{	
	constructor: function()
	{
		this.base(true);		
		this.__categoriescontrol = null;
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init()
		this.AttachEvent("onvisiblechange", this.CreateCallback(this.__OnVisibleStateChange));
		this.ContentControl.SetCssClass("tool-filter-panel");
		this.AddUIControlToHeader(new UI.Filters.FeedsCategoryFilterBarHeader(this));
		this.__categoriescontrol = new UI.Filters.FeedsCategoryFilterBarContent(this)
		this.AddUIControlToContent(this.__categoriescontrol);
		this.HeaderControl.style.width = "100%";
		this.HeaderControl.className = "module-inner";
		this.SetCssClass("module-outer module-actions");
		this.ContentControl.SetWidth("100%");
	}]
	/*,Render :[decl_virtual, function(writer)
	{
		this.base.Render(writer);
	}]*/	
	,__OnVisibleStateChange: function(v)
	{
		if (v)
			this.Expand();
	}
	,SubscribeAll : function()
	{
		if (this.__categoriescontrol)
			this.__categoriescontrol.SubscribeAll();
	}
	,UnsubscribeAll : function()
	{
		if (this.__categoriescontrol)
			this.__categoriescontrol.UnsubscribeAll();
	}
});

DeclareClass("SiteLayout.SynopsisHeadlinesFilterControl", "SiteLayout.ModuleInfoDOMControl",
{	
	constructor: function()
	{
		this.base();	
		this.__TXT_SORT01 = "Sort";
		this.__TXT_SORT02 = "Sorted";
		this.__TXT_RELEVANCE = "~0 by relevance";
		this.__TXT_DATE = "~0 by date";
		this.__TYPE = {Relevance:"Relevance", Date:"PostedDate"};		
		
		this.__linkRelevance = null;
		this.__linkDate = null;	
		this.__tdLinkRelevanceHost = null;
		this.__tdLinkDateHost = null;
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init()
		
		this.ModuleListener = new Utils.ModuleEventListener(null, KEY_MAINCONTENTMODULE, this.OnModuleStateChange, this.OnModuleStateChange);
		this.Listeners.AddCustomListener(this.ModuleListener);		
	}]	
	,__GetCurrentSortSettings : function()
	{
		var module = this.ModuleListener.GetModule();
		if (module && module.IsVisible()) 
		{
			var prefs = ModulesPreferencesStorage.getModulePreferences(module.name, module.defaultPrefs);
			var sortType = prefs.getRelevanceSort();
			
			return (sortType==null || sortType==undefined || sortType=="Undefined") ? this.__TYPE.Date : sortType;			
		}		
		return this.__TYPE.Date;	
	}	
	,__FormatRelevanceLink : function()
	{
		this.__RemoveChildren(this.__tdLinkRelevanceHost.Obj());
		switch(this.__GetCurrentSortSettings())
		{
			case this.__TYPE.Relevance :				
				this.__linkRelevance = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
				this.__linkRelevance.innerText = this.__TXT_RELEVANCE.format(this.__TXT_SORT02);				
			break;

			case this.__TYPE.Date :
				this.__linkRelevance = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
				this.__linkRelevance.href = "#";
				dom_attachEventForObject(this.__linkRelevance,"click", this.CreateCallback(this.__SortByRelevanceClick));
				this.__linkRelevance.innerText = this.__TXT_RELEVANCE.format(this.__TXT_SORT01);			
			break;			
			
			default:
			break;
		}
		this.__tdLinkRelevanceHost.Obj().appendChild(this.__linkRelevance);
	}	
	,__FormatDateLink : function()
	{
		this.__RemoveChildren(this.__tdLinkDateHost.Obj());
		switch(this.__GetCurrentSortSettings())
		{
			case this.__TYPE.Relevance :
				this.__linkDate = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
				this.__linkDate.href = "#";
				dom_attachEventForObject(this.__linkDate,"click", this.CreateCallback(this.__SortByDateClick));
				this.__linkDate.innerText = this.__TXT_DATE.format(this.__TXT_SORT01);						
			break;

			case this.__TYPE.Date :				
				this.__linkDate = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
				this.__linkDate.innerText = this.__TXT_DATE.format(this.__TXT_SORT02);			
			break;			
			
			default:
			break;
		}
		this.__linkDate.id = "right";
		this.__tdLinkDateHost.Obj().appendChild(this.__linkDate);
	}		
	,Update :[decl_virtual, function(writer)
	{ 
		switch(nav_currentNavInfo.GetPageID())
		{
			case PID_FEEDS:
			case PID_TRENDS:
				this.SetVisibleState(true);
				this.__FormatRelevanceLink();
				this.__FormatDateLink();		
			break;
			default:
				this.SetVisibleState(false);
			break;
		}
		return UI.UpdateStatus.NOUPDATE; 
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(nav_currentNavInfo.GetPageID()!=PID_FEEDS
			|| nav_currentNavInfo.GetPageID()!=PID_TRENDS)
			this.SetVisibleState(false);
			
		var rows = []; 
		
		// By Relevance & Date
		this.__tdLinkRelevanceHost = new UI.DOMControls.Td();
		this.__tdLinkRelevanceHost.Obj().style.width = "80%";		
		this.__FormatRelevanceLink();
		this.__tdLinkDateHost = new UI.DOMControls.Td();		
		this.__tdLinkDateHost.Obj().style.width = "20%";
		this.__FormatDateLink();
		
		rows.push(new UI.DOMControls.Tr(this.__tdLinkRelevanceHost, this.__tdLinkDateHost));		
		var tbl = new UI.DOMControls.Table(rows);
		tbl.SetCssClass("hdsSorting");
		this.HostElement.appendChild(tbl.Obj());		
	}]	
	,__SortByRelevanceClick : function() 
	{		
		var module = this.ModuleListener.GetModule();
		if (module && module.IsVisible()) 
			nav_ChangeModuleSettingsBatch(module.name, {RelevanceSort:"Relevance"}, undefined);							
	}			
	,__SortByDateClick : function() 
	{	
		var module = this.ModuleListener.GetModule();
		if (module && module.IsVisible()) 
			nav_ChangeModuleSettingsBatch(module.name, {RelevanceSort:"PostedDate"}, undefined);
	}	
	,__RemoveChildren : function(obj)
	{
		if(obj && obj.children && obj.children.length > 0)
			while(obj.children.length>0)
				obj.removeChild(obj.children[0]);
	
	}	
});

DeclareClass("SiteLayout.SynopsisHeadlinesControl", "UI.Controls.Panel", {
    constructor : function() {
        this.base();
        this.CurrentView = null;
    }
	,Init :[decl_virtual, function(){
		// [AL] temporarily disable sorting panel (enabled now)
		this.FilterPanelControl = this.FilterPanelControl();
		this.SynopsisView = this.CreateSynopsisControl(); 
		this.HeadlinesView = this.CreateHeadlinesControl();
		this.CheckState();
		// [AL] temporarily disable sorting panel (enabled now)
		this.AddControl(this.FilterPanelControl);
		this.AddControl(this.SynopsisView);
		this.AddControl(this.HeadlinesView);
	}]
    ,CreateHeadlinesControl :[decl_virtual, function(){
        return new UI.Controls.ServerControlContainer("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonHeadlinesViewPanel");
    }]
    ,CreateSynopsisControl :[decl_virtual, function(){
        return new UI.Controls.ServerControlContainer("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonSynopsisViewPanel");
    }]
	,CheckState: function(){
		var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();
        this.CurrentView = isHeadlinesView ? this.HeadlinesView : this.SynopsisView;
		this.SynopsisView.SetVisibleState(!isHeadlinesView && this.IsVisible());
		this.HeadlinesView.SetVisibleState(isHeadlinesView && this.IsVisible());
	}
	,Update :[decl_virtual, function(writer){
		this.CheckState();
		return this.base.Update();
	}]	
    ,FilterPanelControl :[decl_virtual, function(){
        return new SiteLayout.SynopsisHeadlinesFilterControl();
    }]
	
});

DeclareClass("SiteLayout.SynopsisHeadlinesControlNewsletters", "SiteLayout.SynopsisHeadlinesControl", {
    constructor : function() {
        NewslettersModuleControl.AttachEvent(NS_EVENTS.OnHeadlinesRefresh, this.CreateCallback(this.OnNeedRefresh));
        this.base();
    }
    ,OnNeedRefresh : function() {
        if (this.IsVisible() && this.CurrentView.Dynamic) {
            this.CurrentView.Dynamic.Refresh("Loading headlines...", false);
        }
    }
    ,CreateHeadlinesControl :[decl_virtual, function(){
        return new UI.Controls.ServerControlContainer("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonHeadlinesViewPanel");
    }]
    ,CreateSynopsisControl :[decl_virtual, function(){
        return new UI.Controls.ServerControlContainer("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonSynopsisViewPanel");
    }]
});

DeclareClass("SiteLayout.SynopsisHeadlinesControlWithRelated", "SiteLayout.SynopsisHeadlinesControl", {
    constructor : function() {
        GlobalTrendsEventManager.AttachEvent("onneedrefresh", this.CreateCallback(this.OnNeedRefresh));
        srch_advAttachEvent("ondosearch", this.CreateCallback(this.OnBeforeSearch));
        this.base();
    }
    ,OnNeedRefresh : function() {
        if (this.IsVisible() && this.CurrentView.Dynamic) {
            this.CurrentView.Dynamic.Refresh("Loading headlines...", false);
        }
    }
    ,OnBeforeSearch : function() {
        GlobalTrendsParameters.SetInitialValues();
    }
    ,CreateHeadlinesControl :[decl_virtual, function(){
        return new SiteLayout.CommonHeadlinesViewPanel("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonHeadlinesViewPanel");
    }]
    ,CreateSynopsisControl :[decl_virtual, function(){
        if (nav_currentNavInfo.GetPageID() == PID_TRENDS) {
            return this.CreateHeadlinesControl();
        } else {
            return new SiteLayout.CommonHeadlinesViewPanel("InfoNgen.TouchPoint.Modules.Common.LayoutControls.CommonSynopsisViewPanel");
        }
    }]
});

DeclareClass("SiteLayout.CommonHeadlinesViewPanel", "UI.Controls.DynamicServerControl", {
	constructor : function(control) {
		this.base(control);
	}
	,AttachDynamicElement: [decl_virtual, function(dynamicElement) {
		this.Dynamic = dynamicElement;
		this.Dynamic.AddParameter(P_SUPPORT_XML, 'true');
		this.Dynamic.OnBeforeDataReady = this.CreateCallback(this.OnBeforeDataReady);
        this.Dynamic.OnLoading = this.CreateCallback(this.OnDynamicLoading);
	}]
    ,OnDynamicLoading : function(id, data) {
        GlobalTrendsParameters.CombineTo(this.Dynamic.currentParameters);
        return true;
    }
	,OnBeforeDataReady : function(thisObj, text) {
        if (GlobalTrendsParameters.ShowRelated.GetValue() == 'false')
            //go to ordinary loading
            return true;

		var xmlDoc = new Xml.NodeAccessor(text);
		var headlinesNode = xmlDoc.SelectSingleNode("//xml/Data/Data/Headlines/xml");

		if (headlinesNode != null) {
			var headlinesData = headlinesNode.xml;
            this.Dynamic.OnDataReady(this.Dynamic, headlinesData);
		}

        var haveToRefreshRelated =
             GlobalTrendsParameters.RelatedCompany.IsDefault() &&
			 GlobalTrendsParameters.RelatedTopic.IsDefault() &&
			 GlobalTrendsParameters.RelatedCustomTopic.IsDefault() &&
			 GlobalTrendsParameters.TrendDate.IsDefault();

        if (haveToRefreshRelated||(GlobalTrendsContext.GetRelatedTopics()!=null&&GlobalTrendsContext.GetRelatedTopics().IsUpdating)||(GlobalTrendsContext.GetRelatedCustomTopics()!=null&&GlobalTrendsContext.GetRelatedCustomTopics().IsUpdating)||(GlobalTrendsContext.GetRelatedCompanies()!=null&&GlobalTrendsContext.GetRelatedCompanies().IsUpdating)) {
			var relatedCompaniesNode = xmlDoc.SelectSingleNode("//xml/Data/Data/RelatedCompanies/xml");
            if (relatedCompaniesNode != null) {
				var companies = GlobalTrendsContext.GetRelatedCompanies();
				if(companies)
					companies.RenderRelated(relatedCompaniesNode.xml);
            }

            var relatedTopicsNode = xmlDoc.SelectSingleNode("//xml/Data/Data/RelatedTopics/xml");
            if (relatedTopicsNode != null) {
				var topics = GlobalTrendsContext.GetRelatedTopics();
				topics.RenderRelated(relatedTopicsNode.xml);
            }
            
            var relatedCustomTopicsNode = xmlDoc.SelectSingleNode("//xml/Data/Data/RelatedCustomTopics/xml");
            if (relatedCustomTopicsNode != null) {
				var customTopics = GlobalTrendsContext.GetRelatedCustomTopics();
				customTopics.RenderRelated(relatedCustomTopicsNode.xml);
            }            
        }

		// skip ordinary loading of data:
		return false;
	}
	,Update :[decl_virtual, function(writer) {
        return UI.UpdateStatus.NOUPDATE;
//		return this.base.Update(writer);
	}]
});


DeclareClass("SiteLayout.SwitchList", "UI.Control", {
	AddItem: function(text, value){
		if(!this.items) this.items = [];
		this.items.push({text:text, value:value});
	}
	,GetTagName : function() {return "ul";}
	,Render :[decl_virtual, function(writer){
		var h = this.HostElement;
		h.className = "lmodule-list";
		for(var i=0, item; item=this.items[i]; i++){
			var li = DOMObjectFactory.CreateElement("li");
			li.setAttribute("vl", item.value)
			li.innerHTML = "<a href='#'>"+item.text+"</a>";
			h.appendChild(li);
		}
		this.Listeners.AddDOMListener(h,"click",this.__onSwitch);
		this.__Update();
	}]
	,Update :[decl_virtual, function(writer){
		this.__Update();
		return UI.UpdateStatus.NOUPDATE;
	}]
	,__Update: function(){
		var childrens = this.HostElement.children;
		for(var i=0, item; item = childrens[i]; i++)
			item.className = this.IsSelect(item.getAttribute("vl"))?"lmodule-list-selected":"";
	}
	,IsSelect :[decl_virtual, function(value){ return false; }]
	,OnSwitch :[decl_virtual, function(value){ }]
	,__onSwitch: function(){
		var src = event.srcElement;
		if(src.tagName.toLowerCase()=="a" && src.parentElement.className !="lmodule-list-selected" ){
			this.OnSwitch(src.parentElement.getAttribute("vl"));
			this.__Update();
		}
		return false;
	}	
});

DeclareClass("SiteLayout.ContentViewSwitch", "SiteLayout.SwitchList", {
	Init :[decl_virtual, function(){
		this.AddItem("Synopsis", "s");
		this.AddItem("Headlines", "h");
	}]
	,IsSelect :[decl_virtual, function(value){ 
		return SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState() == (value == "h");
	}]
	,OnSwitch :[decl_virtual, function(value){
		Utils.MonitoringHelper.SetMonitoringInfo(MA_ContentViewSwitch);
		SiteLayout.ContentViewSwitch.ChangeCurrentHeadlinesState();
		nav_UpdateCurrentNavigation();
	}]
	
	,GetLocationBit : [decl_static, function(){
		switch(nav_currentNavInfo.GetPageID()){
			case PID_FEEDS:
			case PID_TRENDS:
				return nav_currentNavInfo.GetPageLocation() == PID_PLMANAGEFEEDS?4:1;
			case PID_FOLDERS: 
				return nav_currentNavInfo.GetPageLocation() == PID_PLMANAGEFOLDERS?8:2;
			case PID_CALENDARS:
				return 16;
			case PID_BLOGS:
				return 32;
			case PID_MYACCOUNT:
				return nav_currentNavInfo.GetPageLocation() == PID_PLMYACCOUNTPREFERENCESMYNEWSLETTERS?1:64;				
		}
	 }]
	,GetCurrentHeadlinesState : [decl_static, function(){
		return (TouchPointSettings.getHeadlinesViewState()&SiteLayout.ContentViewSwitch.GetLocationBit())>0;
	}]
	,ChangeCurrentHeadlinesState : [decl_static, function(){
		var value = TouchPointSettings.getHeadlinesViewState() ^ SiteLayout.ContentViewSwitch.GetLocationBit();
		TouchPointSettings.setHeadlinesViewState(value);
		if (!IS_ANONYMOUS_USER)
			new httpcmd_SetPreferenceValue("HeadlinesViewState", value);
	}]
});

DeclareClass("SiteLayout.TrendsViewSwitch", "SiteLayout.SwitchList", {
	constructor : function() {
		this.base();
		this.needRefresh = false;
		srch_advAttachEvent("ondosearch", this.CreateCallback(this.NeedRefresh));
		nav_AttachEvent("onnavigationchange", this.CreateCallback(this.NeedRefresh));
	}
	,Init :[decl_virtual, function(){
		this.AddItem("Chart", "trends");
		this.AddItem("Region Map", "map");
	}]

	,NeedRefresh : function() {
		this.needRefresh = true;
	}

	,IsSelect :[decl_virtual, function(value){
		return TouchPointSettings.getTrendsViewState() == value;
	}]

	,OnSwitch :[decl_virtual, function(value){
		TouchPointSettings.setTrendsViewState(value);

		var needRefresh = !GlobalTrendsParameters.IsHeadlinesNotFiltered();

		GlobalTrendsParameters.MapIndustry.SetDefaultValue();
		GlobalTrendsParameters.MapRegion.SetDefaultValue();
		GlobalTrendsParameters.TrendDate.SetDefaultValue();
//		GlobalTrendsParameters.TrendDate.SetValue("");
		GlobalTrendsParameters.RelatedCompany.SetDefaultValue();
		GlobalTrendsParameters.RelatedTopic.SetDefaultValue();
		GlobalTrendsParameters.RelatedCustomTopic.SetDefaultValue();

		var zzz = GlobalTrendsParameters.GetQueryString();

		GlobalTrendsContext.GetCurrentDiagram().Refresh();

		GlobalTrendsContext.GetRelatedCompanies().RefreshRelated();
		GlobalTrendsContext.GetRelatedTopics().RefreshRelated();
		GlobalTrendsContext.GetRelatedCustomTopics().RefreshRelated();
		GlobalTrendsEventManager.OnNeedRefresh();

		this.needRefresh = false;
	}]

	,GetTrendsViewState : [decl_static, function() {
		return TouchPointSettings.getTrendsViewState();
	}]

/*	,GetCurrentHeadlinesState : [decl_static, function(){
		return (TouchPointSettings.getHeadlinesViewState()&SiteLayout.ContentViewSwitch.GetLocationBit())>0;
	}]
	,ChangeCurrentHeadlinesState : [decl_static, function(){
		var value = TouchPointSettings.getHeadlinesViewState() ^ SiteLayout.ContentViewSwitch.GetLocationBit();
		TouchPointSettings.setHeadlinesViewState(value);
		if (!IS_ANONYMOUS_USER)
			new httpcmd_SetPreferenceValue("HeadlinesViewState", value);
	}]   */
});

DeclareClass("SiteLayout.WideScreenSwitch", "SiteLayout.SwitchList", {
	Init :[decl_virtual, function(){
		this.AddItem("Normal", "false");
		this.AddItem("Widescreen", "true");
	}]
	,IsSelect :[decl_virtual, function(value){
		return TouchPointSettings.getWideLayout() == value;
	}]
	,OnSwitch :[decl_virtual, function(value){
		Utils.MonitoringHelper.SetMonitoringInfo(MA_SwitchWideScreen);
		do_updateLayout(value == "true");
		if (!IS_ANONYMOUS_USER)
			new httpcmd_SetPreferenceValue("WideLayout", value);
	}]
});

DeclareClass("SiteLayout.ModuleInfoControl", "UI.Control", 
{
	constructor : function()
	{
		this.base();
		this.ModuleListener = new Utils.ModuleEventListener(null, KEY_MAINCONTENTMODULE, this.OnModuleStateChange, this.OnModuleStateChange);
		this.Listeners.AddCustomListener(this.ModuleListener);
	}
	,GetRenderType : function() {return UI.RenderType.HTML;}
	,OnModuleStateChange : [decl_virtual, function(mod)
	{
		this.ProcessRequest();
	}]
});

DeclareClass("SiteLayout.ModuleInfoDOMControl", "SiteLayout.ModuleInfoControl", 
{
	GetRenderType : function() {return UI.RenderType.DOMCREATION;}
});

DeclareClass("SiteLayout.ModuleRefreshControl", "SiteLayout.ModuleInfoDOMControl", 
{
	Init : [decl_virtual, function() {		
		this.timeElement = DOMObjectFactory.CreateElement("span");
		new dom_DOMObject(this.timeElement).applyClass("action-title");
		
		/*var img = DOMObjectFactory.CreateElement("img");
			img.style.borderStyle = "none";
			img.style.verticalAlign = "middle";
			img.src = cmn_GetImageUrl("refresh.png");*/

		this.refreshLink = DOMObjectFactory.CreateElement("a");
		this.refreshLink.href = "#";		
		//this.refreshLink.appendChild(img);
		this.refreshLink.appendChild(document.createTextNode("Refresh"));
	}],
	
	updateContent: function() {

		var html = "Updated " + date_setFormatedDateTime(null, Utils.GeneralPreferences.GetTimeFormat(), GeneralPreferences.offsetHours) + " ";
		if (this.timeElement)
			this.timeElement.innerHTML = html;		
		var module = this.ModuleListener.GetModule();	
		if (module != null && this.refreshLink) {
			dom_attachEventForObject(this.refreshLink, "click", function(e) 
			{ 
				e.returnValue = false; 
				Utils.MonitoringHelper.SetMonitoringInfo(MA_Refresh);
				var storeSortType = ModulesPreferencesStorage.getModulePreferences(module.name, module.defaultPrefs).getRelevanceSort();
				nav_RefreshWorkspaceModule(module.name, "Loading..."); 
				//setup sort mode
				nav_ChangeModuleSettingsBatch(module.name, {RelevanceSort:storeSortType}, undefined);
			});
		}		
	},
	
	Update :[decl_virtual, function(writer) { 
		this.updateContent();
		return UI.UpdateStatus.NOUPDATE; 
	}],
	
	Render :[decl_virtual, function(writer) {
		this.HostElement.appendChild(this.timeElement);
		this.HostElement.appendChild(this.refreshLink);
		this.updateContent();		
	}]
});

function dom_createForm(action, method) {
	var formElement = document.createElement("form");
	formElement.method = method;
	formElement.action = action;
	var body = document.getElementsByTagName("body")[0];
	body.appendChild(formElement);
	return formElement;
}

function dom_addHiddenField(formElement, fieldName, fieldValue) {
	var inputElement = document.createElement("input");
	inputElement.setAttributeNode(dom_createAttribute("type", "hidden"));
	inputElement.setAttributeNode(dom_createAttribute("name", fieldName));
	inputElement.setAttributeNode(dom_createAttribute("value", fieldValue));
	formElement.appendChild(inputElement);
}

function dom_createAttribute(name, value) {
	var attribute = document.createAttribute(name);
	attribute.nodeValue = value;
	return attribute;
}

DeclareClass("SiteLayout.ModuleExportControl", "SiteLayout.ModuleInfoDOMControl", 
{
	Init : [decl_virtual, function() {		
		
		var img = DOMObjectFactory.CreateElement("img");
		img.style.borderStyle = "none";
		img.style.verticalAlign = "middle";
		img.style.marginRight = "3px";
		img.src = cmn_GetImageUrl("excel_icon.gif");

		this.exportLink = DOMObjectFactory.CreateElement("a");
		this.exportLink.href = "#";		
		this.exportLink.appendChild(img);
		this.exportLink.appendChild(document.createTextNode("Export"));
		
		var _this = this;
		
		dom_attachEventForObject(this.exportLink, "click", function(e) 
		{ 
			e.returnValue = false;
			
			var module = _this.ModuleListener.GetModule();
			
			var prefs = ModulesPreferencesStorage.getModulePreferences(module.name, module.defaultPrefs);
			var preferenceXml = prefs.getUserPreferencesXml(true);
			var filter = _this._GetFilter();
			//new httpcmd_ExportFeeds(filter, module.name, preferenceXml, nav_currentNavInfo.GetPageID(), _this.iframe, _this.HostElement);

			var queryParams = nav_currentNavInfo.GetNavigationQuery();
			var submitForm = dom_createForm(WebFrameworkConfig.RootUrl + "CommandProcessor.aspx?" + queryParams, "post");
			dom_addHiddenField(submitForm, P_ACTIONTYPE_ID, C_EXPORT_FEEDS);
			dom_addHiddenField(submitForm, P_FILTEREXPRESSION, filter);
			dom_addHiddenField(submitForm, P_MODULE_NAME, module.name);
			dom_addHiddenField(submitForm, P_MODULE_PREFERENCES, preferenceXml);
			dom_addHiddenField(submitForm, P_PAGEID, nav_currentNavInfo.GetPageID());
			submitForm.submit();			
		});
		
	}],
	
	IsExportPage : function() {
		var pageId = nav_currentNavInfo.GetPageID();
		var pageLocation = nav_currentNavInfo.GetPageLocation();
		if ((pageId == PID_FEEDS || pageId == PID_BLOGS) && (pageLocation == null || pageLocation == PID_PLSEARCHRESULTS)) {
			return true;
		}
		false;
	},
	
	_GetFilter : function()
	{
		var cluster = nav_currentNavInfo.GetParameter(P_CLUSTER_ID);
		if (!str_IsStringEmpty(cluster))
			return '<tags />';

		var module = this.ModuleListener.GetModule();
		var filter = '';		
		if(srch_PagesCollection.CurrentSearchPage)
			filter = srch_PagesCollection.CurrentSearchPage().GetLastFilterExpression();
		else if(filter=='' || filter==null)
			filter = srch_inpGetXml();
		
		//if (module.currentCommand == null || module.currentCommand.params == null)
		//	filter = srch_inpGetXml();
		//else 
		//	filter = module.currentCommand.params;
		
		return filter;
	},
	
	Update :[decl_virtual, function(writer) { 
		this.SetVisibleState(this.IsExportPage());
		return UI.UpdateStatus.NOUPDATE; 
	}],
	
	Render :[decl_virtual, function(writer) {
		//adding non-breaking spaces
		this.HostElement.appendChild(document.createTextNode("\u00A0\u00A0\u00A0"));
    
		this.HostElement.appendChild(this.exportLink);
		this.HostElement.appendChild(document.createTextNode("\u00A0"));
	}]
});


DeclareClass("SiteLayout.ModulePagingControl", "SiteLayout.ModuleInfoDOMControl", 
{
	constructor: function SiteLayout_ModulePagingControl(hideEmpty) {
		this.base();
		this.hideEmpty = !!hideEmpty;
	}, 
	
	Init : [decl_virtual, function() {		
		this.container = DOMObjectFactory.CreateElement("span");
	}],	

	Update :[decl_virtual, function(writer){ 
		this.updateContent();
		return UI.UpdateStatus.NOUPDATE; 
	}],	
	
	updateContent: function() {
		var module = this.ModuleListener.GetModule();
		var pageNumber = 1;
		var hasNextPage = false;
		var html = "";
		var hide = false;
		
		if (module && module.IsVisible()) {
			var prefs = ModulesPreferencesStorage.getModulePreferences(module.name, module.defaultPrefs);
			if (prefs) {
				pageNumber = prefs.getPageNumber();
				hasNextPage = prefs.getHasNextPage();
				
				var paging = new ui_PagingControl(module.name, prefs.getItemCountReceived(), prefs.getRowsPerPage(), pageNumber, hasNextPage, prefs.getTotalItemCount());
				html = paging.Render();
				if (this.hideEmpty && pageNumber == 1 && hasNextPage == "false") {
					hide = true;
				}
			}
		} else {
			if (this.hideEmpty) {
				hide = true;
			}
			html = "<span class='pgOfst'>Prev 0-0 Next</span>";
			
		}
		if (this.container)
			this.container.innerHTML = html;
		
		if (this.hideEmpty) {
			this.ParentControl.SetVisibleState(!hide);
		}
	},	
	
	Render :[decl_virtual, function SiteLayout_ModulePagingControl_Render(writer)
	{		
		this.HostElement.appendChild(this.container);
		this.updateContent();
	}]
});


DeclareClass("SiteLayout.ContentAreaToolbar", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.AsyncRenderingEnabled = true;
		this.AsyncControlUpdating = true;
	}
	,Init : [decl_virtual, function()
	{		
		this.itemBar = new UI.Controls.ItemBarBase();
		this.SetCssClass("module-actions");
		this.modulePagingCtl = new SiteLayout.ModulePagingControl();
		this.moduleRefreshCtl = new SiteLayout.ModuleRefreshControl();
		this.moduleExportCtl = new SiteLayout.ModuleExportControl();

		this.AddControl(this.itemBar);
		this.itemBar.AddItem(this.modulePagingCtl);
		this.itemBar.AddItem(this.moduleRefreshCtl, UI.Controls.ItemBarAlign.RIGHT);
		this.itemBar.AddItem(this.moduleExportCtl, UI.Controls.ItemBarAlign.RIGHT);
	}]
	,GetTagName : function() { return UI.HtmlTag.Div; }	
});

DeclareClass("SiteLayout.BottomToolbar", "UI.Control",
{
	Init : [decl_virtual, function()
	{		
		this.SetCssClass("module-actions");
		this.modulePagingCtl = new SiteLayout.ModulePagingControl();
		this.AddControl(this.modulePagingCtl);
	}],
	GetTagName : function() { return UI.HtmlTag.Div; }	
});

DeclareClass("SiteLayout.ActionsBottomToolbar", "SiteLayout.ModuleInfoDOMControl",
{
	constructor: function() {
		this.base();
		this.Actions = Array.getHash(["Subscribe", "Unsubscribe", "SetFavorite"]);
	}
	,Update :[decl_virtual, function(writer){
		var visibleState = nav_currentNavInfo.GetPageLocation() != PID_PLMANAGEFOLDERS; 
			this.addToFavoriteLink.SetVisibleState(visibleState);
			this.addToFavoriteDash.SetVisibleState(visibleState);
		return UI.UpdateStatus.NOUPDATE; 
	}]	
	,InitSubscribeLink : [decl_virtual, function()
	{
		this.subscribeLink = new UI.Controls.ScriptLink("Subscribe All", 
			(function() { this.Execute(this.Actions.Subscribe); return false; }).bind(this));
	}]
	,InitUnsubscribeLink : [decl_virtual, function()
	{
		this.unsubscribeLink = new UI.Controls.ScriptLink("Unsubscribe All", 
			(function() { this.Execute(this.Actions.Unsubscribe); return false; }).bind(this));
	}]
	,InitAddToFavoriteLink : [decl_virtual, function()
	{
		this.addToFavoriteLink = new UI.Controls.ScriptLink("Add to Favorite All", 
			(function() { this.Execute(this.Actions.SetFavorite); return false; }).bind(this));
		this.addToFavoriteDash = new UI.Controls.Label(" - ");
	}]
	,Init : [decl_virtual, function()
	{		
		this.SetCssClass("module-actions");
		
		this.InitSubscribeLink();
		this.InitUnsubscribeLink();
		this.InitAddToFavoriteLink();
		
		if (this.subscribeLink) {
			this.AddControl(this.subscribeLink);
		}
		if (this.unsubscribeLink) {
			if (this.subscribeLink) {
				this.AddControl(new UI.Controls.Label(" - "));
			}	
			this.AddControl(this.unsubscribeLink);
		}
		if (this.addToFavoriteLink) {
			if (this.subscribeLink || this.unsubscribeLink) {
				this.AddControl(this.addToFavoriteDash);
			}	
			this.AddControl(this.addToFavoriteLink);
		}
	}]
	,Execute : function(actionType) {
		var module = this.ModuleListener.GetModule();
		if (module) {
			var dsName = module.GetDSName();
			switch (actionType) {
				case this.Actions.Subscribe :
					do_ChangeSubscriptions(dsName, true);
					break;
				case this.Actions.Unsubscribe:	
					do_ChangeSubscriptions(dsName, false);
					break;
				case this.Actions.SetFavorite:
					do_ChangeFavorites(dsName, true);
					break;
			}
		}
	}	
	,GetTagName : function() { return UI.HtmlTag.Div; }	
});

DeclareEnum("SiteLayout.PageTypes",
{	
	MAIN: 0,
	DIRECTORY: 1,
	OTHER : 2
});

var TPMainPagesLocation = [PID_PLSEARCHRESULTS];

DeclareClass("SiteLayout.PageDescription", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.item = null;
	}
	,Init : [decl_virtual, function()
	{
		this.SetCssClass("nl_des");
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.item = null;
	}]
	,Render :[decl_virtual, function(writer)
	{
		this.item = DOMObjectFactory.CreateElement("span");
		this.HostElement.appendChild(this.item);
		this.item.innerHTML = this.GetPageDescription();
	}]
	,Update :[decl_virtual, function(writer)
	{
		this.item.innerHTML = this.GetPageDescription();
		return UI.UpdateStatus.NOUPDATE; 
	}]
	,GetPageDescription : [decl_virtual, function()
	{
		var mainPage = nav_Pages.GetPage(nav_currentNavInfo.GetPageID());
		var locationPage = nav_Pages.GetPage(nav_currentNavInfo.GetPageLocation());
		var res = mainPage.GetName();
		if (locationPage != null)
		{
			switch(locationPage.GetPageID())
			{
				case PID_PLADVANCEDSEARCH:
					res += " " + locationPage.GetName();
					break;
				default:
					break;
			}
		}
		return res;
	}]
});

DeclareClass("SiteLayout.BackLink", "UI.Control",
{
	constructor : function(cssclass)
	{
		this.base();
		this.cssclass = cssclass;
		this.link = null;
	}
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.link = null;
	}]
	,Init : [decl_virtual, function()
	{
		this.SetCssClass("nl_backlink " + this.cssclass);
		evnt_SubscribeOnEvent(EVT_APPLICATION_COMPONENTS_UPDATED, this.CreateCallback(this.ProcessRequest));
	}]
	,Render :[decl_virtual, function(writer)
	{
		this.link = DOMObjectFactory.CreateElement("a");
		this.link.href = "#";
		this.HostElement.appendChild(this.link);
		this.SetInfo();
	}]
	,Update :[decl_virtual, function(writer)
	{
		this.SetInfo();
		return UI.UpdateStatus.NOUPDATE; 
	}]
	,SetInfo : function()
	{
		if (this.link)
		{
			var page = this.GetPage();
			this.link.innerHTML = "Go Back to " + page.GetName();
			this.link.onclick = new Function("nav_NavigateTo(\""+ page.GetPageID() +"\");return false;");
		}
	}
	,GetPage : function()
	{
		var pid = nav_currentNavInfo.GetPageID();
		if (TPMainPages.indexOf(pid) == -1)
			pid = nav_currentNavInfo.GetLastMainPageID();
		if ((APPLICATIONCOMPONENTS & APP_APPLICATIONSECTIONS[pid]) != APP_APPLICATIONSECTIONS[pid])
			pid = PID_FEEDS;
		return nav_Pages.GetPage(pid);
	}
});

DeclareClass("SiteLayout.NavigationPageDescription", "UI.Control",
{
	GetTagName : function() {return UI.HtmlTag.P;}
	,Init : [decl_virtual, function()
	{
		this.SetCssClass("nl_pd");
		this.AddControl(new SiteLayout.PageDescription());
		this.AddControl(new SiteLayout.BackLink("nl_backlink_s"));
	}]
	,Update :[decl_virtual, function(writer)
	{
		if (this.IsVisible())
			return UI.UpdateStatus.CHILDREN_REFRESH;
		return UI.UpdateStatus.NOUPDATE; 
	}]
});

DeclareClass("SiteLayout.NavigationMenuItem", "UI.Control",
{
	constructor : function(page, pageLoc)
	{
		this.base();
		this.page = page;
		this.pageLoc = pageLoc;
		this.IsSelected = false;
	}
	,GetTagName : function() {return UI.HtmlTag.Span;}
	,Init : [decl_virtual, function()
	{
		this.SetCssClass("notselE");
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose()
		this.page = null;
	}]
	,Render :[decl_virtual, function(writer)
	{		
		var pageId = this.page != null ? this.page.GetPageID() : "";
		var pageLocId = this.pageLoc != null ? this.pageLoc.GetPageID() : ""; 	

		var direcrUrl = null;
		if(pageId && pageId!=undefined && pageId!=null)
		try { direcrUrl = eval("U_~0".format(pageId.toUpperCase()));} catch(ex) {}
		
		var link = DOMObjectFactory.CreateElement("a");	
		if(direcrUrl!=null 
			&& direcrUrl.indexOf("default.aspx")==-1 
			&& direcrUrl.indexOf("http://")!=-1)
		{
				var links = direcrUrl.split(";");
				if(links && links.length==2)
				{
					if(!IS_SNP_USER)
						link.href = links[0];
					else
						link.href = links[1];
				}
				else				
					link.href = direcrUrl;
				link.target = "_blank";
		}
		else
		{
			link.href = "#";
			link.onclick = new Function("nav_NavigateTo(\""+ pageId +"\", null, \""+ pageLocId +"\");return false;");
		}
		link.innerHTML = this.page.GetName();
		this.HostElement.appendChild(link);
		link = null;
	}]
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.NOUPDATE;}]
	,Select : function(sel)
	{
		this.IsSelected = sel;
		var cssClass = sel ? "selE" : "notselE";
		this.SetCssClass(cssClass);
	}
});

DeclareClass("SiteLayout.BaseNavigationMenu", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.items = {};
		this.lastPage = null;
		this.evtAttached = false;
		this.needFullRefresh = false;
	}
	,GetTagName : function() {return UI.HtmlTag.P;}
	,OnComponentsUpdated : function(components)
	{
		APPLICATIONCOMPONENTS = components;
		this.needFullRefresh = true;
		this.ProcessRequest();
	}
	,Init : [decl_virtual, function()
	{
		this.needFullRefresh = false;
		this.SetCssClass("nl00");
		var curArray = this.GetPagesArray();
		var flag = false;
		for (var i = 0; i < curArray.length; i++)
		{
			if ((APPLICATIONCOMPONENTS & APP_APPLICATIONSECTIONS[curArray[i]]) == APP_APPLICATIONSECTIONS[curArray[i]])
			{
				if (flag)
				{
					var sep = new UI.Controls.Image("menuSep.gif", 15, 1)
					sep.SetStyleAttribute("marginBottom", "-3px");
					this.AddControl(sep);
				}
				else
					flag = true;
				this.items[curArray[i]] = this.CreateItem(curArray[i]);
				this.AddControl(this.items[curArray[i]]);
			}
		}
		this.SelectCurrentPage();
		if (!this.evtAttached)
		{
			evnt_SubscribeOnEvent(EVT_APPLICATION_COMPONENTS_UPDATED, this.CreateCallback(this.OnComponentsUpdated));
			this.evtAttached = true;
		}
	}]
	,Dispose :[decl_virtual, function()
	{		
		this.base.Dispose()
		this.items = null;
		this.lastPage = null;
	}]
	,Update :[decl_virtual, function(writer)
	{
		if (!this.needFullRefresh)
		{
			if (this.IsVisible())
			{
				this.SelectCurrentPage();
				return UI.UpdateStatus.CHILDREN_REFRESH
			}
			return UI.UpdateStatus.NOUPDATE; 
		}
		else
			return UI.UpdateStatus.FULL_REFRESH; 
	}]
	,GetPagesArray : [decl_virtual, function()
	{
		return [];
	}]
	,CreateItem : [decl_virtual, function(pageID)
	{
		return new SiteLayout.NavigationMenuItem(nav_Pages.GetPage(pageID));
	}]
	,SelectCurrentPage :function()
	{
		var curPageId = nav_currentNavInfo.GetPageID();
		if (this.lastPage != null && this.items[this.lastPage] != null)
		{
			this.items[this.lastPage].Select(false);
			this.lastPage = null;
		}
		if (this.items[curPageId] != null)
		{
			this.items[curPageId].Select(true);
			this.lastPage = curPageId;
		}
	}
	,GetLastSelectedPage : function()
	{
		return this.lastPage;
	}
});

DeclareClass("SiteLayout.MainNavigationMenu", "SiteLayout.BaseNavigationMenu",
{
	Init : [decl_virtual, function()
	{
		this.base.Init();
		this.SetCssClass(this.GetCssClass() + " nl00_m");
	}]
	,GetPagesArray : [decl_virtual, function()
	{
		return TPMainPages;
	}]
});

DeclareClass("SiteLayout.DirectoryNavigationMenu", "SiteLayout.BaseNavigationMenu",
{
	GetPagesArray : [decl_virtual, function()
	{
		return TPDirectoryPages;
	}]
	,Init : [decl_virtual, function()
	{
		var dirTxt = new UI.Controls.Text("Directory:");
		dirTxt.SetCssClass("lmenu-browse nl_brs");
		this.AddControl(new SiteLayout.BackLink("nl_backlink_d"));
		this.AddControl(dirTxt);
		this.base.Init();
		this.SetCssClass(this.GetCssClass() + " nl00_d");
	}]
	,CreateItem : [decl_virtual, function(pageID)
	{
		return new SiteLayout.NavigationMenuItem(nav_Pages.GetPage(pageID), nav_Pages.GetPage(this.GetLocation(pageID)));
	}]
	,GetLocation : function(pageID)
	{
		switch(pageID)
		{
			case PID_FEEDS: 
				return PID_PLMANAGEFEEDS;
			case PID_FOLDERS:	
				return PID_PLMANAGEFOLDERS;
			case PID_CALENDARS: 
				return PID_PLMANAGECALENDARS;
			case PID_BLOGS: 
				return PID_PLMANAGEBLOGS;
		}
		return null;
	}
});

DeclareClass("SiteLayout.MainNavigationPanel", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.menu = null;
		this.menuDirectory = null;
		this.desription = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init : [decl_virtual, function()
	{
		var pType = this.GetPageType();	
		this.menu = new SiteLayout.MainNavigationMenu();
		this.AddControl(this.menu);
		this.menu.SetVisibleState(pType == SiteLayout.PageTypes.MAIN);
		
		this.menuDirectory = new SiteLayout.DirectoryNavigationMenu();
		this.AddControl(this.menuDirectory);
		this.menuDirectory.SetVisibleState(pType == SiteLayout.PageTypes.DIRECTORY);
		
		this.desription = new SiteLayout.NavigationPageDescription();
		this.AddControl(this.desription);
		this.desription.SetVisibleState(pType == SiteLayout.PageTypes.OTHER);
		this.UpdateLogo(pType);
	}]
	,GetPageType : function()
	{
		var ploc = nav_currentNavInfo.GetPageLocation(), pid = nav_currentNavInfo.GetPageID();
		if (TPMainPages.indexOf(pid) != -1 && (str_IsStringEmpty(ploc) || TPMainPagesLocation.indexOf(ploc) != -1))
			return SiteLayout.PageTypes.MAIN;
		if (TPDirectoryPages.indexOf(pid) != -1 && (str_IsStringEmpty(ploc) || TPDirectoryPagesLocation.indexOf(ploc) != -1))
			return SiteLayout.PageTypes.DIRECTORY;
		return SiteLayout.PageTypes.OTHER;
	}
	,Update :[decl_virtual, function(writer)
	{ 
		var pType = this.GetPageType();
		this.UpdateLogo(pType);
		this.menu.SetVisibleState(pType == SiteLayout.PageTypes.MAIN);
		this.menuDirectory.SetVisibleState(pType == SiteLayout.PageTypes.DIRECTORY);
		this.desription.SetVisibleState(pType == SiteLayout.PageTypes.OTHER);
		return UI.UpdateStatus.CHILDREN_REFRESH; 
	}]
	,UpdateLogo: function(pType){
		$("logo").className = (pType==SiteLayout.PageTypes.MAIN)?"":(pType==SiteLayout.PageTypes.DIRECTORY?"logo_dir":"logo_location");
	}
});


DeclareClass("SiteLayout.LeftMenuItem", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.Title = this.Action = "";
		this.__menu = null;
		this.__AddControl = this.AddControl;
		this.AddControl = this.AddContent;
	}
	,AddContent: function(o)
	{
		if(!this.__menu)
		{
			this.__menu = new UI.Controls.PopupArea();
			this.__menu.SetCssClass("ActionMenu");
			this.__AddControl(this.__menu);
		}
		this.__menu.AddControl(o);
	}
	,GetTagName : function() {return UI.HtmlTag.A;}
	,ProcessCreateData :[decl_virtual, function(data)
	{
		this.base.ProcessCreateData(data);
		this.Title = data.getAttribute("Title");
		this.Action = data.getAttribute("Action");
	}]
	,Render :[decl_virtual, function(writer)
	{
		this.HostElement.innerHTML = this.Title;
		this.HostElement.href = "#";
		if(this.__menu)
			this.__menu.RenderControl(this.HostElement.parentElement);
		this.Listeners.AddDOMListener(this.HostElement,"click",this.onClick);
	}]
	,onClick: function(e)
	{
		if(this.__menu)
			this.__menu.ShowPopup(new UI.PopupareaOptions(this.HostElement));
		else
			eval(this.Action);
		this.FireEvent("click");
		e.returnValue = false;
		return false;
	}	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__menu = null;
	}]
});

DeclareClass("SiteLayout.ModulePanel", "UI.Controls.Panel",
{
	constructor : function() {
		this.base();
		this.headerDiv = null;
	}

	,GetTitle : function(title) {
		if (this.headerDiv) {
			return this.headerDiv.innerHTML;
		}
		return "";
	}

	,ChangeTitle : function(title) {
		if (this.headerDiv) {
			this.headerDiv.innerHTML = title;
		}
	}

	,__GetHeaderControl: function()	{ return this.HeaderControl || (this.HeaderControl = this.InsertControl(new UI.Controls.Panel(), 0)); }
	,__GetContentControl: function()	{ return this.ContentControl || (this.ContentControl = this.InsertControl(new UI.Controls.Panel(), this.HeaderControl?1:0)); }
	,__GetFooterControl: function()	{	return this.FooterControl || (this.FooterControl = this.AddControl(new UI.Controls.Panel())); }
	
	,AddHeaderControl: function(ctrl) {	this.__GetHeaderControl().AddControl(ctrl);  }
	,AddContentControl: function(ctrl){ this.__GetContentControl().AddControl(ctrl); }
	,AddFooterControl: function(ctrl) {	this.__GetFooterControl().AddControl(ctrl); }
	
	,GetContentControls: function()	{ return this.ContentControl.__controls; }
	,ProcessCreateData :[decl_virtual, function(data)
	{
		this.SetCssClass(data.getAttribute("CssClass"));
		this.HeaderCssClass =  data.getAttribute("HeaderCssClass");
		this.HeaderText = data.getAttribute("HeaderText");
		this.HeaderControl = this.__LoadControl(data, "HeaderControl");
		this.ContentControl = this.__LoadControl(data, "ContentControl");
		this.FooterControl = this.__LoadControl(data, "FooterControl");
	}]
	,__LoadControl: function(data, param)
	{
		var ctls = data.selectSingleNode(param);
		if (ctls){
			ctls.setAttribute("ControlName", "UI.Controls.Panel");
			var ctl = UI.Control.LoadControlTemplate(ctls);
			this.AddControl(ctl);
			return ctl;
		}
	}
	
	,Render :[decl_virtual, function(writer)
	{
		if(this.HeaderCssClass || this.HeaderText){
			this.headerDiv = DOMObjectFactory.CreateElement("div");
			this.headerDiv.className = this.HeaderCssClass||"";
			this.headerDiv.innerHTML = this.HeaderText||"";
			this.HostElement.appendChild(this.headerDiv);
		}
		this.base.Render(writer);
	}]
	,SetHeaderCss: function(css){
		if(this.HeaderControl)
			this.HeaderControl.SetCssClass(css);
		else
			if(this.HostElement && this.HostElement.firstChild)
				this.HostElement.firstChild.className = css;
			else
				this.HeaderCssClass = css;
	}
});

DeclareClass("UI.Controls.NavFilterControl", "UI.Control", 
{
	constructor : function(filter)
	{		
		this.base();
		this.__navFilter = filter;
		this.UpdateVisibility();
	}
	,UpdateVisibility : function()
	{
		if (str_IsStringEmpty(this.__navFilter))
			this.SetVisibleState(true);
		else
			this.SetVisibleState(nav_currentNavInfo.HasParamsEx(this.__navFilter));
	}
	,Update : [decl_virtual, function()
	{
		this.UpdateVisibility();
		return UI.UpdateStatus.NOUPDATE;
	}]	
	//,Dispose :[decl_virtual, function(){ this.base.Dispose();}]
});

DeclareClass("UI.Controls.MyBloggingActivityActions", "UI.Controls.DropDown",
{
	SetMsgID : function(msgID) 
	{ 
		this.__msgID = msgID; 
	}
	,SetContainerID : function(containerID) 
	{
		this.__containerID = containerID;
	}
	,SetMsgType : function(msgType)
	{
		this.__msgType = msgType;
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.changeHandler = this.CreateCallback(this.OnChange);
		this.AttachEvent("onselected", this.changeHandler);
		this.LoadItems();
		this.SetCssClass("search-filter-actions");
	}]
	,LoadItems: function()
	{
		this.AddItem("Action...","");
		if (this.__msgType != MT_COMMENT)
			this.AddItem("Edit", "0");
		this.AddItem("Delete", "1");
	}
	,OnChange : function()
	{
		switch(this.SelectedValue)
		{
			case "0":
				do_EditBlogPost(this.__msgID);
				break;
			case "1":
				do_deleteMessage(this.__msgID, this.__containerID);
				break;
			default:
				return;
		}
		this.SetSelectedValue("");	
		return false;
	}
	,Dispose :[decl_virtual, function()	
	{
		this.DetachEvent("onselected", this.changeHandler);
	}]
});

DeclareClass("SiteLayout.MovableSection", "UI.Controls.WorkspacePanel",
{	
	Init : [decl_virtual, function()
	{
		this.base.Init();
		var filter = new UI.ModulePreferenceFilter();
		filter.Param = "ItemCountReceived"; filter.Value = "0"; filter.Operation = ">";
		filter.Init();
		this.__GetContentControl().AddFilter(filter);
		this.CreateHeader();
		if(this.HeaderControl)
			this.HeaderControl.AddFilter(filter);
		filter = new UI.MoveFilter();
		filter.Init(null, this);
		filter.GroupID = "CollapsableSections";
		this.AddFilter(filter);
		this.CreateFooter();
	}]
	,CreateHeader :[decl_virtual, function() {}]
	,CreateFooter :[decl_virtual, function() {}]
});

DeclareClass("SiteLayout.SavedSearchesSection", "SiteLayout.MovableSection",
{	
	ProcessCreateData :[decl_virtual, function(data)
	{
		this.Data = {Feeds:['search-type-feed','lmenu-addfeed'],
					 Calendars:['search-type-event', 'lmenu-addevent', 'Events'],
					 Blogs:['search-type-blog','lmenu-addblog'],
					 Folders:['search-type-folder','lmenu-addfolder']};
		this.base.ProcessCreateData(data);
		this.Type = data.getAttribute("SearchType");
		this.Keywords = "searches";
	}]
	,CreateHeader :[decl_virtual, function()
	{
		this.HeaderControl = this.InsertControl(new UI.Controls.LiteralControl((this.Data[this.Type][2]||this.Type) + " Searches"), 0);
		this.HeaderControl.SetCssClass("lmodule-icon-subtitle " + this.Data[this.Type][0]);
	}]
	,CreateFooter :[decl_virtual, function()
	{
		var link = new SiteLayout.LeftMenuItem();
		//link.SetCssClass("summary-footer-link new-search-icon");
		link.SetCssClass("summary-footer-link icon-footer-link " + this.Data[this.Type][1]);
		link.Title = "New "+ (this.Data[this.Type][2]||this.Type) +" Search";
		link.Action = "do_newSearch('" + this.Type +"')";
		this.AddFooterControl(link);
	}]
});

DeclareClass("SiteLayout.FavoriteSection", "UI.Controls.WorkspacePanel",{
	ProcessCreateData :[decl_virtual, function(data){
		this.base.ProcessCreateData(data);
		this.Type = data.getAttribute("SectionType");
	}]
	,Init : [decl_virtual, function(){
		this.HeaderText = (this.Type == PID_CALENDARS)?"Favorite Calendars":("My Favorite " +this.Type);
		this.HeaderCssClass = "lmodule-subtitle icon-favorites";
		this.base.Init();
		
		var link = new UI.Controls.LiteralControl("Go find some good<br><a href='#' onclick='do_Browse()'> " +this.Type.toLowerCase()+ "</a>!");
		link.SetVisibleState(false);
		var filter = new UI.ModulePreferenceFilter();
		filter.Param = "ItemCountReceived"; filter.Value = "0"; filter.Operation = "<=";
		filter.Init();
		link.AddFilter(filter);
		this.AddFooterControl(link);
	}]
});
DeclareClass("SiteLayout.ManageAlertsSwitchBar", "SiteLayout.ModuleInfoDOMControl",
{
	constructor: function() {
		this.base();
		this.on_BatchCount = 3;
		this.off_BatchCount = 3;
		this.Switch = Array.getHash(["On", "Off"]);
	}
	,Render :[decl_virtual, function(writer)
	{	
		var span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		span.innerText = "Turn all alerts ";
		this.HostElement.appendChild(span);
		
		var onLink = new UI.Controls.ScriptLink("on", 
			(function() { this.Execute(this.Switch.On); return false; }).bind(this));
		this.AddControl(onLink);
		
		span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		span.innerText = " - ";
		this.HostElement.appendChild(span);
		
		var offLink = new UI.Controls.ScriptLink("off", 
			(function() { this.Execute(this.Switch.Off); return false; }).bind(this));
		this.AddControl(offLink);

	}]
	,Execute : function(action) {
		var items = this.GetItems(action);		
		if (items.length > 0) {
			if (!this.statusWindow || this.statusWindow.closed) {
				this.statusWindow = batchOperations.createWindow(null, this.OnWindowClose.bind(this));
			}
			this.cancelExecution = false;
			if (action == this.Switch.On) {
				this.SetAlerts(items);	
			} else {
				this.DeleteAlerts(items);		
			}				
		}
	}
	,CloseWindow : function() {
		if (this.statusWindow && !this.statusWindow.closed) {
			this.statusWindow.close();
		}
	}		
	,OnWindowClose : function() {
		this.cancelExecution = true;
	}
	,GetItems : function(action) {
		var items = [];
		var module = this.ModuleListener.GetModule();
		if (module) {
			var dsName = module.GetDSName();
			var ds = data_GetDataset(dsName);
			if (ds) {
				var items = null;
				switch (action) {
					case this.Switch.On:
						var alerts = [];
						var ids = ds.GetValues(SearchItem.PN_ID);
						var alertsIDs = ds.GetValues(SearchItem.PN_ALERT_ID);
						ids = ids.filter(function(value, index) { return alertsIDs[index] == 0; });
						var alerts = ids.map(function(id) { 
										var alert = data_createEmptyItem(AlertItem);
										alert.SetNodeValue(AlertItem.PN_SEARCHID, id);
										return alert;
									});
						items = alerts;

						break;
					case this.Switch.Off:
						var alertIDs = ds.GetValues(SearchItem.PN_ALERT_ID);
						alertIDs = alertIDs.filter(function(value){ return value > 0; }); 
						items = alertIDs;
						break;
				}
			}
		}
		return items;
	}
	,DeleteAlerts:  function(ids) {		
		if (ids.length > 0 && !this.cancelExecution) {
			var aIDs = ids.splice(0, this.off_BatchCount);
			__GetAlertGlobalObject().DeleteAlert(aIDs, this.DeleteAlerts.bind(this, ids));
		} else {
			this.CloseWindow();
		}	
	}
	,SetAlerts:  function(alerts) {
		if (alerts.length > 0 && !this.cancelExecution) {
			var alertsBatch = alerts.splice(0, this.on_BatchCount);
			__GetAlertGlobalObject().SaveAlert(alertsBatch, this.SetAlerts.bind(this, alerts));
		} else {
			this.CloseWindow();
		}
	}
});
var UserCategoriesSetup = null;
DeclareClass("SiteLayout.UserCategoriesSetup", "UI.Control",
{		
	constructor: function(category)
	{
		this.base();
		this.__setup = null;
		UserCategoriesSetup = this;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init : [decl_virtual, function()
	{
		this.__setup = new UI.Controls.FeedCategoryTypesControl(false,true);
		this.AddControl(this.__setup);
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__setup = null;
	}]
	,GetSubscriptions : function()
	{
		return this.__setup.GetSubscriptions();
	}
});

DeclareClass("SiteLayout.BrowseMenuItem", "SiteLayout.LeftMenuItem",{
	GetTitle: function(){
		var title = "";	
		switch(nav_currentNavInfo.GetPageID()){
			case PID_FOLDERS: title = "Folders"; break;
			case PID_BLOGS: title = "Blogs"; break;
			case PID_CALENDARS: title = "Events"; break;
			default: title = "Feeds"; break;
		}
		return title + " Directory";
	}
	,PreRender : [decl_virtual, function(){
		this.Title = this.GetTitle();
		
	}]
	,Update :[decl_virtual, function(){
		this.HostElement.innerHTML = this.GetTitle();
		return this.base.Update();
	}]
	,onClick: function(e){
		do_Browse();
		e.returnValue = false;
		return false;
	}
});
//----------------------------------------------- Newslettres controls ------------------------------------------------------------//
var NewslettersModuleControl = null;
DeclareClass("SiteLayout.NewslettersModuleControl", "UI.Controls.WorkspaceModuleControl",
{	
	constructor: function(ctlType) {
		this.base(ctlType);
		this.__dataset = null;		
		this.__datasetArchiveEmail = null;
		this.__dataSourceName = "NewslettersItemDS";
		this.__dataSourceNameArchive = "NewslettersItemArchiveEmailDS";
		this.__events = [];		
		this.__xPath =	/*00*/	[{"NewslettersItem":"Title",  "XPath":"//~0".format(P_NEWSLETTERS_TITLE)},
						/*01*/	{"NewslettersItem":"Frequency",  "XPath":"//~0".format(P_NEWSLETTERS_FREQUENCY)},
						/*02*/	{"NewslettersItem":"EmailAddress",  "XPath":"//~0".format(P_NEWSLETTERS_EMAIL_ADDR)},
						/*03*/	{"NewslettersItem":"Feeds",  "XPath":"//~0".format(P_NEWSLETTERS_FEEDS)},
						/*04*/	{"NewslettersItem":"NewslettersID",  "XPath":"//~0".format(P_NEWSLETTERS_ID)},
						/*05*/	{"NewslettersItem":"PreviewDate",  "XPath":"//~0".format(P_NEWSLETTERS_SEND_PREVIEW_TIME)},
						/*06*/	{"NewslettersItem":"Item",  "XPath":"//~0".format(P_NEWSLETTERS_PARAM_ITEM)},
						/*07*/	{"NewslettersArchiveEmailCollection":"Item",  "XPath":"//~0".format(P_NEWSLETTERS_ARCHIVE_EMAIL_COLLECTION)},
						/*08*/	{"NewslettersArchiveEmail":"Email",  "XPath":"~0".format(P_NEWSLETTERS_ARCHIVE_EMAIL_ITEM_EMAIL)},
						/*09*/	{"NewslettersArchiveID":"ID",  "XPath":"~0".format(P_NEWSLETTERS_ARCHIVE_EMAIL_ITEM_ID)},
						/*10*/	{"NewslettersComment":"Comment",  "XPath":"//~0".format(P_NEWSLETTERS_COMMENT)},
						/*11*/	{"NewslettersSSComment":"Comment",  "XPath":"//~0".format(P_NEWSLETTERS_SEARCH_COMMENT)},
						/*12*/	{"NewslettersSSComment":"RssId",  "XPath":"//~0".format(P_NEWSLETTERS_RSS_ID)},
						/*13*/	{"NewslettersSSComment":"IsRssEnable",  "XPath":"//~0".format(P_NEWSLETTERS_RSS_IS_ENABLE)}];
		this.__logoHostControl = null;
		this.__callbackUpdate = null;
		this.__ARCHIVE_ITEMS_PERPAGE = parseInt(P_NEWSLETTERS_ARCHIVE_ITEMS_PER_PAGE);		
		this.__DEF_VALUE =  "Loading...";
		this.__selectedArchiveEmail = [];
	}	
	,LoadItemDS : function(id) {	
		if(id!=null && parseInt(id)>0)
		{
			new httpcmd_NewslettersGet(id, this.CreateCallback(this.OnLoadItemDS), this.CreateCallback(this.OnError));
	}
	}
	,LoadItemArchiveEmailDS : function(id) {	
		if(id!=null && parseInt(id)>=0)
		{
			this.__selectedArchiveEmail = [];
			new httpcmd_NewslettersArchiveEmailGet(id, this.CreateCallback(this.OnLoadItemArchiveEmailDS), this.CreateCallback(this.OnError));
		}
	}	
	,UpdateItemDS : function(callback) {	
		this.__callbackUpdate = null;
		
		if(callback)
			this.__callbackUpdate = callback;
		if(this.__dataset!=null && this.__dataset.length>0)
			new httpcmd_NewslettersUpdate(this.__dataset, this.CreateCallback(this.OnUpdateItemDSComplete), this.CreateCallback(this.OnError));
	}	
	,OnUpdateItemDSComplete : function(xml) {	
		if(xml)
			this.__dataset = xml;
		if(this.__callbackUpdate)
			(this.__callbackUpdate)();
	}		
	,OnLoadItemDS : function(xml) {		
		if(xml!=null && xml.length && xml.length>0)
		{		
			this.__dataset = xml;		
			this.PulseEvent(NS_EVENTS.OnLoadDS, this.__dataset);
		}			
	}		
	,OnLoadItemArchiveEmailDS : function(xml) {		
		this.__datasetArchiveEmail = xml;		
		this.PulseEvent(NS_EVENTS.OnLoadArchiveEmailDS, this.__datasetArchiveEmail);
	}			
	,OnError : function(xml) {
		if(xml)
			alert("Error in SiteLayout.NewslettersModuleControl.UpdateItemDS(). xml=" + xml);
	}		
	,AttachEvent : function(eventName, callback) {	
		if (eventName.length>0 && callback!=null)
			this.__events.push([eventName, callback]);
	}
	,PulseEvent : function(eventName, args) {	
		if(args.indexOf("ERROR")>0) return;
		if(this.__events && eventName && eventName.length>0)
			for(var counter=0; counter<this.__events.length; counter++)
				if(this.__events[counter][0] == eventName)
					this.__events[counter][1](args);		
	}	
});
NewslettersModuleControl = new SiteLayout.NewslettersModuleControl();

DeclareClass("SiteLayout.NewslettersGridContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__grid = null;
		this.__link = null;
		this.__archive = null;
		this.__dataset = null;
		this.__processCreateData = null;
		this.__dataSourceName = "NewslettersDS";
		this.__xmlNodeAccessor = null;		
		this.ondsregid;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		this.Listeners.AddObjectListener(this, "onvisiblechange", this.ClearAll);				
		this.__link = new UI.Controls.ScriptLink("Create A New Newsletter", this.CreateCallback(this.CreateNewsletter))
		this.__archive = new UI.Controls.ScriptLink("Newsletter Archive", this.CreateCallback(this.Archive))
		this.AddControl(this.__link);		
		this.AddControl(this.__archive);
	}]
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		this.__processCreateData = data;
		this.base.ProcessCreateData(data);
		if (data != null)		
		{	
			var gridData = data.selectSingleNode("NewslettersGrid");
			if (gridData)
			{
				this.__grid = UI.Control.LoadControlTemplate(gridData);
				this.AddControl(this.__grid);
			}			
		}
	}]
	,Render :[decl_virtual, function(writer)
	{
		var rows = []; 
		var td = new UI.DOMControls.Td();
		if (this.__grid)
			this.__grid.RenderControl(td.Obj());
		rows.push(new UI.DOMControls.Tr(td));
		
		td = new UI.DOMControls.Td();
		td.Obj().innerHTML = "&nbsp;";
		td.SetCssClass("b04 pl10 pf_pg_std_ns");
		rows.push(new UI.DOMControls.Tr(td));		
		td = new UI.DOMControls.Td();
		td.SetCssClass("b04 pl10 pf_pg_std_ns");
		td.Obj().innerHTML = "&nbsp;";
		rows.push(new UI.DOMControls.Tr(td));
				
		td = new UI.DOMControls.Td();
		td.SetCssClass("b04 pl2 pf_pg_std_ns_left");
		this.__link.RenderControl(td.Obj());
		this.__archive.RenderControl(td.Obj());
		this.__archive.GetHostObject().style.marginLeft = "45px";
		rows.push(new UI.DOMControls.Tr(td));				
		
		var tbl = new UI.DOMControls.Table(rows);
		tbl.SetCssClass("pf_pg_tbl_ns");
		this.HostElement.appendChild(tbl.Obj());		
		
		// process startup URL parameters
		if(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE)>0)
		{
			var id = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
			var mode = nav_currentNavInfo.GetParameter(P_MODE);
			if(mode.toLowerCase()=="edit"||mode.toLowerCase()=="publish")
				SiteLayout.NewslettersGridContainer.CheckUserRights(id, mode);
		}	
		
		// attach to DataSet event		
		if (this.GetDataset() == null)
		{
			this.ondsregid = data_attachEvent("ondatasetregistered", this.CreateCallback(this.OnDataSetRegistered) );
			evnt_SubscribeOnEvent(EVT_REFRESH_MODULES, this.CreateCallback(this.OnRefreshWorkspaceModules));
		}
		
	}]
	,OnRefreshWorkspaceModules : function(keywords)
	{
		if (keywords != KEY_NEWSLETTERS)
			return;			
		var mode = nav_currentNavInfo.GetParameter(P_MODE);
		if(mode=="new")
			new httpcmd_NewslettersFirstGet(this.CreateCallback(this.OnLoadNewslettersList));			
		var nsId = parseInt(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE));
		if(mode=="delete" && nsId!=NaN && nsId>0)		
			this.SetActive(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE));
	}			
	,OnLoadNewslettersList : function(xml)
	{	
		data_SetDatasetData(this.__dataSourceName, xml);
		var oID = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
		this.SetActive(oID);
	}		
	,OnDataSetRegistered : function(xDs)
	{
		if (this.__dataSourceName != xDs.name)
			return;
		data_detachEvent("ondatasetregistered",  this.ondsregid);
		this.HighlightOnLoad();	
	}	
	,SetActive : function(id)
	{	
		var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();
		var dsName = isHeadlinesView ? "Subscriptions.Latest" : "Subscriptions.LatestS";	
		data_DropDatasetSelections(dsName);
		data_DataStoreCollection.ClearSelectedItemsForEmailing();
		data_MarkItemSelected(this.__dataSourceName, id, true,true,false,false,event);
	}	
	,HighlightOnLoad : function()
	{	
		//support selectable grid
		this.GetDataset().attachEvent("onitemchange", this.CreateCallback(this.OnItemSelected));
	
		//select grid item on first load
		var oID = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
		if(oID) this.SetActive(oID);
	}		
	,OnItemSelected : function(xItem)
	{		
		if(!xItem)
			return;			
			
		// Prevernt multiple loading. User click on NS name - skip event.
		try {if(window.event.srcElement.innerHTML.toUpperCase().indexOf("SPAN")<0) return;}catch(e) {}
		
		var urlID = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);		
		var currMode = nav_currentNavInfo.GetParameter(P_MODE);		
		if(xItem.GetItemID()!=urlID || currMode=="archive")
			SiteLayout.NewslettersGridContainer.SetCurrentNewsletters(xItem.GetItemID(), null, "edit");
	}		
	,ClearAll : function()
	{
		var dataset = this.GetDataset();
		if (dataset)
			dataset.LoadData(dataset.GetXml());
	}	
	,CreateNewsletter : function()
	{
		cmd = new httpcmd_NewslettersCreate(-1, this.CreateCallback(this.OnCreateNewsletter));
	}
	,Archive : function()
	{
		data_DropDatasetSelections(this.__dataSourceName);		
		var query = nav_GetNavigationQuery();
		query = url_ReplaceQueryStringParam(query, P_MODE, "archive");
		nav_ChangePageParams(query);
		
		// refresh pager
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERARCHIVEPAGER);		
	}	
	,OnCreateNewsletter : function(xml)
	{
		if(xml!=null && xml.length>0)
		{
			var ndAccessor =  new Xml.NodeAccessor(xml);
			var objID  = ndAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[4].XPath).text;
			SiteLayout.NewslettersGridContainer.SetCurrentNewsletters(objID, null, "edit");
		}		
	}	
	,GetDataset : function()
	{
		if (this.__dataset == null)
			this.__dataset = data_GetDataset(this.__dataSourceName);
		return this.__dataset;
	}
	,Update :[decl_virtual, function(writer)
	{
		return this.base.Update();
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__grid =null;
		this.__link = null;
		this.__archive = null;
		this.__dataset = null;
	}]
	,SetCurrentNewsletters : [decl_static, function(pid, name, mode)
	{	
		if(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE) != pid || nav_currentNavInfo.GetParameter(P_MODE)=="archive")
			SiteLayout.NewslettersGridContainer.CheckUserRights(pid, mode);
	}]
	,CheckUserRights : [decl_static, function(pid, mode)
	{
		new httpcmd_NewslettersCheckRights(pid, mode, SiteLayout.NewslettersGridContainer.SetCurrentNewsletters_Force, null);
	}]
	,SetCurrentNewsletters_Force : [decl_static, function(pid, mode, xml)
	{	
		// User has not right to view/operate with newsletter
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")>0)
		{
			mode = "delete"; pid = -1;
			alert("You don't have the proper credentials to use this Newsletter or it was deleted");
		}
		// process startup URL parameters
		else if(mode.toLowerCase()=="publish")
			SiteLayout.NewslettersGridContainer.Send_Publish(pid, "");		
		
		// set newsletter id and clear selected saved search
		var query = url_CombineParams(
				url_MakeParam(P_BEDATA_REFERENCE, pid),
				url_MakeParam(P_MODE, mode));
		query = url_CombineParams(query, url_MakeParam(P_NEWSLETTERS_SELECTED_SEARCH, -1));
		nav_ChangePageParams(query);
		
		// clear previosly selected headlines
		var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();
		var dsNameHeadline = isHeadlinesView ? "Subscriptions.Latest" : "Subscriptions.LatestS";	
		data_DropDatasetSelections(dsNameHeadline);
		data_DataStoreCollection.ClearSelectedItemsForEmailing();				
		
		// load DS
		if(pid == -1)
			nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);
		else		
		NewslettersModuleControl.LoadItemDS(pid);					
	}]	
	,Send_Preview : [decl_static, function(pid, name)
	{
		cmd = new httpcmd_NewslettersSend(pid, SiteLayout.NewslettersGridContainer.SendComplete_Preview, "preview");		
	}]	
	,Send_Publish : [decl_static, function(pid, name, mode)
	{	
		cmd = new httpcmd_NewslettersSend(pid, SiteLayout.NewslettersGridContainer.SendComplete_Publish, "publish");		
	}]		
	,SendComplete_Preview : [decl_static, function()
	{
		alert("The newsletter has been queued for processing and may take a number of minutes before being sent.");
	}]		
	,SendComplete_Publish : [decl_static, function(xml)
	{
		if(xml.indexOf("ALREADY_PUBLISHED")>0)
		{
			alert("The newsletter has been already published.");}
		else
		{
			alert("The newsletter has been queued for publishing and may take a number of minutes before being sent.");
			nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);
		}
	}]			
	,CheckDeleteNewsletter : [decl_static, function(id)
	{
		if(window.confirm('Are you sure you want to delete this Newsletter ?'))				
			new httpcmd_RemoveNewsletters(id, null, null);	
	}]
});

DeclareClass("SiteLayout.NewslettersNameContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
		this.__imageDelimiter = null;
		this.__input = null;
		this.__xmlNodeAccessor = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__text = new UI.Controls.Text("Newsletter Title");		
		this.__text.SetCssClass("nsBold");
		this.__imageDelimiter = new UI.Controls.Image("spacer.gif", 1, 10);
		this.__input = new UI.Controls.InputControl("", null);		
		this.__input.SetCssClass("nsInput");
		this.__input.AttachEvent("onblur", this.CreateCallback(this.Rename));
		this.AddControl(this.__text);
		this.AddControl(this.__imageDelimiter);
		this.AddControl(this.__input);

		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetNewslettersName));
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__text)
			this.__text.Dispose();
		this.__text = null;
		
		if (this.__imageDelimiter)
			this.__imageDelimiter.Dispose();
		this.__imageDelimiter = null;
		
		if (this.__input)
			this.__input.Dispose();
		this.__input = null;		
		
		this.__xmlNodeAccessor = null;
	}]
	,SetNewslettersName : function(xml)
	{
		if(xml!=null && xml.length>0)
		{		
			this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
			oName  = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[0].XPath).text;
			oID  = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[4].XPath).text;
			this.__input.SetValue(oName);
		}
	}
	,Rename : function() 
	{
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0)
			return;

		var name = str_Trim( this.__input.GetValue() );
		if ( str_IsStringEmpty(name) )
		{
			alert("Please enter name.");
			if (this.__input.HostElement)
				this.__input.HostElement.focus();
			return;
		}
						
		this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var oOldValue = this.__xmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[0].XPath);
		if(oOldValue != this.__input.GetValue())
		{
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[0].XPath, this.__input.GetValue(), [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();			
			new httpcmd_NewslettersUpdate(NewslettersModuleControl.__dataset, this.CreateCallback(this.OnCompleteRename), this.CreateCallback(this.OnError));
		}
	}	
	,OnError : function(xml) {
		alert("Error in SiteLayout.NewslettersNameContainer object. xml=" + xml);
	}			
	,OnCompleteRename : function()
	{
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);
	}		
});

DeclareClass("SiteLayout.NewslettersFrequencyContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
		this.__imageDelimiter = null;
		this.__frequency = null;
		this.__xmlNodeAccessor = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__text = new UI.Controls.Text("Send Preview");	
		this.__text.SetCssClass("nsFrequency");	
		this.__imageDelimiter = new UI.Controls.Image("spacer.gif", 1, 25);
		this.__frequency = new UI.Controls.DropDown();		
		this.__frequency.AttachEvent("onselected", this.CreateCallback(this.Update));
		this.__frequency.AddItem("Daily", 1);		
		this.__frequency.AddItem("Weekly", 2);
		this.__frequency.AddItem("Manually", 3);
		this.__frequency.SetWidth(150);
		
		this.AddControl(this.__text);
		this.AddControl(this.__imageDelimiter);
		this.AddControl(this.__frequency);
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetNewslettersFrequency));		
		
		this.SetNewslettersFrequency(NewslettersModuleControl.__dataset);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__text)
			this.__text.Dispose();
		this.__text = null;
		
		if (this.__imageDelimiter)
			this.__imageDelimiter.Dispose();
		this.__imageDelimiter = null;
		
		if (this.__frequency)
			this.__frequency.Dispose();
		this.__frequency = null;	
		
		this.__xmlNodeAccessor = null;
	}]
	,SetNewslettersFrequency : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var oFreq = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[1].XPath).text;
			this.__frequency.SetSelectedValue(oFreq);
			oXmlNodeAccessor = null;
		}
	}	
	,Update : function() 
	{
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0 || xml.indexOf("ERROR") > 0)
			return;
						
		this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var oOldValue = this.__xmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[1].XPath);
		if(oOldValue!=this.__frequency.SelectedValue)
		{
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[1].XPath, this.__frequency.SelectedValue, [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();
			new httpcmd_NewslettersUpdate(NewslettersModuleControl.__dataset, this.CreateCallback(this.OnCompleteUpdate), this.CreateCallback(this.OnError));
		}		
	}		
	,OnError : function(xml) {
		alert("Error in SiteLayout.NewslettersFrequencyContainer object. xml=" + xml);
	}			
	,OnCompleteUpdate : function()
	{
	}			
});

DeclareClass("SiteLayout.NewslettersSendingTimeContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
		this.__imageDelimiter = null;
		this.__time = null;
		this.__xmlNodeAccessor = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__text = new UI.Controls.Text("Sending Time");	
		this.__text.SetCssClass("nsFrequency");	
		this.__imageDelimiter = new UI.Controls.Image("spacer.gif", 1, 25);
		this.__time = new UI.Controls.DropDown();		
		this.__time.AttachEvent("onselected", this.CreateCallback(this.Update));		

		var timeArray = Utils.GeneralPreferences.GetTimeFormat().indexOf("tt") > 0 ? NS_SENDING_TIME_12 : NS_SENDING_TIME_24;		
		for(var value in timeArray)		
			if(typeof(timeArray[value])=="string")
				this.__time.AddItem(value, timeArray[value]);		
		this.__time.SetWidth(150);
		
		this.AddControl(this.__text);
		this.AddControl(this.__imageDelimiter);
		this.AddControl(this.__time);
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetTime));		
		
		this.SetTime(NewslettersModuleControl.__dataset);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
	}]
	,SetTime : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var oFreq = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[5].XPath).text;
			this.__time.SetSelectedValue(oFreq);
			oXmlNodeAccessor = null;
		}
	}	
	,Update : function() 
	{
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0 || xml.indexOf("ERROR") > 0)
			return;
						
		this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var oOldValue = this.__xmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[5].XPath);
		if(oOldValue!=this.__time.SelectedValue)
		{
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[5].XPath, this.__time.SelectedValue, [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();
			new httpcmd_NewslettersUpdate(NewslettersModuleControl.__dataset, this.CreateCallback(this.OnCompleteUpdate), this.CreateCallback(this.OnError));
		}		
	}		
	,OnError : function(xml) {
		alert("Error in SiteLayout.NewslettersSendingTimeContainer object. xml=" + xml);
	}			
	,OnCompleteUpdate : function()
	{
	}				
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__text)
			this.__text.Dispose();
		this.__text = null;
		
		if (this.__imageDelimiter)
			this.__imageDelimiter.Dispose();
		this.__imageDelimiter = null;
		
		if (this.__time)
			this.__time.Dispose();
		this.__time = null;	
		
		this.__xmlNodeAccessor = null;
	}]	
});

DeclareClass("SiteLayout.NewslettersRssOutContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.AsyncRenderingEnabled = true;
		this.AsyncControlUpdating = true;
		this.KeywordsAttach(KEY_NEWSLETTERRSSOUT)
		
		this.__TXT_ENABLE_ACTIVE = "Enable";
		this.__TXT_ENABLE_INACTIVE = "Enabled";
		this.__TXT_DISABLE_ACTIVE = "Disable";
		this.__TXT_DISABLE_INACTIVE = "Disabled";
		this.__TXT_RSS_PATH = "Show RSS path";
		
		this.__isRssEnable = "false";
		this.__RssId = "";
		this.__confirmText =  "The RSS Out path has been already generated. Would you like to      \rgenerate a new one? Note, that after generating of the new RSS      \rpath, recipients using the old RSS path will not receive newsletter      \rupdates.\r\tOK - generate new RSS path;\r\tCancel - use existing RSS path";
				
		this.__linkEnable = null;
		this.__linkDisable = null;
		this.__linkPath = null;
		this.__linkEnableHost = null;
		this.__linkDisableHost = null;
		this.__linkPathHost = null;		
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__linkEnable = new UI.Controls.ScriptLink(this.__TXT_ENABLE_ACTIVE, this.CreateCallback(this.EnableClick));
		this.__linkDisable = new UI.Controls.ScriptLink(this.__TXT_DISABLE_ACTIVE, this.CreateCallback(this.DisableClick));
		this.__linkPath = new UI.Controls.ScriptLink(this.__TXT_RSS_PATH, this.CreateCallback(this.PathClick));
		this.AddControl(this.__linkEnable);		
		this.AddControl(this.__linkDisable);
		this.AddControl(this.__linkPath);
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetData));		
	}]
	,Render :[decl_virtual, function(writer)
	{	
		var rows = []; 
		
		// RSS logo
		var imgLogo  = new UI.DOMControls.Image("SearchIcon/icon-search-feed.gif", "");
		var txtLogo = new UI.DOMControls.Text(" RSS Out:");		
		txtLogo.Obj().style.position = "relative";
		txtLogo.Obj().style.posTop = "-3";
		var oTdLogo = new UI.DOMControls.Td(imgLogo, txtLogo);
		oTdLogo.Obj().style.paddingLeft = "10px";
		// Enable
		this.__linkEnableHost = new UI.DOMControls.Td();
		this.__linkEnable.RenderControl(this.__linkEnableHost.Obj());		
		// Disable
		this.__linkDisableHost = new UI.DOMControls.Td();
		this.__linkDisable.RenderControl(this.__linkDisableHost.Obj());		
		// Path
		this.__linkPathHost = new UI.DOMControls.Td();
		this.__linkPath.RenderControl(this.__linkPathHost.Obj());		
		
		rows.push(new UI.DOMControls.Tr(oTdLogo, this.__linkEnableHost, this.__linkDisableHost, this.__linkPathHost));		
		var tbl = new UI.DOMControls.Table(rows);
		tbl.SetCssClass("nsRssOutTable");
		this.HostElement.appendChild(tbl.Obj());		
	}]
	,SetData : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			this.__RssId = oXmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[12].XPath);
			this.__isRssEnable = oXmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[13].XPath)
			oXmlNodeAccessor = null;
			
			if(this.__isRssEnable && this.__isRssEnable=="true")			
				this.EnableClickFormatControls();
			else
				this.DisableClickFormatControls();
		}
	}		
	,SetPath : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			this.__RssId = oXmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[12].XPath);
			oXmlNodeAccessor = null;
		}	
	}
	,EnableClick : function() 
	{	
		if(this.__RssId && this.__RssId.length>0)
		{
			var liveCurrent = confirm(this.__confirmText);
			if(liveCurrent)
				this.__RssId = "";			
		}			
		
		this.__isRssEnable = "true";			
		this.EnableClickFormatControls();
		
		new httpcmd_NewslettersRssSet(
			nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE),
			true,
			this.__RssId,
			this.CreateCallback(this.SetPath), this.CreateCallback(this.OnError)
		);
	}		
	,DisableClick : function() 
	{		
		this.__isRssEnable = "false";
		this.DisableClickFormatControls();
		
		new httpcmd_NewslettersRssSet(
			nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE),
			false,
			this.__RssId,
			this.CreateCallback(this.SetPath), this.CreateCallback(this.OnError)
		);		
	}				
	,EnableClickFormatControls : function() 
	{	
		this.RemoveChildren(this.__linkEnableHost.Obj());
		var oSpanTextEnable = new UI.DOMControls.Text(this.__TXT_ENABLE_INACTIVE);
		oSpanTextEnable.Obj().style.color = "black";
		oSpanTextEnable.Obj().style.fontWeight = "bold";
		this.__linkEnableHost.Obj().appendChild(oSpanTextEnable.Obj());
		
		this.RemoveChildren(this.__linkDisableHost.Obj());
		this.__linkDisableHost.Obj().appendChild(this.__linkDisable.HostElement);		
		
		this.RemoveChildren(this.__linkPathHost.Obj());
		this.__linkPathHost.Obj().appendChild(this.__linkPath.HostElement);		
	}			
	,DisableClickFormatControls : function() 
	{		
		this.RemoveChildren(this.__linkEnableHost.Obj());
		this.__linkEnableHost.Obj().appendChild(this.__linkEnable.HostElement);

		this.RemoveChildren(this.__linkDisableHost.Obj());
		var oSpanTextDisable = new UI.DOMControls.Text(this.__TXT_DISABLE_INACTIVE);
		oSpanTextDisable.Obj().style.color = "black";
		oSpanTextDisable.Obj().style.fontWeight = "bold";
		this.__linkDisableHost.Obj().appendChild(oSpanTextDisable.Obj());
		
		this.RemoveChildren(this.__linkPathHost.Obj());
		var oSpanTextPath = new UI.DOMControls.Text(this.__TXT_RSS_PATH);
		oSpanTextPath.Obj().style.color = "gray";
		this.__linkPathHost.Obj().appendChild(oSpanTextPath.Obj());		
	}				
	,PathClick : function() 
	{	
		
		var param = url_MakeParam(P_NEWSLETTERS_ID, nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE));
		nav_openPopupEx(PID_NEWSLETTERVIEWRSS, param, 613, 160, false, false );	
	}				
	,RemoveChildren : function(obj)
	{
		if(obj && obj.children && obj.children.length > 0)
			while(obj.children.length>0)
				obj.removeChild(obj.children[0]);
	
	}
	,OnError : function(xml) 
	{
	}
	,GetSpan : function(text, style)
	{
		var oSpan = new UI.DOMControls.Text(text);
		oSpan.Obj()
	}
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if(this.__linkEnable)
			this.__linkEnable.Dispose();
		if(this.__linkDisable)
			this.__linkDisable.Dispose();
		if(this.__linkPath)
			this.__linkPath.Dispose();
	}]	
});


DeclareClass("SiteLayout.NewslettersCommentContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
		this.__textBox = null;
		this.__imageDelimiter = null;
		this.__xmlNodeAccessor = null;
		this.__OLD_VALUE = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__text = new UI.Controls.Text("Newsletter Comment");	
		this.__text.SetCssClass("nsFrequency");	
		this.__imageDelimiter = new UI.Controls.Image("spacer.gif", 1, 25);
		this.__textBox = new UI.Controls.TextArea("100%", "50px");		
		this.__textBox.SetValue(NewslettersModuleControl.__DEF_VALUE);
		this.Listeners.AddObjectListener(this.__textBox, "onblur", this.OnBlur);
		this.Listeners.AddObjectListener(this.__textBox, "onkeydown", this.OnKeyDown);
		
		this.AddControl(this.__text);
		this.AddControl(this.__imageDelimiter);
		this.AddControl(this.__textBox);
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetText));		
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
	}]
	,CheckLength : function()
	{
		var tbValue = this.__textBox.GetValue();
		if(tbValue && tbValue.length>parseInt(P_NEWSLETTERS_COMMENT_LENGTH))
			this.__textBox.SetValue(tbValue.substr(0, P_NEWSLETTERS_COMMENT_LENGTH));
	}
	,SetText : function(xml)
	{
		var oTextValue = "";
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var oText = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[10].XPath)
			if(oText)
				oTextValue = oText.text;
			oXmlNodeAccessor = null;
		}
		this.__OLD_VALUE = oTextValue;
		this.__textBox.SetValue(oTextValue);
	}	
	,OnBlur : function() 
	{	
		this.CheckLength();	
		
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0 || xml.indexOf("ERROR") > 0)
			return;
		this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var tbValue = this.__textBox.GetValue();
		if(this.__OLD_VALUE !=null && tbValue!=this.__OLD_VALUE)
		{		
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[10].XPath, this.__textBox.GetValue(), [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();			
			new httpcmd_NewslettersUpdate(NewslettersModuleControl.__dataset, null, this.CreateCallback(this.OnError));		
		}
	}		
	,OnKeyDown : function() 
	{		
		this.CheckLength();	
	}			
	,OnError : function(xml) 
	{
	}			
	,OnCompleteUpdate : function()
	{
	}				
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__text)
			this.__text.Dispose();
		this.__text = null;
		
		if (this.__imageDelimiter)
			this.__imageDelimiter.Dispose();
		this.__imageDelimiter = null;
		
		if (this.__textBox)
			this.__textBox.Dispose();
		this.__textBox = null;	
		
		this.__xmlNodeAccessor = null;
	}]	
});

DeclareClass("SiteLayout.NewslettersEmailTitleContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
		var rows = []; 
		var oText = new UI.DOMControls.Text("E-Mail Address");		
		var td1 = new UI.DOMControls.Td(oText);
		var td2 = new UI.DOMControls.Td(new UI.DOMControls.Text("Remove from list"));
		td2.SetAttribute("align", "right")
		var tr = new UI.DOMControls.Tr(td1, td2)
		tr.SetCssClass("nsEmailAddresssTitle");
		rows.push(tr);		
		
		var tbl = new UI.DOMControls.Table(rows);
		this.HostElement.appendChild(tbl.Obj());		
	}]
	,Dispose :[decl_virtual, function()
	{
	}]
});

DeclareClass("SiteLayout.NewslettersEmailDataContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__emails = [];		
		this.__input = null;
		this.__panel = null;
		this.__xmlNodeAccessor = null;
		this.__table = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__input = new UI.Controls.InputControl("", null);				
		this.__panel = new UI.DOMControls.Div(new UI.DOMControls.LiteralControl("&nbsp;"));
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetEmailAddress));		
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();		
		this.HostElement.style.height = "100%";
		this.__panel.SetCssClass("nsEmailArea");
		this.HostElement.appendChild(this.__panel.Obj());
		
		// add email
		var rows = [];
		var oTextAdd = new UI.DOMControls.Text("Add E-Mail");
		var oTdAdd = new UI.DOMControls.Td(oTextAdd);
		oTdAdd.SetColSpan(2);
		rows.push(new UI.DOMControls.Tr(oTdAdd));		
		
		var oTdInput = new UI.DOMControls.Td(this.__input.domObj);
		oTdInput.SetAttribute("width", "40%");
		var oTdBtn = new UI.DOMControls.Td(new UI.DOMControls.Button("Add", this.CreateCallback(this.AddEmail)));
		oTdInput.SetCssClass("nsRecipienceInput");		
		rows.push(new UI.DOMControls.Tr(oTdInput, oTdBtn));		
		
		var tbl = new UI.DOMControls.Table(rows);
		this.HostElement.appendChild(tbl.Obj());		
	}]
	,AddEmail : function()
	{
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0)
			return;
			
		this.__xmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var oOldValue = this.__xmlNodeAccessor.GetNodeValue(NewslettersModuleControl.__xPath[2].XPath);			

		var name = str_Trim( this.__input.GetValue() );
		if ( str_IsStringEmpty(name) )
		{
			alert("Please enter name.");
			return;
		}
		else if(!vld_IsEmailValid(name))
		{
			alert("Please enter correct email address.");
			return;
		}		
		else if((new RegExp(name)).test(oOldValue))
		{
			alert("This email address already added.");
			return;
		}
		else
		{
			var emailPart = name.split("@");
			if(emailPart.length==2 && (emailPart[0].length>64 || emailPart[0].length>255))
			{
				alert("Email address to long.");
				return;			
			}			
		}		
		
		// save
		oNewValue = (oOldValue==null) ? "0:"+name : oOldValue.text + ",0:"+name;
		this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[2].XPath, oNewValue, [{"name":"IsNew", "value":"true"}]);
		NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();
		NewslettersModuleControl.UpdateItemDS(this.CreateCallback(this.OnAddEmailComplete));
		this.__input.SetValue("");
	}	
	,OnAddEmailComplete : function()
	{		
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);
		this.SetEmailAddress(NewslettersModuleControl.__dataset);
	}
	,DeleteEmail : function(e)
	{
		if(!e && !e.srcElement)
			return;		
		if(!confirm('Are you sure you want to delete this E-Mail?'))
			return;
		oID = e.srcElement.getAttribute(P_NEWSLETTERS_ID+"_Z");
		oEmail = e.srcElement.getAttribute(P_NEWSLETTERS_EMAIL_ADDR);
		
		if(oID!=null && oID.length>0 && oEmail!=null && oEmail.length>0)
		{
			this.__xmlNodeAccessor = new Xml.NodeAccessor(NewslettersModuleControl.__dataset);
			oOldValue = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[2].XPath).text;
			oNewValue = oOldValue.replace(new RegExp(oID+"\:"+oEmail,"ig"), "-"+oID+":"+oEmail);
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[2].XPath, oNewValue, [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();
			NewslettersModuleControl.UpdateItemDS(this.CreateCallback(this.OnDeleteEmailComplete));
		}
	}
	,OnDeleteEmailComplete : function()
	{
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);
		this.SetEmailAddress(NewslettersModuleControl.__dataset);
	}	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		
		if (this.__input)
			this.__input.Dispose();
		this.__input = null;	
		
		this.__xmlNodeAccessor = null;					
	}]
	,SetEmailAddress : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("EROOR")<=0)
		{		
			// parse
			this.__emails = [];		
			this.__xmlNodeAccessor = new Xml.NodeAccessor(xml);
			var oNode = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[2].XPath);
			if(oNode==null)
				return;				
			
			oNode.text = oNode.text.replace(/^\s+|\s+$/g,"");
			if(oNode.text!=null && oNode.text.length>0)
			{
				arrEmail = oNode.text.split(",");
				for(i=0; i<arrEmail.length; i++)
				{
					if(arrEmail[i]!=null && arrEmail[i].length>0)
					{
						// Bad in case of 123@mail.ru
						oEmail = {"ID":arrEmail[i].split(":")[0],
								"Address":arrEmail[i].split(":")[1]};
						this.__emails.push(oEmail);
					}								
				}				
			}			
						
			// set values
			var rows = []; 
			for(i1=0; i1<this.__emails.length; i1++)
			{					
				var oDelImg  = new UI.DOMControls.Image("action-delete.png", "");
				oDelImg.SetAttribute(P_NEWSLETTERS_ID+"_Z", this.__emails[i1].ID);
				oDelImg.SetAttribute(P_NEWSLETTERS_EMAIL_ADDR, this.__emails[i1].Address);
				oDelImg.AttachEvent("click", this.CreateCallback(this.DeleteEmail));
				oText = new UI.DOMControls.Text(this.__emails[i1].Address);
				oTdText = new UI.DOMControls.Td(oText);
				oTdDelLink = new UI.DOMControls.Td(oDelImg);
				rows.push(new UI.DOMControls.Tr(oTdText, oTdDelLink));		
			}		
			oTdEmpty = new UI.DOMControls.Td(new UI.DOMControls.Text(""));
			oTdEmpty.SetColSpan(2);
			oTdEmpty.SetCssClass("nsEmpty");
			rows.push(new UI.DOMControls.Tr(oTdEmpty));
			var tbl = new UI.DOMControls.Table(rows);
			
			while(this.__panel.Obj().hasChildNodes())
				this.__panel.Obj().removeChild(this.__panel.Obj().firstChild);
			this.__panel.Obj().appendChild(tbl.Obj());
		}
	}		
});

DeclareClass("SiteLayout.NewslettersSavedSearchContainer", "UI.Control",
{		
	constructor: function()
	{
		this.__HIGHLIGHT = "ffffcc";
		this.__HIGHLIGHT_FF = "rgb(225, 228, 204)";
		this.__ACTIVE = "e4e4e4";
		this.__ACTIVE_FF = "rgb(228, 228, 228)";
		this.base();
		this.__feeds = [];		
		this.__panel = null;
		this.__panelEasyAccess = [];
		this.__active = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__panel = new UI.DOMControls.Div(new UI.DOMControls.LiteralControl("&nbsp;"));
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(this.SetFeeds)); 
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
		this.__panel.SetCssClass("nsFeedArea");
		this.HostElement.appendChild(this.__panel.Obj());		
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
	}]
	,SetFeeds : function(xml)
	{
		if(xml!=null && xml.length>0 && xml.indexOf("EROOR")<=0)
		{		
			// parse
			this.__feeds = [];		
			this.__panelEasyAccess = [];
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var oText = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[3].XPath).text;
			if(oText!=null && oText.length>0)
			{
				var arrFeeds = oText.split(",,,");
				for(var i=0; i<arrFeeds.length; i++)
				{
					if(arrFeeds[i]!=null && arrFeeds[i].length>0)
					{
						var oFeed = {"ID":(arrFeeds[i].split(":")[0]),
								 "Enable":(arrFeeds[i].split(":")[1]),
								 "Name":(arrFeeds[i].split(":")[2])}
						this.__feeds.push(oFeed);
					}								
				}
			}
			oXmlNodeAccessor = null;
			
			// set values
			var rows = []; 
			if(this.__feeds!=null)
			{
				for(var x=0; x<this.__feeds.length; x++)
				{
					var oStatus  = new UI.DOMControls.Image(parseInt(this.__feeds[x].Enable)>0 ? "status-on.gif" : "status-off.gif","");
					oStatus.AttachEvent("click", this.CreateCallback(this.RevertFeed));
					oStatus.SetCssClass("nsStatus");										
					var oTdStatus = new UI.DOMControls.Td(oStatus);
					oTdStatus.SetCssClass("nsSSWidth");
					oTdStatus.SetAttribute("align", "middle");
					var oSearch = new UI.DOMControls.Text(this.__feeds[x].Name);					
					var oTdSearch = new UI.DOMControls.Td(oSearch);	
					oTdSearch.AttachEvent("click", this.CreateCallback(this.SetActive));					
					var oTr = new UI.DOMControls.Tr(oTdStatus, oTdSearch);										
					oTr.SetAttribute(P_NEWSLETTERS_ID+"_Z", this.__feeds[x].ID);
					oTr.SetAttribute(P_NEWSLETTERS_ITEM, this.__feeds[x].Enable);
					oTr.SetAttribute(P_NEWSLETTERS_FEEDS, this.__feeds[x].Name);					
					oTr.AttachEvent("mouseout", this.CreateCallback(this.MouseOut));
					oTr.AttachEvent("mouseover", this.CreateCallback(this.MouseOver));
					rows.push(oTr);										
					this.__panelEasyAccess.push({"oStatus":oStatus, "oTdStatus":oTdStatus, "oTr":oTr});
				}		
				var tbl = new UI.DOMControls.Table(rows);
				
				while(this.__panel.Obj().hasChildNodes())
					this.__panel.Obj().removeChild(this.__panel.Obj().firstChild);
				this.__panel.Obj().appendChild(tbl.Obj());				
			}
		}	
		
		//set active
		this.SetActive(null);
	}
	,RevertFeed : function(e)
	{
		if(!e && !e.srcElement)
			return;		
		var oTR = this.FindTR(e.srcElement);			
		var oID = oTR.attributes[P_NEWSLETTERS_ID+"_Z"].value;
		var oStatus = oTR.attributes[P_NEWSLETTERS_ITEM].value;
		var oName = oTR.attributes[P_NEWSLETTERS_FEEDS].value;
		
		if(oID!=null && oID.length>0 
			&& oStatus!=null && oStatus.length>0
			&& oName!=null && oName.length>0)
		{
			this.__xmlNodeAccessor = new Xml.NodeAccessor(NewslettersModuleControl.__dataset);
			var oPtSt = (oStatus == "0") ? "1" : "0";
			oName = oName.replace(/\+/ig, "\\+");
			oName = oName.replace(/\./ig, "\\.");
			oName = oName.replace(/\*/ig, "\\*");
			oName = oName.replace(/\?/ig, "\\?");
			oName = oName.replace(/\|/ig, "\\|");
			oName = oName.replace(/\(/ig, "\\(");
			oName = oName.replace(/\)/ig, "\\)");
			oName = oName.replace(/\{/ig, "\\{");
			oName = oName.replace(/\}/ig, "\\}");
			oName = oName.replace(/\[/ig, "\\[");
			oName = oName.replace(/\]/ig, "\\]");
			oName = oName.replace(/\,/ig, "\\,");
			var oOldValue = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[3].XPath).text;
			var oNewValue = oOldValue.replace(new RegExp(oID+"\:"+oStatus+"\:"+oName,"ig"), oID+"\:"+oPtSt+"\:"+oName);
			this.__xmlNodeAccessor.SetNodeValue(NewslettersModuleControl.__xPath[3].XPath, oNewValue, [{"name":"IsNew", "value":"true"}]);
			NewslettersModuleControl.__dataset = this.__xmlNodeAccessor.GetXml();			
			NewslettersModuleControl.UpdateItemDS(this.CreateCallback(this.OnRevertFeedComlete));
		}
	}	
	,OnRevertFeedComlete : function()
	{
		this.SetFeeds(NewslettersModuleControl.__dataset);	
		
		// Refresh grid. Disable preview link if there are not selected searches.
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERS);		
	}
	,SetActive : function(e)
	{
		if(!this.__feeds 
			|| this.__feeds.length<=0
			|| !this.__panelEasyAccess)	
			return;
		
		// capture ID from event
		if(e && e.srcElement )
		{
			var oTR = this.FindTR(e.srcElement);			
			this.__active = oTR.getAttribute(P_NEWSLETTERS_ID+"_Z");	
		}
		// capture ID from url
		else 
		{		
			var urlID = -1;
			try { urlID = parseInt(nav_currentNavInfo.GetParameter(P_NEWSLETTERS_SELECTED_SEARCH)) } catch(e) {}
			
			// if urlID=-1 takes ID from first SS otherwise use current
			if(isNaN(urlID) || urlID<0 || this.__active==null)
				this.__active = this.__feeds[0].ID;
		}
				
		var ssID = null;
		var ssName = null;
		var nsTitle = null;
		var query = nav_GetNavigationQuery();
		for(var x=0; x<this.__panelEasyAccess.length; x++)
			if(this.__panelEasyAccess[x].oTr.attributes[P_NEWSLETTERS_ID+"_Z"] == this.__active)
			{
				ssID = this.__panelEasyAccess[x].oTr.attributes[P_NEWSLETTERS_ID+"_Z"];
				ssName = this.__panelEasyAccess[x].oTr.attributes[P_NEWSLETTERS_FEEDS];				
				var oXmlNodeAccessor =  new Xml.NodeAccessor(NewslettersModuleControl.__dataset);
				nsTitle = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[0].XPath).text;
				
				// clear selection and hide headlines
				if(this.__panelEasyAccess[x].oTr.Obj().style.backgroundColor.search(this.__ACTIVE)>=0)
				{
					this.__panelEasyAccess[x].oTr.Obj().style.backgroundColor = "white";	
					query = url_ReplaceQueryStringParam(query, P_MODE, "edit");
					query = url_ReplaceQueryStringParam(query, P_NEWSLETTERS_SELECTED_SEARCH, "");
				}
				// set selected and show headlines
				else
				{
					this.__panelEasyAccess[x].oTr.Obj().style.backgroundColor = this.__ACTIVE;
					query = url_ReplaceQueryStringParam(query, P_MODE, "headlines");
					query = url_ReplaceQueryStringParam(query, P_NEWSLETTERS_SELECTED_SEARCH, ssID);
				}
				nav_ChangePageParams(query);
				//[AL] - disable because reload all controls
				//nav_UpdateCurrentNavigation();				
			}
			else
				this.__panelEasyAccess[x].oTr.Obj().style.backgroundColor = "white";	
				
		// update navigation & pulse event.		
		NewslettersModuleControl.PulseEvent(NS_EVENTS.OnHeadlinesRefresh, [ssID, ssName, nsTitle]);
	}
	,MouseOut : function(e)	
	{
		var oTR = this.FindTR(e.srcElement);
		if(!oTR) return;
	
		// Support FF
		if(oTR.style.backgroundColor.indexOf(this.__ACTIVE)<0
			&& oTR.style.backgroundColor.indexOf(this.__ACTIVE_FF)<0)
			oTR.style.backgroundColor = "white";
	}
	,MouseOver : function(e)
	{
		var oTR = this.FindTR(e.srcElement);
		if(!oTR) return;	
		
		// Support FF
		if(oTR.style.backgroundColor.indexOf(this.__ACTIVE)<0
			&& oTR.style.backgroundColor.indexOf(this.__ACTIVE_FF)<0)
			oTR.style.backgroundColor = this.__HIGHLIGHT;			
	}		
	,FindTR : function(startElem)
	{
		if(startElem.tagName
			&& startElem.tagName.toUpperCase()=="TR")
			return startElem;
		else if(startElem.parentNode)
			return this.FindTR(startElem.parentNode);
			
		return null;
	}	
});

DeclareClass("SiteLayout.NewslettersSavedSearchCommentContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
		this.__textBox = null;
		this.__imageDelimiter = null;
		this.__NS_ID = 0;
		this.__SS_ID = 0;
		this.__OLD_VALUE = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		this.__text = new UI.Controls.Text("Saved Search Comment");	
		this.__text.SetCssClass("nsSSComment");	
		this.__imageDelimiter = new UI.Controls.Image("spacer.gif", 1, 25);
		this.__textBox = new UI.Controls.TextArea("100%", "50px");		
		this.__textBox.SetValue(NewslettersModuleControl.__DEF_VALUE);
		this.Listeners.AddObjectListener(this.__textBox, "onblur", this.OnBlur);
		this.Listeners.AddObjectListener(this.__textBox, "onkeydown", this.OnKeyDown);
		
		this.AddControl(this.__text);
		this.AddControl(this.__imageDelimiter);
		this.AddControl(this.__textBox);
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnHeadlinesRefresh, this.CreateCallback(this.OnLoadComment));		
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
	}]
	,CheckLength : function()
	{
		var tbValue = this.__textBox.GetValue();
		if(tbValue && tbValue.length>parseInt(P_NEWSLETTERS_COMMENT_LENGTH))
			this.__textBox.SetValue(tbValue.substr(0, P_NEWSLETTERS_COMMENT_LENGTH));
	}
	,OnKeyDown : function() 
	{		
		this.CheckLength();	
	}					
	,OnLoadComment : function(data)
	{
		if(data && data.length==3 )
		{
			this.__NS_ID = nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
			this.__SS_ID = data[0];
			new httpcmd_NewslettersSSCommentGet(this.__NS_ID, this.__SS_ID, this.CreateCallback(this.SetText), null);
		}
	}		
	,SetText : function(xml)
	{
		var oTextValue = "";
		if(xml!=null && xml.length>0 && xml.indexOf("ERROR")<=0)
		{		
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var oText = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[11].XPath)
			if(oText)
				oTextValue = oText.text;
			oXmlNodeAccessor = null;
			
		}
		this.__OLD_VALUE = oTextValue;
		this.__textBox.SetValue(oTextValue);		
	}	
	,OnBlur : function() 
	{		
		var xml = NewslettersModuleControl.__dataset;
		if(xml==null || xml.length<=0 || xml.indexOf("ERROR") > 0)
			return;
			
		this.CheckLength();
		var tbValue = this.__textBox.GetValue();
		if(this.__OLD_VALUE !=null
			&& tbValue!=this.__OLD_VALUE 
			&& this.__NS_ID>0 
			&& this.__SS_ID>0)
			new httpcmd_NewslettersSSCommentUpdate(this.__NS_ID, this.__SS_ID, tbValue, null, this.CreateCallback(this.OnError));
	}		
	,OnError : function(xml) {
	}			
	,OnCompleteUpdate : function()
	{
	}				
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__text)
			this.__text.Dispose();
		this.__text = null;
		
		if (this.__imageDelimiter)
			this.__imageDelimiter.Dispose();
		this.__imageDelimiter = null;
		
		if (this.__textBox)
			this.__textBox.Dispose();
		this.__textBox = null;			
	}]	
});


DeclareClass("SiteLayout.NewslettersLogoContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadDS, this.CreateCallback(SiteLayout.NewslettersLogoContainer.SetNewslettersID));
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();		
		NewslettersModuleControl.__logoHostControl = this.HostElement;
	}]
	,SetNewslettersID : [decl_static, function(param)
	{		
		if(NewslettersModuleControl!=null 
		&& NewslettersModuleControl.__dataset!=null
		&& NewslettersModuleControl.__dataset.length>0)
		{
			oXmlNodeAccessor =  new Xml.NodeAccessor(NewslettersModuleControl.__dataset);
			oID = oXmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[4].XPath).text;		
			oRnd = Math.floor(Math.random()*99999);
			
			if(NewslettersModuleControl.__logoHostControl != null)
			{
				var isLoad = NewslettersModuleControl.__logoHostControl.getAttribute("IsLoad");
				if(isLoad!=null && isLoad.length>0 && parseInt(isLoad)==oID && param!=null)
					return
				else
					NewslettersModuleControl.__logoHostControl.setAttribute("IsLoad", oID);
			}
		
			var fsInput = document.createElement("INPUT");
			fsInput.type = "file";
			fsInput.name = "fileInput";
			fsInput.id = "fileInput";			
			var fsSubmit = document.createElement("INPUT");
			fsSubmit.type = "submit";
			fsSubmit.value = "Upload";
			fsSubmit.className = "nsSubmitLogo";
			var fsHiddenAction = document.createElement("INPUT");
			fsHiddenAction.type = "hidden";
			fsHiddenAction.name = "actiontype";
			fsHiddenAction.value = "upload_logo_newsletters";			
			var fsHiddenNs = document.createElement("INPUT");
			fsHiddenNs.type = "hidden";
			fsHiddenNs.name = "newsletters_item_xml";
			fsHiddenNs.value = "-1";			
			
			var fsImgLogo = null;
			var fsForm = null;						
			if(BrowserInfo.IsIE()) 
			{
				fsImgLogo = document.createElement("<img src=\"newsletter_logo.aspx\" alt=\"Newsletter Logo\" id=\"imgNewslettersLogo\" />");			
				fsForm = document.createElement("<form action=\"CommandProcessor.aspx?actiontype=upload_logo_newsletters\" enctype=\"multipart/form-data\" method=\"post\" onsubmit=\"return SiteLayout.NewslettersLogoContainer.AddLogo(this, {'onStart' : null, 'onComplete' : null})\">");
			}
			else
			{
				fsImgLogo = document.createElement("IMG");
				fsImgLogo.src = "newsletter_logo.aspx";
				fsImgLogo.alt = "Newsletter Logo";
				fsImgLogo.id = "imgNewslettersLogo";
			
				fsForm = document.createElement("FORM");
				fsForm.action = "CommandProcessor.aspx?actiontype=upload_logo_newsletters";
				fsForm.enctype = "multipart/form-data";
				fsForm.method = "post";
				fsForm.setAttribute("onsubmit", "return SiteLayout.NewslettersLogoContainer.AddLogo(this, {'onStart' : null, 'onComplete' : null})");
			}
			
			fsHiddenNs.value = oID;
			fsImgLogo.src = "newsletter_logo.aspx?nsid="+oID+"&rnd="+oRnd;
			
			fsForm.appendChild(fsInput);
			fsForm.appendChild(fsHiddenAction);
			fsForm.appendChild(fsHiddenNs);
			fsForm.appendChild(fsSubmit);		
		
			var rows = []; 			
			oTdLblBrnd = new UI.DOMControls.Td(new UI.DOMControls.Text("Newsletter Branding"));
			oTdLblBrnd.SetCssClass("nsBold");
			oTdLblBrnd.SetColSpan(2)		
			rows.push(new UI.DOMControls.Tr(oTdLblBrnd));
			
			oTdInp = new UI.DOMControls.Td();
			oTdInp.SetColSpan(2)		
			oTdInp.Obj().appendChild(fsForm);
			rows.push(new UI.DOMControls.Tr(oTdInp));			
			
			oTdLblFile = new UI.DOMControls.Td(new UI.DOMControls.Text("Branding Logo:"));
			oTdLblFile.SetColSpan(2)		
			rows.push(new UI.DOMControls.Tr(oTdLblFile));
			
			oTdLogo = new UI.DOMControls.Td();
			oTdLogo.Obj().className = "nsLogo";
			oTdLogo.Obj().align = "center";
			oTdLogo.Obj().VAlign = "center";			
			oTdLogo.Obj().appendChild(fsImgLogo);
			oTdTxt = new UI.DOMControls.Td(
				new UI.DOMControls.Text("Acceptable file formats are .gif .jpg"), 
				new UI.DOMControls.LiteralControl("<br/>"),
				new UI.DOMControls.Text("Files over 130x65 pixels will be resized."));
			oTdTxt.Obj().className = "nsLogoInfoText";
			oTdTxt.Obj().align = "left";
			oTdTxt.Obj().vAlign = "top";			
			rows.push(new UI.DOMControls.Tr(oTdLogo, oTdTxt));
			
			var tbl = new UI.DOMControls.Table(rows);
			tbl.Obj().id = "table" + oRnd;
			tbl.Obj().name = tbl.Obj().id;
			
			if(NewslettersModuleControl.__logoHostControl!=null)
			{
				if(NewslettersModuleControl.__logoHostControl.children.length > 0)
					NewslettersModuleControl.__logoHostControl.replaceChild(
						tbl.Obj(), 
						NewslettersModuleControl.__logoHostControl.children[0]);
				else				
					NewslettersModuleControl.__logoHostControl.appendChild(tbl.Obj());				
			}
		}
	}]		
	,AddLogo : [decl_static, function(f, c){	
		// set frame
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="SiteLayout.NewslettersLogoContainer.AddLogoLoaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
	
		// set target
		f.setAttribute('target', n);

		// on start			
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	}]
	,AddLogoLoaded : [decl_static, function(id)
	{	
		SiteLayout.NewslettersLogoContainer.SetNewslettersID();

		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}					
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
	}]
});

DeclareClass("SiteLayout.NewslettersHeadlineTitle", "UI.Control",
{		
	constructor: function()
	{
		this.__label = null;
		this.base();
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnHeadlinesRefresh, this.CreateCallback(this.OnRefresh));
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
		var rows = []; 
		this.__label = new UI.DOMControls.Text("");		
		var oTd = new UI.DOMControls.Td(this.__label);
		oTd.SetAttribute("align", "left")
		oTd.SetCssClass("nsHeadlinesTitle");
		var tr = new UI.DOMControls.Tr(oTd)
		rows.push(tr);		
		
		var tbl = new UI.DOMControls.Table(rows);
		this.HostElement.appendChild(tbl.Obj());		
	}]
	,RefreshMessages :[decl_virtual, function(data)
	{		
		// Refresh headlines grid	
		nav_RefreshWorkspaceModules(KEY_MESSAGES);
	}]
	,OnRefresh :[decl_virtual, function(data)
	{			
		if(data && data.length==3 )
		{
			this.__label.SetText("~0 - ~1 Headlines".format(data[2], data[1]));
			this.RefreshMessages();
		}
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
	}]
});

DeclareClass("SiteLayout.NewslettersHeadlineTitleArchive", "UI.Control",
{		
	constructor: function()
	{
		this.__label = null;
		this.base();
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.base.Render();
		var rows = []; 
		this.__label = new UI.DOMControls.Text("Newsletter Archive");		
		var oTd = new UI.DOMControls.Td(this.__label);
		oTd.SetAttribute("align", "left")
		oTd.SetCssClass("nsHeadlinesTitle");
		var tr = new UI.DOMControls.Tr(oTd)
		rows.push(tr);		
		
		var tbl = new UI.DOMControls.Table(rows);
		this.HostElement.appendChild(tbl.Obj());		
	}]
	,RefreshMessages :[decl_virtual, function(data)
	{		
	}]
	,OnRefresh :[decl_virtual, function(data)
	{			
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
	}]
});

DeclareClass("SiteLayout.NewslettersArchiveFilterByName", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__data = [];
		this.__names = null;
		this.__xmlNodeAccessor = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__names = new UI.Controls.DropDown();		
		this.__names.SetCssClass("ddBlockNS");
		this.__names.SetReadOnly(true);
		this.__names.AttachEvent("onselected", this.CreateCallback(this.OnChange));			
		this.__names.SetWidth(110);
		this.AddControl(this.__names);
		
		if(this.__data==null || this.__data.length<=0)
			new httpcmd_NewslettersGetList(this.CreateCallback(this.LoadNames), this.CreateCallback(this.OnError));			
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.style.verticalAlign = "top";	
			this.HostElement.parentElement.style.paddingTop = "2px";
		}
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
		this.__xmlNodeAccessor = null;					
	}]
	,StoreDataToCookie : function() 
	{		
		tpl_SetCookie(P_NEWSLETTERS_ARCHIVE_GRID_FILTER_BY_NAME, this.__names.SelectedValue, true);	
	}	
	,OnChange : function() 
	{
		data_ClearPagingCookie();
		this.StoreDataToCookie();
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERSARCHIVE);
	}			
	,LoadNames : function(xml)
	{		
		if(xml!=null && xml.length>0 && xml.indexOf("EROOR")<=0)
		{		
			if(!xml)return;
			var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
			var arrNodes = oXmlNodeAccessor.SelectNodes(NewslettersModuleControl.__xPath[6].XPath);
			if (arrNodes == null || arrNodes.length <= 0) return;

			// clear					
			this.__names.Clear();
					
			// add default and data
			this.__names.AddItem("All", "-1");			
			for(var i=0; i<arrNodes.length; i++)
			{
				var nodeDoc = new Xml.NodeAccessor(arrNodes[i].xml);
				var title = nodeDoc.SelectSingleNode(NewslettersModuleControl.__xPath[0].XPath).text;
				var id = nodeDoc.SelectSingleNode(NewslettersModuleControl.__xPath[4].XPath).text;
				this.__names.AddItem(title, id);
			}
			
			// enabled
			this.__names.SetReadOnly(false);
			this.__names.SetSelectedValue("-1", null);
			this.StoreDataToCookie();
		}
	}		
});

DeclareClass("SiteLayout.NewslettersArchiveFilterByDate", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__values = [{"Text":"Last 7 days",		"Value":NS_ARCHIVE_FILTER_BY_DATE.Last7days},
						 {"Text":"Last 2 weeks",	"Value":NS_ARCHIVE_FILTER_BY_DATE.Last2weeks},
						 {"Text":"Last 30 days",	"Value":NS_ARCHIVE_FILTER_BY_DATE.Last30days},
						 {"Text":"Last 60 days",	"Value":NS_ARCHIVE_FILTER_BY_DATE.Last60days},
						 {"Text":"Last 180 days",	"Value":NS_ARCHIVE_FILTER_BY_DATE.Last180days},
						 {"Text":"Last year",		"Value":NS_ARCHIVE_FILTER_BY_DATE.Lastyear}];
		this.__dates = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__dates = new UI.Controls.DropDown();		
		this.__dates.SetCssClass("ddBlockNS");
		for(var i=0; i<this.__values.length; i++)
			this.__dates.AddItem(this.__values[i].Text, this.__values[i].Value);	
		this.__dates.SetSelectedValue(this.__values[0].Value, null);		
		this.__dates.SetWidth(85);
		this.__dates.AttachEvent("onselected", this.CreateCallback(this.OnChange));	
		
		this.AddControl(this.__dates);
		this.StoreDataToCookie();
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.style.verticalAlign = "top";		
			this.HostElement.parentElement.style.paddingTop = "2px";
		}
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
	,StoreDataToCookie : function() 
	{
		tpl_SetCookie(P_NEWSLETTERS_ARCHIVE_GRID_FILTER_BY_DATE, this.__dates.SelectedValue, true);	
	}		
	,OnChange : function() 
	{
		this.StoreDataToCookie();
		data_ClearPagingCookie();
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERSARCHIVE);
	}			
});

DeclareClass("SiteLayout.NewslettersArchiveFilterByCreation", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__creation = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__creation = new UI.Controls.DropDown();		
		this.__creation.SetCssClass("ddBlockNS");		
		this.__creation.AddItem("Earliest first", "0");
		this.__creation.AddItem("Oldest first", "1");
		this.__creation.SetSelectedValue("0", null);		
		this.__creation.SetWidth(95);
		this.__creation.AttachEvent("onselected", this.CreateCallback(this.OnChange));
		
		this.AddControl(this.__creation);
		this.StoreDataToCookie();			
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.style.verticalAlign = "top";		
			this.HostElement.parentElement.style.paddingTop = "2px";
		}
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
	,StoreDataToCookie : function() 
	{
		tpl_SetCookie(P_NEWSLETTERS_ARCHIVE_GRID_FILTER_SORT, this.__creation.SelectedValue, true);	
	}			
	,OnChange : function() 
	{
		this.StoreDataToCookie();
		data_ClearPagingCookie();
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERSARCHIVE);
	}			
});

DeclareClass("SiteLayout.NewsletterArchiveTopToolbar", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.AsyncRenderingEnabled = true;
		this.AsyncControlUpdating = true;
		this.KeywordsAttach(KEY_NEWSLETTERARCHIVEPAGER)
	}
	,Init : [decl_virtual, function()
	{		
		this.itemBar = new UI.Controls.ItemBarBase();
		this.SetCssClass("module-actions");
		this.modulePagingCtl = new SiteLayout.ModulePagingControlArchiveNewsletter();
		this.AddControl(this.itemBar);
		this.itemBar.AddItem(this.modulePagingCtl);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.style.paddingTop = "5px";
			this.HostElement.parentElement.colSpan = 6;
		}
		this.base.Render();
		evnt_SubscribeOnEvent(EVT_REFRESH_MODULES, this.CreateCallback(this.OnRefreshWorkspaceModules));
	}]		
	,GetTagName : function() { return UI.HtmlTag.Div; }	
	,OnRefreshWorkspaceModules : function(keywords)
	{
		if (keywords != KEY_NEWSLETTERARCHIVEPAGER)
			return;	
		nav_SetNSArchiveItemsCount(this.CreateCallback(this.UpdatePager));
	}
	,UpdatePager : function(xml) 
	{ 
		var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var iCount = parseInt(oXmlNodeAccessor.GetNodeValue("//NewsletterArchiveItemsCount"));	
		if(iCount==NaN || iCount<=0)
			iCount = 0;					
		this.modulePagingCtl.updateContent(iCount);
	}			
});


DeclareClass("SiteLayout.NewsletterArchiveBottomToolbar", "UI.Control",
{
	constructor : function()
	{
		this.base();
		this.AsyncRenderingEnabled = true;
		this.AsyncControlUpdating = true;
		this.KeywordsAttach(KEY_NEWSLETTERARCHIVEPAGER)
	}
	,Init : [decl_virtual, function()
	{		
		this.SetCssClass("module-actions");
		this.modulePagingCtl = new SiteLayout.ModulePagingControlArchiveNewsletter();
		this.AddControl(this.modulePagingCtl);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
			this.HostElement.parentElement.colSpan = 6;
		this.base.Render();
		evnt_SubscribeOnEvent(EVT_REFRESH_MODULES, this.CreateCallback(this.OnRefreshWorkspaceModules));
	}]	
	,GetTagName : function() { return UI.HtmlTag.Div; }	
	,OnRefreshWorkspaceModules : function(keywords)
	{
		if (keywords != KEY_NEWSLETTERARCHIVEPAGER)
			return;	
		nav_SetNSArchiveItemsCount(this.CreateCallback(this.UpdatePager));		
	}	
	,UpdatePager : function(xml) 
	{ 
		var oXmlNodeAccessor =  new Xml.NodeAccessor(xml);
		var iCount = parseInt(oXmlNodeAccessor.GetNodeValue("//NewsletterArchiveItemsCount"));	
		if(iCount==NaN || iCount<=0)
			iCount = 0;					
		this.modulePagingCtl.updateContent(iCount);
	}		
});


DeclareClass("SiteLayout.ModulePagingControlArchiveNewsletter", "UI.Control",
{
	Init : [decl_virtual, function() {		
		this.container = DOMObjectFactory.CreateElement("span");	
		data_ClearPagingCookie();
	}]	
	,Update :[decl_virtual, function(writer){ 
		this.updateContent();
		return UI.UpdateStatus.NOUPDATE; 
	}]
	,updateContent: function(count) {		
		var pageNumber = tpl_GetCookie(P_NEWSLETTERS_ARCHIVE_GRID_PAGE);
		if(pageNumber==null || typeof(pageNumber)=="undefined")
			pageNumber = 1;
		var hasNextPage = false;
		if(count==null || count==NaN || count<=0)
			count = 0;		
		var html = "<span class='pgOfst'>Prev 0-0 Next (total ~0)</span>".format(count);
		
		if(pageNumber!=null && count>0)
		{					
			hasNextPage = pageNumber * NewslettersModuleControl.__ARCHIVE_ITEMS_PERPAGE > count ? false : true;			
			var paging = new ui_PagingControlNSArchive(NewslettersModuleControl.__ARCHIVE_ITEMS_PERPAGE, NewslettersModuleControl.__ARCHIVE_ITEMS_PERPAGE, pageNumber, hasNextPage, count);
			html = paging.Render();
		}
		if (this.container)
			this.container.innerHTML = html;
	},		
	Render :[decl_virtual, function SiteLayout_ModulePagingControl_Render(writer)
	{		
		this.HostElement.appendChild(this.container);
		this.updateContent();
	}]
	, OnDataSetRegistered : function(xDs) {}
});

DeclareClass("SiteLayout.NewslettersArchiveGridContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__grid = null;
		this.__dataset = null;
		this.__processCreateData = null;
		this.__dataSourceName = "NewslettersArchiveDS";
		this.__xmlNodeAccessor = null;		
		this.__loadedId = null;
		this.ondsregid;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		this.Listeners.AddObjectListener(this, "onvisiblechange", this.ClearAll);				
	}]
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		this.__processCreateData = data;
		this.base.ProcessCreateData(data);
		if (data != null)		
		{	
			var gridData = data.selectSingleNode("NewsletterArchiveGrid");
			if (gridData)
			{
				this.__grid = UI.Control.LoadControlTemplate(gridData);
				this.AddControl(this.__grid);
			}			
		}
	}]
	,Render :[decl_virtual, function(writer)
	{
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
			this.HostElement.parentElement.colSpan = 6;
	
		var rows = []; 
		var td = new UI.DOMControls.Td();
		if (this.__grid)
			this.__grid.RenderControl(td.Obj());
		rows.push(new UI.DOMControls.Tr(td));
		
		td = new UI.DOMControls.Td();
		td.Obj().innerHTML = "&nbsp;";
		td.SetCssClass("b04 pl10 pf_pg_std_ns");
		rows.push(new UI.DOMControls.Tr(td));		
		td = new UI.DOMControls.Td();
		td.SetCssClass("b04 pl10 pf_pg_std_ns");
		td.Obj().innerHTML = "&nbsp;";
		rows.push(new UI.DOMControls.Tr(td));				
		
		var tbl = new UI.DOMControls.Table(rows);
		tbl.SetCssClass("pf_pg_tbl_ns");
		this.HostElement.appendChild(tbl.Obj());			
		
		// attach to DataSet event		
		if (this.GetDataset() == null)
		{
			this.ondsregid = data_attachEvent("ondatasetregistered", this.CreateCallback(this.OnDataSetRegistered) );
			evnt_SubscribeOnEvent(EVT_REFRESH_MODULES, this.CreateCallback(this.OnRefreshWorkspaceModules));
		}		
	}]
	,GetDataset : function()
	{
		if (this.__dataset == null)
			this.__dataset = data_GetDataset(this.__dataSourceName);
		return this.__dataset;
	}
	,OnDataSetRegistered : function(xDs)
	{		
		if (this.__dataSourceName != xDs.name)
			return;
		data_detachEvent("ondatasetregistered",  this.ondsregid);
		this.HighlightOnLoad();	
	}		
	,HighlightOnLoad : function()
	{	
		//support selectable grid
		this.GetDataset().attachEvent("onitemchange", this.CreateCallback(this.OnItemSelected));
	
		// refresh pager
		nav_RefreshWorkspaceModules(KEY_NEWSLETTERARCHIVEPAGER);
		// waiting loading DS. there is no additional events for catching data
		window.setTimeout(this.CreateCallback(this.SetActive), 3000);
	}
	,SetActive : function()
	{		
		data_DropDatasetSelections(this.__dataSourceName);
		data_DataStoreCollection.ClearSelectedItemsForEmailing();		
	
		//select grid item on first load
		var dsArch = data_GetDataset(this.__dataSourceName);
		if(dsArch && dsArch.xdata.GetByIndex(0)!=null )		
		{
			var iNSArchiveId = dsArch.xdata.GetByIndex(0).GetItemID();
			data_MarkItemSelected(this.__dataSourceName, iNSArchiveId, true,true,false,false,event);
		}
		// clear email list
		else
			this.OnItemSelected(-1);
	}		
	,OnItemSelected : function(xItem)
	{		
		if(!xItem && xItem!=-1)
			return;						
		
		// load email for selected newsletter
		var nsId = xItem==-1 ? 0:xItem.GetNodeValue(P_NEWSLETTERS_ARCHIVE_STATE_ID);
		if(this.__loadedId!=nsId)
			NewslettersModuleControl.LoadItemArchiveEmailDS(nsId);					
		this.__loadedId=nsId;
	}			
	,OnRefreshWorkspaceModules : function(keywords)
	{
		if (keywords != KEY_NEWSLETTERSARCHIVE)
			return;	
		this.HighlightOnLoad();
	}
	,Update :[decl_virtual, function(writer)
	{
		return this.base.Update();
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__grid =null;
		this.__dataset = null;
	}]
});

DeclareClass("SiteLayout.NewsletterArchiveRecipients", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__text = new UI.Controls.LiteralControl("Newsletter Recipients");		
		this.__text.SetCssClass("nsNsRecipience");
		this.AddControl(this.__text);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
			this.HostElement.parentElement.colSpan = 4;
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
});

DeclareClass("SiteLayout.NewsletterArchiveResend", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__link = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__link = new UI.Controls.ScriptLink("Resend newsletter", this.CreateCallback(this.ResendNewsletter))
		this.AddControl(this.__link);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.colSpan = 2;
			this.HostElement.parentElement.align = "right";
		}
		this.base.Render();
	}]
	,ResendNewsletter : function()
	{
		var ds = data_GetSelectedItems("NewslettersArchiveDS");
		if (ds != null && NewslettersModuleControl.__selectedArchiveEmail.length > 0)
		{
			var bodyId = ds.GetByIndex(0).GetXmlDocument().selectSingleNode("//~0".format(P_NEWSLETTERS_ARCHIVE_BODY_ID)).text;
			var stateId = ds.GetByIndex(0).GetXmlDocument().selectSingleNode("//~0".format(P_NEWSLETTERS_ARCHIVE_STATE_ID)).text;
			new httpcmd_NewslettersArchiveResend(bodyId, stateId, NewslettersModuleControl.__selectedArchiveEmail.join(","), this.CreateCallback(this.OnResendComplete), null);
			alert("Newsletter successfully resend.");			
		}		
		else
		{
			alert("Please select email.");
		}
	}	
	,OnResendComplete : function()
	{
		//nav_RefreshWorkspaceModules(KEY_NEWSLETTERSARCHIVE);
	}
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
});

DeclareClass("SiteLayout.NewslettersArchiveEmailTitleContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__text = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__text = new UI.Controls.LiteralControl("E-Mail Address");		
		this.__text.SetCssClass("nsEmailAddresssTitle");
		this.AddControl(this.__text);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
			this.HostElement.parentElement.colSpan = 6;
		this.base.Render();
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
});

DeclareClass("SiteLayout.NewslettersArchiveEmailDataContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__emails = [];		
		this.__panel = null;
		this.__xmlNodeAccessor = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__input = new UI.Controls.InputControl("", null);				
		this.__panel = new UI.DOMControls.Div(new UI.DOMControls.LiteralControl("&nbsp;"));
		
		NewslettersModuleControl.AttachEvent(NS_EVENTS.OnLoadArchiveEmailDS, this.CreateCallback(this.SetEmailAddress));
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.colSpan = 6;
			this.HostElement.parentElement.width = "100%";
		}
	
		this.base.Render();
		this.HostElement.style.height = "100%";
		this.__panel.SetCssClass("nsEmailArea");
		this.HostElement.appendChild(this.__panel.Obj());
	}]
	,SetEmailAddress : function(xml)
	{
		// clear
		while(this.__panel.Obj().hasChildNodes())
			this.__panel.Obj().removeChild(this.__panel.Obj().firstChild);		
	
		if(xml!=null && xml.length>0 && xml.indexOf("EROOR")<=0)
		{		
			// parse
			this.__emails = [];
			this.__xmlNodeAccessor = new Xml.NodeAccessor(xml);
			var oNodeArchiveEmail = this.__xmlNodeAccessor.SelectSingleNode(NewslettersModuleControl.__xPath[7].XPath);
			if(oNodeArchiveEmail==null)
				return;
				
			// set values
			var rows = []; 
			for(var iEmailCounter=0; iEmailCounter<oNodeArchiveEmail.childNodes.length; iEmailCounter++)
			{
				var email = oNodeArchiveEmail.childNodes[iEmailCounter].selectSingleNode(NewslettersModuleControl.__xPath[8].XPath).text.replace(/^\s+|\s+$/g,"");
				var id = oNodeArchiveEmail.childNodes[iEmailCounter].selectSingleNode(NewslettersModuleControl.__xPath[9].XPath).text.replace(/^\s+|\s+$/g,"");
				if(email!=null && email.length>0)
				{
					//"<input type='checkbox' checked value='~0' email='~1'/>"
					var oCheckBox = document.createElement("input");
					oCheckBox.setAttribute("type", "checkbox");
					oCheckBox.setAttribute("value", id);
					oCheckBox.setAttribute("email", email);										
					var oSpan = document.createElement("span");
					var spanClass = "nsArchiveEmail";
					if(oSpan.className)
						oSpan.className = spanClass;
					else 
						oSpan.setAttribute("class", spanClass);					
					oSpan.innerText = email;
					this.__emails.push(oCheckBox);
					var oTdText = new UI.DOMControls.Td();
					oTdText.Obj().appendChild(oCheckBox);
					// set checked only after added to parent control
					oCheckBox.checked = true;
					dom_attachEventForObject(oCheckBox, "click", this.CreateCallback(this.OnEmailSelect));
					
					oTdText.Obj().appendChild(oSpan);
					rows.push(new UI.DOMControls.Tr(oTdText));
					
					// add to storage 
					var canAdd= true;
					for(var i=0; i<NewslettersModuleControl.__selectedArchiveEmail.length; i++)
						if(NewslettersModuleControl.__selectedArchiveEmail[i]==email)
							canAdd = false;
					if(canAdd)		
						NewslettersModuleControl.__selectedArchiveEmail.push(email);			
				}				
			}
			
			var tbl = new UI.DOMControls.Table(rows);			
			this.__panel.Obj().appendChild(tbl.Obj());			
		}
	}	
	,OnEmailSelect : function(event)
	{
		if(event && event.srcElement)
		{
			var email =	event.srcElement.getAttribute("email");
			if(event.srcElement.checked)
			{
				var canAdd = true;
				for(var i=0; i<NewslettersModuleControl.__selectedArchiveEmail.length; i++)
					if(NewslettersModuleControl.__selectedArchiveEmail[i]==email)
						canAdd = false;
				if(canAdd)		
					NewslettersModuleControl.__selectedArchiveEmail.push(email);			
			}
			else if(event.srcElement.checked == false)
				for(var i=0; i<NewslettersModuleControl.__selectedArchiveEmail.length; i++)
					if(NewslettersModuleControl.__selectedArchiveEmail[i]==email)
					{
						NewslettersModuleControl.__selectedArchiveEmail.splice(i, 1);
						break;
					}
		}
	}			
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		
		if (this.__input)
			this.__input.Dispose();
		this.__input = null;	
		
		this.__xmlNodeAccessor = null;					
	}]
});

DeclareClass("SiteLayout.NewsletterArchiveView", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__link = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{					
		this.__link = new UI.Controls.ScriptLink("View newsletter", this.CreateCallback(this.ResendNewsletter))
		this.AddControl(this.__link);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		if(this.HostElement && this.HostElement.parentElement && this.HostElement.parentElement.colSpan)
		{
			this.HostElement.parentElement.colSpan = 6;
			this.HostElement.parentElement.align = "right";
		}
		this.base.Render();
	}]
	,ResendNewsletter : function()
	{
		var ds = data_GetSelectedItems("NewslettersArchiveDS");
		if (ds != null)
		{
			var bodyId = ds.GetByIndex(0).GetXmlDocument().selectSingleNode("//~0".format(P_NEWSLETTERS_ARCHIVE_BODY_ID)).text;			
			nav_openPopupEx(PID_NEWSLETTERVIEWBODY, url_MakeParam(P_NEWSLETTERS_ARCHIVE_BODY_ID, bodyId), 650, 460, true, true);
		}		
	}	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();		
	}]
});

//----------------------------------------------- Portfolio controls ------------------------------------------------------------//
DeclareClass("SiteLayout.PortfolioModuleControl", "UI.Controls.WorkspaceModuleControl",
{		
	__setDatasetDataHandler: function(text, data, statusText)
	{
		var oldxColl = data_GetDataset(text);
		if(oldxColl != null && oldxColl.GetCount() > 0)
		{
			var xColl = Data.Helper.CreateCollectionByInfo(CoverageItem, data);
			if (xColl != null && xColl.GetCount() > 0)
			{
				var doc = oldxColl.GetXmlDocument();
				var ids = doc.selectNodes("//~0/~1[../IsNew='true']".format( CoverageItem.ItemName, CoverageItem.ItemIDName));
				if (ids != null)
				{
					for(var i=0; i < ids.length; i++)
					{
						var xItem = xColl.Get(ids[i].text);
						if (xItem != null)
							xItem.SetNodeValue( "IsNew", "true" );
					}
					data = xColl.GetXml();
				}
			}
		}
		data_SetDatasetData(text, data, statusText);
	}
});
DeclareClass("SiteLayout.PortfolioTagsModuleControl", "UI.Controls.WorkspaceModuleControl",
{		
	__setDatasetDataHandler: function(text, data, statusText)
	{
		var xColl = Data.Helper.CreateCollectionByInfo(SymbologyItem, data);
		if (xColl != null && xColl.GetCount() > 0)
		{
			var codes = SiteLayout.PortfolioNewCodesManager.GetCodes(null);
			if (codes != null)
			{
				for(var i=0; i < codes.length; i++)
				{
					var xItem = xColl.Get(codes[i]);
					if (xItem != null)
						xItem.SetNodeValue( "IsNew", "true" );
				}
				data = xColl.GetXml();
			}
		}
		data_SetDatasetData(text, data, statusText);
	}
});
DeclareClass("SiteLayout.PortfolioGridContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__grid = null;
		this.__link = null;
		this.__dataset = null;
		this.__dataSourceName = "PortfolioDS";
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		this.Listeners.AddObjectListener(this, "onvisiblechange", this.ClearAllNewMarkers);
		
		this.__link = new UI.Controls.ScriptLink("Create A New Portfolio ", this.CreateCallback(this.CreatePortfolio))
		this.AddControl(this.__link);
	}]
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		this.base.ProcessCreateData(data);
		if (data != null)		
		{	
			var gridData = data.selectSingleNode("PortfolioGrid");
			if (gridData)
			{
				this.__grid = UI.Control.LoadControlTemplate(gridData);
				this.AddControl(this.__grid);
			}
		}
	}]
	,Render :[decl_virtual, function(writer)
	{	
		var rows = []; 
		var td = new UI.DOMControls.Td();
		if (this.__grid)
			this.__grid.RenderControl(td.Obj());
		rows.push(new UI.DOMControls.Tr(td));
				
		td = new UI.DOMControls.Td();
		td.SetCssClass("b04 pt20 pl10 pf_pg_std");
		this.__link.RenderControl(td.Obj());
		rows.push(new UI.DOMControls.Tr(td));
		
		td = new UI.DOMControls.Td();
		td.SetCssClass("b04 pf_pg_thd");
		td.Obj().innerHTML = "&nbsp;";
		rows.push(new UI.DOMControls.Tr(td));
		
		var tbl = new UI.DOMControls.Table(rows);
		tbl.SetCssClass("pf_pg_tbl");
		this.HostElement.appendChild(tbl.Obj());
		this.CreateOnLoad();
	}]
	,CreateOnLoad : function()
	{	
		if (this.GetDataset() == null)
			this.ondsregid = data_attachEvent("ondatasetregistered", this.CreateCallback(this.OnDataSetRegistered) );
		else
		{
			if (window.flg_CreateNewPortfolioOnLoad == true)
				this.CreatePortfolio();
			flg_CreateNewPortfolioOnLoad = false;
		}
	}
	,OnDataSetRegistered : function(xDs)
	{
		if (this.__dataSourceName != xDs.name)
			return;
		data_detachEvent("ondatasetregistered",  this.ondsregid);
		this.CreateOnLoad();
	}
	,ClearAllNewMarkers : function()
	{
		SiteLayout.PortfolioNewCodesManager.Clear();
		var dataset = this.GetDataset();
		if (dataset)
		{
			for(var i =0; i < dataset.GetCount(); i++)
			{
				var xItem = dataset.GetByIndex(i);
				if (xItem != null)
					xItem.SetNodeValue( CoverageItem.PN_ISNEW, "false" );
			}
			dataset.LoadData(dataset.GetXml());
		}
	}
	,CreatePortfolio : function()
	{
		var name = this.GenerateUnicName("Portfolio");
		if (name != null)
			new httpcmd_AddPortfolio(name);
		return false;
	}
	,GetDataset : function()
	{
		if (this.__dataset == null)
			this.__dataset = data_GetDataset(this.__dataSourceName);
		return this.__dataset;
	}
	,IsUnicName : function(name, dataset)
	{
		for ( var i = 0; i < dataset.GetCount(); i++ )
		{
			if ( dataset.GetByIndex(i).GetNodeValue("Name") == name )
				return false;
		}
		return true;
	}
	,GenerateUnicName : function( namePrefix )
	{
		var dataset = this.GetDataset();
		if (dataset)
		{
			var suffix = dataset.GetCount();
			var name = namePrefix + suffix;
			while ( !this.IsUnicName( name, dataset ) )
			{
				suffix++;
				name = namePrefix + suffix;
			}
			return name;
		}
		return null;
	}
	,Update :[decl_virtual, function(writer)
	{
		if (this.IsVisible())
			this.CreateOnLoad();
		return this.base.Update();
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.__grid =null;
		this.__link = null;
		this.__dataset = null;
	}]
	,SetCurrentPortfolio : [decl_static, function(pid, name, mode)
	{
		srch_inpClearProcess();
		var query = url_CombineParams(url_CombineParams(url_MakeParam(P_MODE, mode), url_MakeParam(P_BEDATA_REFERENCE, pid)), url_MakeParam(P_TITLE, name));
		nav_ChangePageParams(query);
	}]
	,CheckDeletePortfolio : [decl_static, function(id)
	{
		if (nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE) == id)
			nav_ChangePageParams(P_MODE);	
	}]
});

DeclareClass("SiteLayout.PortfolioNewCompaniesCount", "UI.Control",
{	
	GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		this.Listeners.AddObjectListener(SiteLayout.PortfolioNewCodesManager, "onchange", this.ProcessRequest);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.SetCssClass("count_of_new_items");
		this.SetStyleAttribute("color", "#159105");
		this.SetInnerHtml();
	}]
	,SetInnerHtml : function()
	{
		if (this.HostElement != null)
		{
			var txt = "";
			var mc = SiteLayout.PortfolioNewCodesManager.GetCodesCount(null);
			if ( mc == 1 )
				txt = "1 company was added.";
			else if(mc > 1)
				txt = mc + " companies were added.";
			this.HostElement.innerHTML = txt;
		}
	}
	,Update :[decl_virtual, function(writer)
	{
		if (this.IsVisible())
			this.SetInnerHtml();
		return this.base.Update();
	}]	
});

DeclareClass("SiteLayout.PortfolioTagsGridContainer", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__grid = null;
		this.__dsRef = null;
		this.__literal = null;
		this.__tdRemoveAll = null;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{
		this.__dsRef = new Utils.DataSourceEventListener("PortfolioTagsDS", null)
		this.Listeners.AddCustomListener(this.__dsRef);
		this.Listeners.AddObjectListener(this, "onvisiblechange", this.OnChange);
		
		this.__literal = new SiteLayout.PortfolioNewCompaniesCount();
		this.AddControl(this.__literal);
	}]
	,ProcessCreateData :[decl_virtual, function(data) 
	{
		this.base.ProcessCreateData(data);
		if (data != null)		
		{	
			var gridData = data.selectSingleNode("PortfolioTagsGrid");
			if (gridData)
			{
				this.__grid = UI.Control.LoadControlTemplate(gridData);
				this.AddControl(this.__grid);
			}
		}
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.__grid.AddParameter(P_MODE, nav_currentNavInfo.GetParameter(P_MODE));
		this.__grid.AddParameter(P_BEDATA_REFERENCE, nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE));
		
		var rows = []; 
		var cells = [];
		var td = new UI.DOMControls.Td();
		this.__literal.RenderControl(td.Obj());
		cells.push(td);
		this.__tdRemoveAll = new UI.DOMControls.Td(new UI.DOMControls.Link("Remove All", "#", this.CreateCallback(this.RemoveAll)));
		this.__tdRemoveAll.SetCssClass("pt10");
		this.__tdRemoveAll.Obj().setAttribute("align", "right");
		this.__tdRemoveAll.SetVisibleState(nav_currentNavInfo.GetParameter(P_MODE) == "edit");
		cells.push(this.__tdRemoveAll);
		rows.push(new UI.DOMControls.Tr(cells));
				
		var td = new UI.DOMControls.Td();
		td.SetColSpan(2);
		if (this.__grid)
			this.__grid.RenderControl(td.Obj());
		rows.push(new UI.DOMControls.Tr(td));
						
		td = new UI.DOMControls.Td();
		td.SetColSpan(2);
		td.SetCssClass("b04");
		td.Obj().innerHTML = "&nbsp;";
		rows.push(new UI.DOMControls.Tr(td));
		
		var tbl = new UI.DOMControls.Table(rows);
		this.HostElement.appendChild(tbl.Obj());
	}]
	,GetDataset : function()
	{
		return this.__dsRef.GetDataSource();
	}
	,RemoveAll : function()
	{
		var ds = this.GetDataset();
		if (ds != null)
		{
			if (!confirm("Are you sure you want to remove all companies from this portfolio?")) return;
			this.Lock();
			var codes = [];
			for(var i=0; i < ds.GetCount(); i++)
				codes.push(ds.GetByIndex(i).GetItemID());
			SiteLayout.PortfolioCoverageEditor.__codes[nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE)] = null;
			new httpcmd_RemoveFromPortfolio(codes.join(";"), this.CreateCallback(this.OnRemoveComplete));
		}
		
	}
	,OnRemoveComplete : function()
	{
		this.Unlock();
	}
	,Update :[decl_virtual, function(writer)
	{
		if (this.IsVisible())
		{
			var mode = nav_currentNavInfo.GetParameter(P_MODE);
			if (this.__grid != null)
			{
				this.__grid.AddParameter(P_MODE, mode);
				this.__grid.AddParameter(P_BEDATA_REFERENCE, nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE));
				this.__grid.Refresh("Loading..", {"supportXml" : this.__curMode == mode});
			}
			if (this.__tdRemoveAll != null)
				this.__tdRemoveAll.SetVisibleState(mode == "edit");
				
			this.__curMode = mode;		
		}
		return this.base.Update();
	}]	
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__tdRemoveAll)
			this.__tdRemoveAll.Dispose();
		this.__tdRemoveAll = null;
		this.__literal = null;
		this.__grid =null;
		this.__dsRef = null;
	}]
});


DeclareClass("SiteLayout.PortfolioCoverageEditor", "UI.Control",
{		
	constructor: function()
	{
		this.base();
		this.__input = null;
		this.__textArea = null;
		this.__table = null;
		this.__inprg = false;
		this.__dataset = null;
		SiteLayout.PortfolioCoverageEditor.__codes = [];
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init :[decl_virtual, function() 
	{	
		var rows = []; 
		var td = new UI.DOMControls.Td(new UI.DOMControls.Text("Portfolio Name"));
		td.SetCssClass("pl15");
		td.Obj().setAttribute("height", "20px");
		rows.push(new UI.DOMControls.Tr(td));
				
		this.__input = new UI.DOMControls.InputControl(nav_currentNavInfo.GetParameter(P_TITLE));
		this.__input.AttachEvent("blur", this.CreateCallback(this.Rename))
		var td = new UI.DOMControls.Td(this.__input);
		td.SetCssClass("b04 pl15 pt10");
		rows.push(new UI.DOMControls.Tr(td));
		
		var td = new UI.DOMControls.Td(new UI.DOMControls.Text("Enter Ticker Symbols "));
		td.SetCssClass("b04 pl15 pt5");
		rows.push(new UI.DOMControls.Tr(td));
		
		this.__textArea = new UI.DOMControls.TextArea("", "7");
		this.__textArea.AttachEvent("keypress", this.CreateCallback(this.KeyPressed))
		this.__textArea.SetCssClass("pop01c");
		this.__textArea.Obj().setAttribute("id", "txta_portfolio_tags");
		this.__textArea.Obj().setAttribute("name", "txta_portfolio_tags");
		this.__textArea.Obj().style["height"] = "180px";

		
		var flit = new UI.DOMControls.LiteralControl("<br>Separate symbols by comma, up to 100 ticker symbols.<br>If you don't know the symbol you can use our&nbsp;");
		var link = new UI.DOMControls.Link("company lookup tool", "#", this.CreateCallback(this.ShowLockup));
		var slit = new UI.DOMControls.LiteralControl("<br><br>");
		var button = new UI.DOMControls.Button("Add", this.CreateCallback(this.AddTag));
		var td = new UI.DOMControls.Td(this.__textArea, flit, link, slit, button);
		td.SetCssClass("b04 pl15 pt10");
		rows.push(new UI.DOMControls.Tr(td));
		
		this.__table = new UI.DOMControls.Table(rows);
	}]
	,Render :[decl_virtual, function(writer)
	{	
		this.HostElement.appendChild(this.__table.Obj());
		Utils.MonitoringHelper.SetMonitoringInfo(MA_AddToPortfolio);		
		if (!srch_PagesCollection.GetSearchPageByName(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS,true))
			srch_PagesCollection.AddSearchPage(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS,new srch_SearchPage(null,null,GETSTIBYID(SRCH_TN_SYMBOL).longhint,  Data.Search.PortfolioInputSearch, null));
		srch_PagesCollection.SetCurrentSearchPageByName(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS);
	}]
	,Update :[decl_virtual, function(writer)
	{
		if (this.IsVisible())
		{
			srch_PagesCollection.SetCurrentSearchPageByName(PID_PLMYACCOUNTPREFERENCESMYPORTFOLIOS);
			this.__input.SetValue(nav_currentNavInfo.GetParameter(P_TITLE));
		}
		return this.base.Update();
	}]	
	,Rename : function()
	{
		var name = str_Trim( this.__input.GetValue() );
		if ( str_IsStringEmpty(name) )
		{
			alert( "Please enter name." );
			this.__input.Obj().focus();
			return;
		}
		var isnew = false;
		var ds = this.GetPortfolioDataset();
		var xItem = null;
		if (ds && (xItem = ds.Get(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE))) != null)
			isnew = xItem.GetNodeValue(CoverageItem.PN_ISNEW);
			
		new httpcmd_RenamePortfolio	(nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE), name, isnew, this.CreateCallback(this.OnRenameComplete));
	}
	,OnRenameComplete : function(isOk)
	{
		if (!isOk)
			this.__input.SetValue(nav_currentNavInfo.GetParameter(P_TITLE));
	}
	,KeyPressed : function()
	{
		if (event.keyCode == 13)
			return this.AddTag(); 
	}
	,AddTag : function()
	{
		this.Lock();
		if (srch_inpLoadTaggingString(this.CreateCallback(this.OnComplete), this.CreateCallback(this.OnCanceled)) == false)
			this.OnCanceled();
		return false;
	}
	,OnComplete : function(){this.DoAddTags(); this.Unlock();}
	,OnCanceled : function(){this.Unlock();}
	,ShowLockup : function()
	{
		srch_inpClearProcess();
		do_showCompanyLookup('srch_inpAddTagFromLookup', this.CreateCallback(this.DoAddTags));
		return false;
	}
	,DoAddTags : function()
	{
		if (this.__inprg == true)
			return;
		var xmlSearch = srch_inpGetClientXmlInterface();
		var tags = xmlSearch.GetTags();
		if (tags == null || tags.length == 0) return;
		var codes = new Array();
		var dataset = this.GetDataset();
		if (dataset == null)
			return;
		var itemsInDataset = dataset.GetCount();
		var length = Math.min(this.GetMaxAllowedPortfolioSize() - itemsInDataset, tags.length); 
		
		for ( var i = 0; i < length; i++ )
		{
			var code = xmlSearch.GetTagPropertyValue( tags[i], SRCH_TP_VALUE );
			if (dataset != null && dataset.Get(code) != null)
				continue;
			codes[codes.length] = code;
		}
		
		if (length != tags.length)
		{
			if (length < 1)
			{
				alert("You reach your portfolio's limit (" + this.GetMaxAllowedPortfolioSize().toString() + ").");
				return;
			}
			else
				alert("You exceed your portfolio's limit (" + this.GetMaxAllowedPortfolioSize().toString() + "). Only " + length.toString() + " item(s) will be added.");
		}
		
		if (codes.length == 0)  
		{
			alert("Item(s) with such name already exists.");
			return;
		}
		this.__inprg = true;
		new httpcmd_AddToPortfolio( nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE), codes, this.CreateCallback(this.OnAddTagsComplite));	
	}
	,OnAddTagsComplite : function()
	{
		this.__inprg = false;
		srch_inpSetInputValue("");
	}
	,GetPortfolioDataset : function()
	{
		if (this.__pfdataset == null)
			this.__pfdataset = data_GetDataset("PortfolioDS");
		return this.__pfdataset;
	}
	,GetDataset : function()
	{
		if (this.__dataset == null)
			this.__dataset = data_GetDataset("PortfolioTagsDS");
		return this.__dataset;
	}
	,GetMaxAllowedPortfolioSize : function()
	{
		if (CURUSERTYPE == 'LiteUser') return TouchPointConfig.PortfolioLimitForLite;
		return TouchPointConfig.PortfolioLimit;
	}
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		if (this.__textArea)
			this.__textArea.Dispose();
		this.__textArea = null;
		if (this.__input)
			this.__input.Dispose();
		this.__input = null;
		
		if (this.__table)
			this.__table.Dispose();
		this.__table = null;	
	}]
});
DeclareClass("SiteLayout.PortfolioNewCodesManager", null,
{		
	CODES : [decl_static, []]
	
	,AttachEvent:[decl_static, function(evtname, func)
	{ 
		if (SiteLayout.PortfolioNewCodesManager.__EeventContainer == null)
			SiteLayout.PortfolioNewCodesManager.__EeventContainer = new cmn_EventContainer();
		return SiteLayout.PortfolioNewCodesManager.__EeventContainer.attachEvent(evtname, func); 
	}]
	,DetachEvent: [decl_static, function(evtname, id)
	{
		if (SiteLayout.PortfolioNewCodesManager.__EeventContainer != null)
			return SiteLayout.PortfolioNewCodesManager.detachEvent(evtname, id); 
	}]
	,FireEvent	: [decl_static, function(evtname /*params[] called params*/)
	{ 
		if (SiteLayout.PortfolioNewCodesManager.__EeventContainer != null)
			return SiteLayout.PortfolioNewCodesManager.__EeventContainer.fireEvent.apply(SiteLayout.PortfolioNewCodesManager.__EeventContainer, arguments);
	}]
	
	,AddCodes :[decl_static, function(id, codes)
	{
		id = SiteLayout.PortfolioNewCodesManager.ChekID(id);
		if (codes != null && codes.length > 0 && id != null)
		{
			if (SiteLayout.PortfolioNewCodesManager.CODES[id] == null)
				SiteLayout.PortfolioNewCodesManager.CODES[id] = [];
			SiteLayout.PortfolioNewCodesManager.CODES[id] = SiteLayout.PortfolioNewCodesManager.CODES[id].concat(codes);
			SiteLayout.PortfolioNewCodesManager.FireEvent("onchange");
		}
	}]
	,GetCodes :[decl_static, function(id)
	{
		id = SiteLayout.PortfolioNewCodesManager.ChekID(id);
		if (id != null)
			return SiteLayout.PortfolioNewCodesManager.CODES[id];
		return null;
	}]
	,GetCodesCount :[decl_static, function(id)
	{
		var codes = SiteLayout.PortfolioNewCodesManager.GetCodes(id);
		if (codes != null)
			return codes.length;
	}]
	,GetCurrentID :[decl_static, function()
	{
		return nav_currentNavInfo.GetParameter(P_BEDATA_REFERENCE);
	}]
	,ChekID :[decl_static, function(id)
	{
		if (id == null)
			id = SiteLayout.PortfolioNewCodesManager.GetCurrentID();
		return id;
	}]
	,RemoveCodes :[decl_static, function(id, codes)
	{
		id = SiteLayout.PortfolioNewCodesManager.ChekID(id);
		if (id != null && codes != null
			&& SiteLayout.PortfolioNewCodesManager.CODES[id] != null && SiteLayout.PortfolioNewCodesManager.CODES[id].length > 0 )
		{
			var ischange = false;
			for(var j = 0; j < codes.length; j++)
				for (var i=0; i < SiteLayout.PortfolioNewCodesManager.CODES[id].length; i++)
				{
					if (codes[j] == SiteLayout.PortfolioNewCodesManager.CODES[id][i])
					{
						SiteLayout.PortfolioNewCodesManager.CODES[id].remove(i);
						ischange = true;
						break;
					}
				}
			if (ischange)
				SiteLayout.PortfolioNewCodesManager.FireEvent("onchange");
		}
	}]
	,RemoveAllCodes :[decl_static, function(id)
	{
		id = SiteLayout.PortfolioNewCodesManager.ChekID(id);
		if (id != null)
		{
			SiteLayout.PortfolioNewCodesManager.CODES[id] = null;
			SiteLayout.PortfolioNewCodesManager.FireEvent("onchange");
		}
	}]
	,Clear :[decl_static, function()
	{
		SiteLayout.PortfolioNewCodesManager.CODES = [];
	}]
});
//----------------------------------------------- Advanced Search Empty Panel ------------------------------------------------------------//
DeclareClass("UI.Controls.AdvancedSearchEmptyPanel", "UI.Control", {
	constructor: function() {		
		this.base();
		this.Text = "undefined";						
		this.__textLabel = new UI.DOMControls.Text(this.Text);
		this.__image = new UI.DOMControls.Image("icon_tree_minus_15height.gif", "");		
		this.__div = new UI.DOMControls.Div(this.__textLabel);		
		this.__wrapper = new UI.DOMControls.Div(this.__image);		
		this.__emptyArea = new UI.DOMControls.Div(new UI.DOMControls.Text(""));
	}
	,GetTagName: function() {
		return UI.HtmlTag.Div;
	}
	,ProcessCreateData :[decl_virtual, function(data) {				
		this.Text = data.getAttribute("Html");
		this.__textLabel.SetText(this.Text);
	}]	
	,Init: [decl_virtual, function() {				
		this.__wrapper.Obj().appendChild(this.__div.Obj());
		this.__wrapper.Obj().className = "sa-title";
		this.__image.Obj().style.position = "relative";
		this.__image.Obj().style.marginLeft = "5";
		this.__image.Obj().style.styleFloat = "left";		
		this.__div.Obj().style.position = "relative";
		this.__div.Obj().style.styleFloat = "left";		
		this.__div.Obj().style.marginTop = "3px";		
		this.__emptyArea.Obj().style.height = "12px"; 	
		
	}]
	,SetText: function(text) {
		this.Text = text;
		this.RepaintContent();
	}
	,RepaintContent: function()
	{
		this.__div.innerText = this.Text;
	}
	,Render:[decl_virtual, function(writer) {		
		this.HostElement.appendChild(this.__wrapper.Obj());
		this.HostElement.appendChild(this.__emptyArea.Obj());
		this.RepaintContent();		
		this.base.Render(writer);
	}]	
});
//----------------------------------------------- Advanced Search Empty Panel ------------------------------------------------------------//


/*********************** Trends **************************************************/

DeclareClass("Trends.Context", null, {
	constructor : function() {
		this.diagramUpdate = true;
		this.topicsDynamic = null;
		this.companiesDynamic = null;
		this.relatedCompanies = null;
		this.relatedTopics = null;
		this.relatedCustomTopics = null;
	}
	,SetCurrentDiagram : function(diagram)	{
		this.diagram = diagram; 
	}
	,GetCurrentDiagram : function() {
		return this.diagram;
	}
	,SetCurrentFilter : function(filter) {
		this.filter = filter;
	}
	,GetCurrentFilter : function()	{
	    return this.filter;
	}
	,SetRelatedCompanies : function(control) {
		this.relatedCompanies = control;
	}
	,GetRelatedCompanies : function() {
		return this.relatedCompanies;
	}
	,SetRelatedTopics : function(control) {
		this.relatedTopics = control;
	}
	,GetRelatedTopics : function() {
		return this.relatedTopics;
	}
	,SetRelatedCustomTopics : function(control) {
		this.relatedCustomTopics = control;
	}
	,GetRelatedCustomTopics : function() {
		return this.relatedCustomTopics;
	}	
});

var GlobalTrendsContext = new Trends.Context();

/**
 * Trends Event Manager
 */
DeclareClass("Trends.EventManager", null, {
	constructor : function() {
		this.events = new cmn_EventContainer();
	}
	,AttachEvent : function(evt, func)	{
		this.events.attachEvent(evt, func);
	}
	,DetachEvent : function(evt, func)	{
		this.events.detachEvent(evt, func);
	}
    ,OnNeedRefresh : function(full_refresh) {
        this.events.fireEvent("onneedrefresh", full_refresh);
    }
	,OnNeedDiagramRefresh : function() {
		this.events.fireEvent("onneeddiagramrefresh");
	}
	,OnTrendsFilterSearch : function(industryId, periodId, averageId) {
		this.events.fireEvent("onfiltersearch", industryId, periodId, averageId);
	}
	,OnTrendClick : function(date, obj) {
		this.events.fireEvent("ontrendclick", date, obj);
	}
	,OnRegionMapClick : function(industryCode, industryName, regionCode, regionName, obj) {
		this.events.fireEvent("onregionmapclick", industryCode, industryName, regionCode, regionName, obj);
	}
	,OnTrendDateChanged : function(date) {
		this.events.fireEvent("ontrenddatechanged", date);
	}
});
var GlobalTrendsEventManager = new Trends.EventManager();

DeclareClass("Trends.Parameter", null, {
	constructor : function(name, value) {
		this.name = name;
		this.value = value;
        this.defaultValue = value;
	}
	,SetValue : function(value) {
		this.value = value;
    }
    ,SetDefaultValue : function() {
        this.value = this.defaultValue;
    }
    ,GetValue : [decl_virtual, function() {
        return this.value;
    }]
    ,GetName : function() {
        return this.name;
    }
    ,IsDefault : function() {
        return (this.value == this.defaultValue)
    }
});

DeclareClass("Trends.ShowRelatedParameter", "Trends.Parameter", {
    constructor : function() {
        this.base(P_TRENDS_SHOW_RELATED, null);
    }
    ,GetValue : [decl_virtual, function() {
        if (nav_currentNavInfo.GetPageID() == PID_TRENDS)
            return true;

        return GeneralPreferences.EnableTrendsOnOtherPages ? 'true' : 'false';
    }]
});

DeclareClass("Trends.Parameters", null, {
	constructor : function() {
		this.SetInitialValues();
	}
	,SetInitialValues : function() {
			try
			{				
				if(!this.Period.GetValue())
				{
        	this.Period = new Trends.Parameter(P_TRENDS_PERIOD, GeneralPreferences.TrendsDefaultDateRange);
        	if(!this.Period.GetValue())
        		this.Period = new Trends.Parameter(P_TRENDS_PERIOD, "Last30Days");
        }
			}
			catch(e)
			{       
				this.Period = new Trends.Parameter(P_TRENDS_PERIOD, "Last30Days");
			}
			
        this.Industry = new Trends.Parameter(P_TRENDS_INDUSTRY_ID, "");
        this.MovingAverage = new Trends.Parameter(P_TRENDS_MOVING_AVERAGE, "None");
        this.MapIndustry = new Trends.Parameter(P_TRENDS_MAP_INDUSTRY, "");
        this.MapRegion = new Trends.Parameter(P_TRENDS_MAP_REGION, "");
        this.RelatedTopic = new Trends.Parameter(P_TRENDS_RELATED_TOPIC, "");
        this.RelatedCustomTopic = new Trends.Parameter(P_TRENDS_RELATED_CUSTOM_TOPIC, "");
        this.RelatedCompany = new Trends.Parameter(P_TRENDS_RELATED_COMPANY, "");
        this.TrendDate = new Trends.Parameter(P_TRENDS_TREND_DATE, "");
        this.ShowRelated = new Trends.ShowRelatedParameter();
        this.FilterExpression = new Trends.Parameter(P_FILTEREXPRESSION, "");
	}
    ,GetQueryString : function() {
        var list = new dm_QueryString();
        list.Add(this.Period.GetName(), this.Period.GetValue());
        list.Add(this.Industry.GetName(), this.Industry.GetValue());
        list.Add(this.MovingAverage.GetName(), this.MovingAverage.GetValue());
        list.Add(this.MapIndustry.GetName(), this.MapIndustry.GetValue());
        list.Add(this.MapRegion.GetName(), this.MapRegion.GetValue());
        list.Add(this.RelatedCompany.GetName(), this.RelatedCompany.GetValue());
        list.Add(this.RelatedTopic.GetName(), this.RelatedTopic.GetValue());
        list.Add(this.RelatedCustomTopic.GetName(), this.RelatedCustomTopic.GetValue());
        list.Add(this.TrendDate.GetName(), this.TrendDate.GetValue());
        list.Add(this.ShowRelated.GetName(), this.ShowRelated.GetValue());
        list.Add(this.FilterExpression.GetName(), this.FilterExpression.GetValue());
        return list;
    }
    ,CombineTo : function(/*dm_QueryString*/ queryString) {
    	if(queryString.GetValue(P_FILTEREXPRESSION))
    		this.FilterExpression.SetValue(queryString.GetValue(P_FILTEREXPRESSION));    	
        queryString.CombineQueries(this.GetQueryString());
    }
	,IsHeadlinesNotFiltered : function() {
		var result =
			this.MapIndustry.IsDefault() &&
			this.MapRegion.IsDefault() &&
			this.TrendDate.IsDefault() &&
			this.RelatedCompany.IsDefault() &&
			this.RelatedTopic.IsDefault() &&
			this.RelatedCustomTopic.IsDefault();

		return result;
	}
});
var GlobalTrendsParameters = new Trends.Parameters();

DeclareClass("UI.Trends.FilterPartTable", null, {
	constructor : function(title, domControl) {
		this.titleTd = new UI.DOMControls.Td(new UI.DOMControls.LiteralControl(title));
		this.titleTd.SetCssClass("filter-part-title");

		this.controlTd = null;

		if (domControl)
			this.controlTd = new UI.DOMControls.Td(domControl);
		else
			this.controlTd = new UI.DOMControls.Td();

		this.table = new UI.DOMControls.Table(new UI.DOMControls.Tr(this.titleTd), new UI.DOMControls.Tr(this.controlTd));
	}

	,GetTitleTd : function() {
		return this.titleTd;
	}

	,GetControlTd : function() {
		return this.controlTd;
	}

	,GetTable : function() {
		return this.table;
	}
});

DeclareClass("UI.Trends.Filter", "UI.Controls.Panel", {
	constructor : function(name) {
		GlobalTrendsContext.SetCurrentFilter(this);
		this.DataLoadText = "Loading trends filter";
        this.InitValues();
		this.base("some");
	}

    ,InitValues : function() {
        this.dateRangeValue = GlobalTrendsParameters.Period.GetValue();
        this.industryValue = GlobalTrendsParameters.Industry.GetValue();
        this.movingAverageValue = GlobalTrendsParameters.MovingAverage.GetValue();
    }

	,FixValues : function() {
        GlobalTrendsParameters.Period.SetValue(this.dateDropDown.GetValue());
        GlobalTrendsParameters.Industry.SetValue(this.sectorDropDown.GetValue());
        GlobalTrendsParameters.MovingAverage.SetValue(this.movingAverageDropDown.GetValue());
        this.InitValues();
	}

	,UpdateValues : function()	{
		this.sectorDropDown.SetSelectedValue(this.industryValue);
		this.dateDropDown.SetSelectedValue(this.dateRangeValue);
		this.movingAverageDropDown.SetSelectedValue(this.movingAverageValue);
	}

	,Update :[decl_virtual, function(writer) {
		this.UpdateValues();
		this.UpdateFilters();
		return this.base.Update(writer);
	}]

	,UpdateFilters : function() {
		var state = SiteLayout.TrendsViewSwitch.GetTrendsViewState();

		if (state == "map") 	{
			this.sectorTd.SetCssClass("filter-part");
			this.movAvgTd.SetCssClass("filter-part-hidden");
		} else	{
			this.sectorTd.SetCssClass("filter-part-hidden");
			this.movAvgTd.SetCssClass("filter-part");
		}
	}

	,Init: [decl_virtual, function() {

		//Industry
		this.sectorDropDown = new UI.Controls.DropDown();
		this.sectorDropDown.Clear();
		this.sectorDropDown.AddItem('Unfiltered', '');
		for(var i=0; i< TPIndustryCache.length; i++)
			this.sectorDropDown.AddItem(TPIndustryCache[i].name, TPIndustryCache[i].code);
		this.sectorDropDown.SetSelectedValue('');

		//Date Range
		this.dateDropDown = new UI.Controls.DropDown();
		this.dateDropDown.Clear();
		for(var i=0; i< TPTrendsDateFilterValues.length; i++)
			this.dateDropDown.AddItem(TPTrendsDateFilterValues[i].name, TPTrendsDateFilterValues[i].value);

		//Moving average days
		this.movingAverageDropDown = new UI.Controls.DropDown();
		this.movingAverageDropDown.Clear();
		for(var i=0; i< TPTrendsMovingAverageDaysValues.length; i++)
			this.movingAverageDropDown.AddItem(TPTrendsMovingAverageDaysValues[i].name, TPTrendsMovingAverageDaysValues[i].value);

		this.base.Init();
		this.AddControl(this.sectorDropDown);
		this.AddControl(this.dateDropDown);
		this.AddControl(this.movingAverageDropDown);

		this.switcher = new SiteLayout.TrendsViewSwitch();
		this.AddControl(this.switcher);

		//Set initial values
		this.UpdateValues();
	}]

	,OnSearchClick : function(event) {
		this.FixValues();
		GlobalTrendsParameters.Industry.SetValue(this.sectorDropDown.GetValue());
		GlobalTrendsParameters.Period.SetValue(this.dateDropDown.GetValue());
		GlobalTrendsParameters.TrendDate.SetValue("");
		GlobalTrendsParameters.MovingAverage.SetValue(this.movingAverageDropDown.GetValue());
		GlobalTrendsParameters.RelatedTopic.SetValue("");
		GlobalTrendsParameters.RelatedCustomTopic.SetValue("");
		GlobalTrendsParameters.RelatedCompany.SetValue("");
//		GlobalTrendsEventManager.OnTrendsFilterSearch(this.sectorDropDown.GetValue(), this.dateDropDown.GetValue(), this.movingAverageDropDown.GetValue());
		GlobalTrendsEventManager.OnNeedRefresh(true);
		GlobalTrendsEventManager.OnNeedDiagramRefresh();
		//srch_trendsDoSearch();
		return false;
	}

	,Render :[decl_virtual, function(writer) {
		this.HostElement.style.backgroundColor = "#eaeaea";

		//Filter parts
		var sectorPart = new UI.Trends.FilterPartTable("Industry");
		var datePart = new UI.Trends.FilterPartTable("Date Range");
		var movAvgPart = new UI.Trends.FilterPartTable("Mov Avg");
		var searchPart = new UI.Trends.FilterPartTable("&nbsp;", new UI.DOMControls.Button("Update", this.CreateCallback(this.OnSearchClick)));

		this.sectorTd = new UI.DOMControls.Td(sectorPart.GetTable());
		this.sectorTd.SetAttribute("width", "160px");
		this.sectorTd.SetCssClass("filter-part");

		var dateTd = new UI.DOMControls.Td(datePart.GetTable());
		dateTd.SetAttribute("width", "110px");
		dateTd.SetCssClass("filter-part");

		this.movAvgTd = new UI.DOMControls.Td(movAvgPart.GetTable());
		this.movAvgTd.SetAttribute("width", "110px");
		this.movAvgTd.SetCssClass("filter-part");

		var searchTd = new UI.DOMControls.Td(searchPart.GetTable());
		searchTd.SetAttribute("width", "75px");
		searchTd.SetCssClass("filter-part");

		var resizeTd = new UI.DOMControls.Td(new UI.DOMControls.LiteralControl("&nbsp;"));

		var switcherTd = new UI.DOMControls.Td();
		switcherTd.SetAttribute("width", "90px");
		switcherTd.SetAttribute("style", "padding-bottom:3px; ");
		this.switcher.RenderControl(switcherTd.Obj());


		var filterTable = new UI.DOMControls.Table(
			new UI.DOMControls.Tr(this.sectorTd, dateTd, this.movAvgTd, searchTd, switcherTd, resizeTd));

		filterTable.SetCssClass("trends-filter");
		this.HostElement.appendChild(filterTable.Obj());

		this.sectorDropDown.RenderControl(sectorPart.GetControlTd().Obj());
		this.dateDropDown.RenderControl(datePart.GetControlTd().Obj());
		this.movingAverageDropDown.RenderControl(movAvgPart.GetControlTd().Obj());

		this.UpdateFilters();		
	}]
});

DeclareClass("UI.Trends.Diagram", "UI.Controls.WorkspacePanel", {
	constructor : function() {
		this.base();
		GlobalTrendsEventManager.AttachEvent("onneeddiagramrefresh", this.CreateCallback(this.Refresh));
	}
	,Init :[decl_virtual, function(){
		this.AAAAA = "UI.Trends.Diagram";
		GlobalTrendsContext.SetCurrentDiagram(this);
		this.Diagram1 = new UI.Trends.TrendsDiagramContainer("InfoNgen.TouchPoint.Modules.Trends.Trend.TrendPanel");
		this.Diagram2 = new UI.Trends.RegionMapDiagramContainer("InfoNgen.TouchPoint.Modules.Trends.RegionMap.RegionMapPanel");
		this.CheckState();		
		this.AddContentControl(this.Diagram1);
		this.AddContentControl(this.Diagram2);
	}]
	,CheckState: function(){
		var state = SiteLayout.TrendsViewSwitch.GetTrendsViewState();
		this.Diagram1.SetVisibleState((state == "trends") && this.IsVisible());
		this.Diagram2.SetVisibleState((state == "map") && this.IsVisible());	
	}

	,Refresh : function() {
		this.Diagram1.__controlState = UI.ControlState.UNINITIALIZED;
		this.Diagram2.__controlState = UI.ControlState.UNINITIALIZED;
		this.ProcessRequest();
		GlobalTrendsContext.GetCurrentFilter().ProcessRequest();
	}

	,Render :[decl_virtual, function(writer)
	{
		this.base.Render(writer);
	}]

	,Update :[decl_virtual, function(writer){
		this.CheckState();

//		if (!GlobalTrendsContext.GetDiagramUpdateStatus())
//		return UI.UpdateStatus.NOUPDATE;

		return this.base.Update(writer);
	}]
});


DeclareClass("UI.Trends.RegionMapDiagramContainer", "UI.Controls.DynamicServerControl",
{
	constructor : function() {
		this.base("InfoNgen.TouchPoint.Modules.Trends.RegionMap.RegionMapPanel");
		this.clear_parameters_before_loading = false;
		this.oldCell = new Object();
		this.selectedCell = null;
		GlobalTrendsEventManager.AttachEvent("onregionmapclick", this.CreateCallback(this.OnRegionMapClick));
	}
	,OnRegionMapClick : function(industryCode, industryName, regionCode, regionName, obj) {
		if (obj) {
			if (this.selectedCell && this.selectedCell.parentNode && this.oldCell) {
				this.selectedCell.parentNode.style.backgroundColor = this.oldCell.parentBackColor;
				this.selectedCell.style.color = this.oldCell.color;
			}
			this.selectedCell = obj;
			this.oldCell.parentBackColor = obj.parentNode.style.backgroundColor;
			this.oldCell.color = obj.style.color;
			obj.parentNode.style.backgroundColor = "#FF0000";
			obj.style.color = "#FFFFFF";
		}

        GlobalTrendsParameters.MapIndustry.SetValue(industryCode);
        GlobalTrendsParameters.MapRegion.SetValue(regionCode);
        GlobalTrendsEventManager.OnNeedRefresh();

	}

	,OnDynamicLoading : [decl_virtual, function(id, data) {
        GlobalTrendsParameters.MapIndustry.SetDefaultValue();
        GlobalTrendsParameters.MapRegion.SetDefaultValue();
        GlobalTrendsParameters.CombineTo(this.GetDynamicParameters());
	}]
});

DeclareClass("UI.Trends.TrendsDiagramContainer", "UI.Controls.DynamicServerControl", {
	constructor : function() {
		this.base("InfoNgen.TouchPoint.Modules.Trends.Trend.TrendPanel");
		this.clear_parameters_before_loading = false;
		this.oldCell = new Object();
		this.selectedCell = null;
	    GlobalTrendsEventManager.AttachEvent("ontrendclick", this.CreateCallback(this.OnTrendClick));
	}
	,OnTrendClick : function(date, obj) {


		if (obj) {
			if (this.selectedCell && this.selectedCell.parentNode && this.oldCell)	 {
				this.selectedCell.style.backgroundColor = this.oldCell.backgroundColor;
			}

			this.selectedCell = obj;
			this.oldCell.backgroundColor = obj.style.backgroundColor;

			obj.style.backgroundColor = "#FF0000";
		}
	}

    ,OnDynamicLoading : [decl_virtual, function(id, data) {
        GlobalTrendsParameters.TrendDate.SetDefaultValue();
        GlobalTrendsParameters.CombineTo(this.GetDynamicParameters());
    }]
});

DeclareClass("UI.Trends.RelatedPanel", "UI.Controls.WorkspacePanel", {
	constructor : function() {
		nav_AttachEvent("onnavigationchange", this.CreateCallback(function() {
		}));

        srch_advAttachEvent("ondosearch", this.CreateCallback(function() {
        	GlobalTrendsParameters.SetInitialValues();
    	}));

		//simple enum
		this.COMPANIES = 1;
		this.TOPICS = 2;
		this.CUSTOMTOPICS = 3;

		//by default this is related companies
		this.Mode = this.COMPANIES;
		this.Dynamic = null;
		this.Data = null;
		this.IsUpdating = false;
		this.NoDataText = "";
		
		this.base();
	}

	,ProcessCreateData: [decl_virtual, function(data) {
		this.base.ProcessCreateData(data);
		if (this.ControlType == "InfoNgen.TouchPoint.Modules.Trends.Related.RelatedCompanies") 
		{
			this.Mode = this.COMPANIES;
			GlobalTrendsContext.SetRelatedCompanies(this);
		} 
		else if (this.ControlType == "InfoNgen.TouchPoint.Modules.Trends.Related.RelatedTopics") 
		{
			this.Mode = this.TOPICS;
			GlobalTrendsContext.SetRelatedTopics(this);
		} 
		else if (this.ControlType == "InfoNgen.TouchPoint.Modules.Trends.Related.RelatedCustomTopics") 
		{
			this.Mode = this.CUSTOMTOPICS;
			GlobalTrendsContext.SetRelatedCustomTopics(this);		
		}
		this.NoDataText = data.getAttribute("NoDataText");
	}]
	,Init :[decl_virtual, function(){
		this.base.Init();
		this.wsModule.DataLoadText = "Loading...";
		this.wsModule.ClientDataObject = this.CreateCallback(this.OnDynamicLoading);
		this.wsModule.NoDataText = this.NoDataText;
		
		GlobalTrendsParameters.SetInitialValues();
	}]
	,OnDynamicLoading : function(dynamic, params) {
		if (dynamic == null || typeof(dynamic) == 'undefined')
			return;
		this.Dynamic = dynamic;
		this.IsUpdating = true;
	}
	,RenderRelated : function(data) {
		if (this.Dynamic == null)
			return;

		this.IsUpdating = false;
		this.Dynamic.OnDataReady(this.Dynamic, data);
		this.Data = data;
	}
	,RefreshRelated : function() {
		if (this.Dynamic == null || this.Data == null)
			return;

		this.RenderRelated(this.Data);
	}
});

DeclareClass("SiteLayout.SymbolTypeControl", "UI.Control",
{
	constructor : function()
	{
		this.base();
		TouchPointSettings.attachEvent("onafterchange",this.CreateCallback(this.ReloadStatus));
		this.isPrimary = pref_GetShowPrimarySymbols();
	}
	,Init : [decl_virtual, function()
	{
		this.img = DOMObjectFactory.CreateElement(UI.HtmlTag.Image);
		this.SetCssClass("grey");
	}]
	,ReloadStatus : function()
	{
		this.isPrimary = pref_GetShowPrimarySymbols();
		this.ShowImage();
	}
	,ChangeStatus : function()
	{
		this.isPrimary = !this.isPrimary;
		TouchPointSettings.setShowPrimarySymbols(this.isPrimary?"-1":"0");
	}
	,ShowImage : function()
	{
		var src = cmn_GetImageUrl("icon_check_grey.gif");
		if (this.isPrimary)
			src = cmn_GetImageUrl("icon_check.gif");
		this.img.src = src;
	}
	/*,Disable : function(value)
	{
		this.__disabled = value;
		if (this.HostElement)
			this.HostElement.disabled = value;
		this.img.disabled = value;
		this.img.style.filter = (value)?"progid:DXImageTransform.Microsoft.BasicImage(grayscale=1, xray=0, mirror=0, invert=0, opacity=1.00, rotation=0)":"";
	}*/
	,Render :[decl_virtual, function(writer)
	{
		this.HostElement.appendChild(this.img);
		this.img.width = 16;
		this.img.height = 15;
		this.img.style.marginBottom = -1;
		dom_attachEventForObject(this.img,"click",this.CreateCallback(this.ChangeStatus));
		this.ShowImage();
		this.HostElement.appendChild(document.createTextNode(" Primary Symbols Only"));
		/*if (this.__disabled)
			this.Disable(this.__disabled);*/
	}]
	,Dispose :[decl_virtual, function()
	{
		this.base.Dispose();
		this.img = null;
	}]
});
DeclareClass("SiteLayout.RecentSearchesPopup", "UI.Control",
{
	GetTagName : function() {return UI.HtmlTag.Image;}
	,Render :[decl_virtual, function(writer)
	{
		this.HostElement.style.cursor = "pointer";
		this.HostElement.width = 27;
		this.HostElement.height = 22;
		this.HostElement.src = cmn_GetImageUrl("icon_recentsearches.png");
		dom_attachEventForObject(this.HostElement,"click",function() {SiteLayout.InputSearchControlBase.ShowRecentSearchesPopup(1000)});
	}]
});
DeclareClass("SiteLayout.InputSearchControlBase", "UI.Control",
{
	constructor : function()
	{
		this.base();
		TPInputSearchControl = this;
	}
	,Init : [decl_virtual, function()
	{
		srch_seAttachEvent("onstatechange",this.CreateCallback(this.Reload));
	}]
	,Reload : [decl_virtual, function()
	{
	}]
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,GetInputControl : [decl_static, function()
	{
		if (TPInputSearchControl)
			return TPInputSearchControl.GetInputControl();
		return null;
	}]
	,SetInputValue : [decl_static, function(val)
	{
		if (TPInputSearchControl)
			TPInputSearchControl.SetInputValue(val);
	}]
	,AppendValueToInput : [decl_static, function(val)
	{
		if (TPInputSearchControl)
			TPInputSearchControl.AppendValueToInput(val);
	}]
	,GetInputValue : [decl_static, function()
	{
		if (TPInputSearchControl)
			return TPInputSearchControl.GetInputValue();
		return null;
	}]
	,ShowRecentSearchesPopup : [decl_static, function(timer)
	{
		if (TPInputSearchControl && TPRecentSearchesObject.PopupID)	{
			var options = new UI.PopupareaOptions(SiteLayout.InputSearchControlBase.GetInputControl());
			options.hideTimeout = timer;
			options.allowAutoRedirection = false;
			uirso_RenderAvailableTags();
			UI.Popuparea.Find(TPRecentSearchesObject.PopupID).showPopupFromObject(options);
		}
		return null;
	}]
	,GetScopeTagName : [decl_static, function()
	{
		if (TPInputSearchControl)
			return TPInputSearchControl.GetScopeTagName();
		return null;
	}]
	,GetScopeForCurrentPage : [decl_static, function()
	{
		if (TPInputSearchControl)
			return TPInputSearchControl.GetScopeForCurrentPage();
		return null;
	}]
	,AddSpecialFilters : [decl_static, function()
	{
		if (TPInputSearchControl)
			return TPInputSearchControl.AddSpecialFilters();
		return null;
	}]
	,GetUniqueSearchInputID : function(pid, ploc)
	{
		var ssID = null;
		if (nav_IsNavigationEnabled())
		{
			pid  = this.GetNavigationPID(pid);
			ploc = this.GetNavigationLocation(ploc);
			switch(ploc)
			{
				case PID_PLSEARCHRESULTS:
				case PID_PLADVANCEDSEARCH:
					ploc = "";
					break;
			}
			if (!str_IsStringEmpty(ploc))
				ploc = "__" + ploc;
			ssID = pid+ploc;
		}
		return ssID;
	}
	,GetNavigationPID : function(pid)
	{
		var pid = "";
		if (nav_IsNavigationEnabled())
		{
			if (!pid) pid = nav_currentNavInfo.GetPageID();
			if (!pid) pid = "";
		}
		return pid;
	}
	,GetNavigationLocation : function(ploc)
	{
		var ploc = "";
		if (nav_IsNavigationEnabled())
		{
			if (!ploc) ploc = nav_currentNavInfo.GetPageLocation();
			if (!ploc) ploc = "";
		}
		return ploc;
	}
});
DeclareClass("SiteLayout.InputSearchControl", "SiteLayout.InputSearchControlBase",
{
	constructor : function()
	{
		this.base();
		this.input = DOMObjectFactory.CreateElement(UI.HtmlTag.Input);
		this.AsyncRenderingEnabled = false;
		if(BrowserInfo.IsIE())
			this.Listeners.AddDOMListener(window,"resize",this.CreateCallback(this.OnControlResize));
		this.emptyText = "Enter Ticker Symbol";
		//css class
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.LoadFromConfig();

		this.symbolTypeControl = new SiteLayout.SymbolTypeControl();
		this.AddControl(this.symbolTypeControl);
		this.recentSearchesPopup = new SiteLayout.RecentSearchesPopup();
		this.AddControl(this.recentSearchesPopup);

		this.scopeDropDown = new UI.Controls.DropDown();
		this.scopeDropDown.ID = "sc";
		this.scopeDropDown.SetCssClass("search-dropdown");
		this.scopeDropDown.AttachEvent("onselected", this.CreateCallback(this.ScopeChange));
		this.AddControl(this.scopeDropDown);

		var thisObj = this;
		dom_attachEventForObject(this.input,"keydown",this.CreateCallback(this.OnKeyDown));
		dom_attachEventForObject(this.input,"focus",function(){thisObj.ChangeInputStatus(true);});

		this.searchbutton = DOMObjectFactory.CreateElement(UI.HtmlTag.Input);
		this.searchbutton.type = "button";
		this.link_save = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		this.link_clear = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		this.link_advanced = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		//this.additional_span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
	}]
	,AllowSaveSearch : function()
	{
		if (nav_IsNavigationEnabled() && nav_currentNavInfo.GetPageID() == PID_HOME)
			return false;
		return CREData.BrandsFilter().AllowSaveSearch == "true";
	}
	,Render :[decl_virtual, function(writer)
	{
		var table, row, cell, span, anchor;

		table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		table.border = 0;
		table.style.height = "100%";
		this.HostElement.appendChild(table);

		row = table.insertRow();

		cell = row.insertCell();
		this.recentSearchesPopup.RenderControl(cell);

		cell = row.insertCell();
		this.input.className = this.__GetInputCssClass();
		cell.appendChild(this.input);

		this.__scopeDropDownTitle = row.insertCell();
		this.__scopeDropDownTitle.style.display = "none";
		this.__scopeDropDownTitle.innerHTML = this.__GetDropDownTitleHtml();
		this.__scopeDropDownTitle.style.paddingLeft = "0";

		this.__scopeDropDownContainer = row.insertCell();
		this.__scopeDropDownContainer.style.display = this.__scopeDropDownContainer.style.display = "none";
		this.__scopeDropDownContainer.style.paddingLeft = "0";
		this.scopeDropDown.RenderControl(this.__scopeDropDownContainer);

		cell = row.insertCell();
		cell.style.paddingLeft = "0";
		cell.vAlign = "top";
		dom_attachEventForObject(this.searchbutton,"click",this.CreateCallback(this.__DoSearch));
		cell.appendChild(this.searchbutton);

		row = table.insertRow();
		row.style.height = "100%";
		cell = row.insertCell();

		cell = row.insertCell();
		this.symbolTypeControl.RenderControl(cell);

		cell.appendChild(this.link_clear);
		this.__ChangeClearLinkDisplay("none");
		this.link_clear.className = "blue";

		//this.additional_span.appendChild(document.createTextNode(" - "));
		//this.link_clear.appendChild(this.additional_span);
		anchor = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
		this.link_clear.appendChild(anchor);
		anchor.innerText = "Clear Search";
		anchor.href = "#";
		dom_attachEventForObject(anchor,"click",function(){srch_ClearSearchResults(true);return false;});

		this.link_clear.appendChild(this.link_save);
		var img = DOMObjectFactory.CreateElement(UI.HtmlTag.Image);
		img.src = cmn_GetImageUrl("menuSep.gif");
		img.style.marginBottom = "-2px";
		this.link_save.appendChild(document.createTextNode(" "));
		this.link_save.appendChild(img);
		this.link_save.appendChild(document.createTextNode(" "));

		anchor = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
		this.link_save.appendChild(anchor);
		anchor.innerText = "Save";
		anchor.href = "#";
		dom_attachEventForObject(anchor,"click",srch_inpSave);

		this.__scopeDropDownTitle2 = row.insertCell();
		this.__scopeDropDownTitle.style.display = "none";

		this.__linkAdvancedContainer = row.insertCell();
		this.__linkAdvancedContainer.align = "right";
		this.__linkAdvancedContainer.style.paddingTop = "5px";
		this.__linkAdvancedContainer.appendChild(this.link_advanced);
		cell = row.insertCell();
		//this.link_advanced.style.paddingLeft = "57px";
		anchor = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
		this.link_advanced.appendChild(anchor);
		anchor.innerText = "Advanced Search";
		anchor.href = "#";
		dom_attachEventForObject(anchor,"click",function(){srch_OpenAdvancedSearchPane();return false;});
		this.Reload();
		return table;
	}]
	,Update : [decl_virtual, function()
	{
		this.Reload(this.__navigationquery == nav_GetNavigationQuery());
		return UI.UpdateStatus.NOUPDATE;
	}]
	,GetScopeDropDownID : function()
	{
		if (!this.ScopeDropDownID)
			this.ScopeDropDownID = this.scopeDropDown.GetClientID();
		return this.ScopeDropDownID;
	}
	,LoadFromConfig : [decl_virtual, function()
	{
		var ssID = this.GetUniqueSearchInputID();
		if (!ssID) return;
		var node = TPSearchInputXML.GetNodeByName(ssID);
		if (!node) return false;
		this.searchText = TPSearchInputXML.GetAttribute("searchbuttontext",node);
		this.showAdvancedSearchLink = eval(TPSearchInputXML.GetAttribute("showadvancedsearch",node));
		this.showSymbolCheckBox = eval(TPSearchInputXML.GetAttribute("showsymbolcheckbox",node));
		this.enablePrompt = eval(TPSearchInputXML.GetAttribute("enableprompt",node));
		this.showRecentSearches = eval(TPSearchInputXML.GetAttribute("showrecentsearches",node));
		this.emptyText = TPSearchInputXML.GetAttribute("emptytext",node);
		return true;
	}]
	,CheckLayout : [decl_virtual, function()
	{
		if (!nav_IsNavigationEnabled() || !this.LoadFromConfig())
			return false;
		var key = this.GetNavigationLocation();
		if (str_IsStringEmpty(key))
			key = this.GetNavigationPID();
		switch(key)
		{
			case PID_MANAGESEARCHES:
			case PID_PLADVANCEDSEARCH:
				return false;
		}
		return true;
	}]
	,SetSearchButtonText : [decl_virtual, function(searchText)
	{
		this.searchbutton.value = searchText;
	}]
	,Reload : [decl_virtual, function(skipReload)
	{
		this.__navigationquery = nav_GetNavigationQuery();
		if (!this.CheckLayout())
		{
			this.SetVisibleState(false);
			return;
		}
		if (skipReload == true) return;
		this.SetVisibleState(true);
		this.base.Reload();
		this.SetSearchButtonText(this.searchText);
		this.recentSearchesPopup.SetVisibleState(this.showRecentSearches);
		if (!this.showAdvancedSearchLink)
		{
			this.link_advanced.style.display = "none";
			this.link_save.style.display = "none";
		}
		if (!this.showSymbolCheckBox)
		{
			this.__ChangeSymbolTypeDisplay(false);
			//this.additional_span.style.display = "none";
		}
		else
		{
			this.__ChangeSymbolTypeDisplay(true);
			//this.additional_span.style.display = "";
		}
		this.InitInput();
		this.ReloadScope();
		this.AnalyzeState()
	}]
	,RegisterLookingForwardInput : function()
	{
		return lf_RegisterControl(this.GetInputControl());
	}
	,ChangeInputStatusInternal : function()
	{
		this.ChangeInputStatus(false);
	}
	,GetFocusHandler : function()
	{
		if (!this.__focushandler)
			this.__focushandler = this.CreateCallback(this.RegisterLookingForwardInput);
		return this.__focushandler
	}
	,GetBlurHandler : function()
	{
		if (!this.__blurhandler)
			this.__blurhandler = this.CreateCallback(this.ChangeInputStatusInternal);
		return this.__blurhandler;
	}
	,InitInput : function()
	{
		this.input.enteredvalue = "";
		var thisObj = this;
		try {dom_detachEventForObject(this.input,"focus",this.GetFocusHandler());}
		catch(e){}
		try {dom_detachEventForObject(this.input,"blur",this.GetBlurHandler());}
		catch(e){}

		var inputcontrol = srch_inpGetCurrentInputSearch();
		if (inputcontrol.GetTag(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME,SRCH_TN_SAVEDSEARCH))) != null)
		{
			this.__ChangeSymbolTypeDisplay(false);
			//this.additional_span.style.display = "none";
			//this.symbolTypeControl.Disable(true);
		}
		else
		{
			if (this.showSymbolCheckBox)
				this.__ChangeSymbolTypeDisplay(true);
			//this.additional_span.style.display = "";
			//this.symbolTypeControl.Disable(false);
		}
		if (this.enablePrompt)
		{
			this.input.parser = this;
			this.SearchEngine = inputcontrol;
			dom_attachEventForObject(this.input,"focus",this.GetFocusHandler());
		}
		else
		{
			this.input.parser = null;
			this.SearchEngine = null;
			dom_attachEventForObject(this.input,"blur",this.GetBlurHandler());
		}
		this.ChangeInputStatus(false);
		this.SetInputValue(srch_GetQueryString());
	}
	,OnControlResize : function()
	{
		//Fix bug "Search button is located under search bar if I reduce the window and Widescreen option is turned on.".(#3680741400001025408)
		if (this.input && this.input.currentStyle && this.input.runtimeStyle)
		{
			var oldpos = this.input.currentStyle.position;
			this.input.runtimeStyle.position = "";
			this.input.runtimeStyle.position = oldpos;
		}
	}
	,OnKeyDown : function()
	{
		if(event.keyCode==13)
		{
			this.__DoSearch();
			this.input.blur();
			return false;
		}
	}
	,ChangeInputStatus : function(active, reinit)
	{
		reinit = reinit == true ? true : false;
		if (!reinit && (this.input.IsActive == active || this.input.isCanceled == false && !active))
		{
			if (!active && str_IsStringEmpty(this.input.enteredvalue))
			{
				this.input.value = this.emptyText;
				this.input.style.color = "#999";
				this.input.IsActive = active;
			}
			return;
		}
		if (this.input.IsActive)
			this.input.enteredvalue = this.input.value;
		this.input.style.color = "#000";
		if (str_IsStringEmpty(this.input.enteredvalue))
		{
			if (active)
				this.input.value = "";
			else
			{
				this.input.style.color = "#999";
				this.input.value = this.emptyText;
			}
		}
		this.input.IsActive = active;
	}
	,GetInputControl : [decl_virtual, function()
	{
		return this.input;
	}]
	,SetInputValue : function(value)
	{
		if (str_IsStringEmpty(value))
			value = "";
		if (!str_IsStringEmpty(this.input.enteredvalue) || !str_IsStringEmpty(value))
		{
			this.input.enteredvalue =
			this.input.value = value;
			this.ChangeInputStatus(this.input.IsActive, true);
		}
	}
	,GetInputValue : function()
	{
		return (this.input.IsActive == true)?this.input.value:this.input.enteredvalue;
	}
	,AppendValueToInput : function(val)
	{
		var inputvalue = this.input.enteredvalue;
		if (!str_IsStringEmpty(inputvalue))
			inputvalue += " ";
		else
			inputvalue = "";
		inputvalue += val;
		this.SetInputValue(inputvalue);
	}
	,ScopeChange : [decl_virtual, function(obj,selectedvalue)
	{
		if (!selectedvalue) return;
		var ssID = this.GetUniqueSearchInputID();
		if (ssID && TPSearchInputXML)
		{
			var node = TPSearchInputXML.GetNodeByName(ssID);
			if (node)
			{
				var last = TPSearchInputXML.GetAttribute("last",node);
				if (last != selectedvalue)
				{
					var npar = nav_currentNavInfo.GetParameter(P_BRANDFILTER);
					if (selectedvalue && selectedvalue.toLowerCase() == BRANDNAME_SNP.toLowerCase())
					{
						if (!npar || npar.toLowerCase() != BRANDNAME_SNP.toLowerCase())
							nav_ChangePageParams(url_MakeParam(P_BRANDFILTER, BRANDNAME_SNP), false);
					}
					else
					{
						if (npar && npar.toLowerCase() == BRANDNAME_SNP.toLowerCase())
							nav_ChangePageParams(P_BRANDFILTER, false);
					}
					srch_ResearchOnNextStep();
					TPSearchInputXML.SetAttribute("last",selectedvalue,node);
				}
			}
		}
	}]
	,GetScopeTagName : [decl_virtual, function()
	{
		return SRCH_TN_CONTAINERSEARCHSCOPE;
	}]
	,AddSpecialFilters : [decl_virtual, function()
	{
		return;
	}]
	,GetScopeForCurrentPage : [decl_virtual, function()
	{
		var ssID = this.GetUniqueSearchInputID();
		if (ssID)
			contid = nav_currentNavInfo.GetContainerLocation();
		if (TPSearchInputXML && contid == null && !IS_ANONYMOUS_USER)
		{
			var node = TPSearchInputXML.GetNodeByName(ssID);
			if (node != null)
			{
				var list = TPSearchInputXML.SelectSingleNode("//" + node.nodeName + "/List");
				if (list)
					return this.__GetScopeValue(node);
			}
		}
		return null;
	}]
	,__ChangeClearLinkDisplay : function(disp)
	{
		this.link_clear.style.display = disp;
	}
	,__ChangeSymbolTypeDisplay : function(disp)
	{
		this.symbolTypeControl.SetVisibleState(disp);
		if (disp)
		{
			this.link_clear.style.paddingLeft = "50px";
			this.link_clear.parentElement.style.paddingTop = "";
		}
		else
		{
			this.link_clear.style.paddingLeft = "235px";
			this.link_clear.parentElement.style.paddingTop = "4px";
		}
	}
	,__GetScopeValue : function(node)
	{
		var res = null;
		if (node)
		{
			var last = TPSearchInputXML.GetAttribute("last",node);
			var deflt = TPSearchInputXML.GetAttribute("default",node);
			if (IS_SNP_USER)
			{
				var bf = nav_currentNavInfo.GetParameter(P_BRANDFILTER);
				if (bf)
					bf = bf.toLowerCase();
				if (bf == BRANDNAME_SNP.toLowerCase())
					last = bf;
				else
					if (last && last.toLowerCase() == BRANDNAME_SNP.toLowerCase())
						last = deflt;
			}
			res = last ? last : deflt;
		}
		return res;
	}
	,ReloadScope : [decl_virtual, function(pid,ploc)
	{
		var scopeid = this.GetScopeDropDownID();
		var scope = gettpDropDownById(scopeid);
		if (!scope) return;
		var contid = null;
		var ssID = this.GetUniqueSearchInputID();
		var pdisp = "";
		if (ssID)
		{
			contid = nav_currentNavInfo.GetContainerLocation();
			pid = this.GetNavigationPID(pid);
			ploc = this.GetNavigationLocation(ploc);
		}
		if (TPSearchInputXML && contid == null && !IS_ANONYMOUS_USER)
		{
			var node = TPSearchInputXML.GetNodeByName(ssID);
			if (node)
			{
				var list = TPSearchInputXML.SelectSingleNode("//" + node.nodeName + "/List");
				if (list)
				{
					pdisp = "";
					if (this.__scopeDropDownContainer.pid != pid || this.__scopeDropDownContainer.location != ploc)
					{
						this.__scopeDropDownContainer.pid = pid;
						this.__scopeDropDownContainer.location = ploc;
						var items = TPSearchInputXML.SelectNodes("//" + node.nodeName + "/List/Item");
						scope.Clear();
						for(var i=0,ic=items.length; i < ic; i++)
							scope.AddValue(TPSearchInputXML.GetAttribute("text",items[i]), TPSearchInputXML.GetAttribute("value",items[i]));
						var width;
						switch(pid)
						{
							case PID_CALENDARS:  width = "165px"; break;
							case PID_FOLDERS: width = "150px"; break;
							case PID_BLOGS: width = "140px"; break;
							default:
								width = "145px";
								if (IS_SNP_USER)
									scope.AddValue("In S&P Headlines", BRANDNAME_SNP.toLowerCase());
								break;
						}
						this.scopeDropDown.SetWidth(width);
					}
					var val = this.__GetScopeValue(node);
					if (val == null)
						val = nav_currentNavInfo.GetParameter(P_PREDEFINEDLOCATION);
					if (!str_IsStringEmpty(val) && str_IsStringEmpty(nav_currentNavInfo.GetParameter(P_CLUSTER_ID)))
						scope.SetValue(val);
					else
						scope.SetValue(TPSearchInputXML.GetAttribute("default",node));
				}
				else
					pdisp = "none";
			}
		}
		else
			pdisp = "none";
		if (srch_inpGetTag(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME,SRCH_TN_SAVEDSEARCH))) != null)
			pdisp = "none";
		if(pid==PID_TRENDS)
			pdisp = "none";
		this.__scopeDropDownTitle.style.display = this.__scopeDropDownContainer.style.display = pdisp;
		if (this.__scopeDropDownTitle2)
			this.__scopeDropDownTitle2.style.display = this.__scopeDropDownTitle.style.display;
		if (pdisp == "none" && this.__linkAdvancedContainer)
		{
			this.__linkAdvancedContainer.align = "";
		}
		else
		{
			this.__linkAdvancedContainer.align = "right";
		}
	}]
	,AnalyzeState : function()
	{
		this.AnalyzeSearchState()
		this.AnalyzeClusterState();
		if (!this.AllowSaveSearch())
			this.link_save.style.display = "none";
	}
	,AnalyzeSearchState : function()
	{
		if (srch_inpGetState() == SRCH_SES_NONE)
		{
			this.__searchinprogress = false;
			this.__ChangeClearLinkDisplay("none");
			/*if (this.showAdvancedSearchLink)
				this.link_advanced.style.display = "";*/
		}
		else
		{
			this.__searchinprogress = true;
			this.__ChangeClearLinkDisplay("");
			//this.link_advanced.style.display = "none";
		}

		if (this.showAdvancedSearchLink)
		{
			if (srch_inpGetTag(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME, SRCH_TN_SAVEDSEARCH))) != null)
				this.link_save.style.display = "none";
			else
				this.link_save.style.display = "";
		}
		else
			this.link_save.style.display = "none";
	}
	,AnalyzeClusterState : function()
	{
		if (this.showAdvancedSearchLink)
		{
			var cluster_id = nav_currentNavInfo.GetParameter(P_CLUSTER_ID);
			this.link_advanced.style.display = !str_IsStringEmpty(cluster_id) ? "none" : "";//(this.__searchinprogress ? "none" : "");
			if (!str_IsStringEmpty(cluster_id))
			{
				if (this.link_save.style.display != "none")
					this.link_save.olddisplay = this.link_save.style.display;
				this.link_save.style.display = "none";
			}
			else
			{
				if (this.link_save.olddisplay)
					this.link_save.style.display = this.link_save.olddisplay;
			}
		}
		else
		{
			this.link_save.style.display = "none";
			this.link_advanced.style.display = "none";
		}
	}
	/*parser section (use for prompting)*/
	,CancelPrompt : function(allowClearValues)
	{
		this.ChangeInputStatus(false);
		if (this.SearchEngine)
			this.SearchEngine.CancelPrompt(allowClearValues);
	}
	,Parse : function(value,pos)
	{
		if (this.SearchEngine)
			return this.SearchEngine.Parse(value,pos);
		return null;
	}
	,AddPrompt : function(tagname,displayvalue,tagid,item)
	{
		if (this.SearchEngine)
			this.SearchEngine.AddPrompt(tagname,displayvalue,tagid,item);
	}
	,Dispose : [decl_virtual, function()
	{
		this.base.Dispose();
		this.input = null;
	}]
	,__GetInputCssClass : [decl_virtual, function()
	{
		return "search-query";
	}]
	,__GetDropDownTitleHtml :[decl_virtual, function()
	{
		return "";
	}]
	,__DoSearch :[decl_virtual, function()
	{
		srch_inpLoadQueryString();
		return false;
	}]
});

DeclareClass("UI.Searches.SearchActions", "UI.Controls.DropDown",
{
	SetSearchID : function(searchID)
	{
		this.__searchID = searchID;
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.changeHandler = this.CreateCallback(this.OnChange);
		this.AttachEvent("onselected", this.changeHandler);
		this.LoadItems();
		this.SetCssClass("search-filter-actions");
	}]
	,LoadItems: [decl_virtual, function()
	{
		this.AddItem("Action...","");
		this.AddItem("Run Search", "0");
		this.AddItem("Modify", "1");
		this.AddItem("Delete", "2");
	}]
	,OnChange : function()
	{
		switch(this.SelectedValue)
		{
			case "0":
				srch_RunSearch(this.__searchID);
				break;
			case "1":
				srch_LoadSearch(this.__searchID);
				break;
			case "2":
				do_deleteSearch(this.__searchID);
				break;
			default:
				return;
		}
		this.SetSelectedValue("");
		return false;
	}
	,Dispose :[decl_virtual, function()
	{
		this.DetachEvent("onselected", this.changeHandler);
	}]
});

DeclareClass("AlertGlobalObject", null,
{
	constructor: function()
	{
		this.__eventContainer = new cmn_EventContainer();
		this.FireMethod = this.CreateCallback(this.__eventContainer.fireEvent);
		this.Listener = new Utils.SavedSearchEventListener([SRCH_TN_SAVEDSEARCH],this.CreateCallback(this.__LoadAlert));
		this.Listener.Attach();
	}
	,MarkAlertDelete: function(searchId)
	{
		this.__MarkAlertDelete = searchId!=srch_advGetDecimalSearchID();
		if(!this.__MarkAlertDelete)
			this.DeleteAlert(srch_advGetDecimalAlertID());
	}
	,MarkAlertCreate: function(searchId)
	{
		this.__MarkAlertCreate = searchId!=srch_advGetDecimalSearchID();
		if(!this.__MarkAlertCreate)
		{
			var alert = data_createEmptyItem(AlertItem);
			alert.SetNodeValue(AlertItem.PN_SEARCHID, searchId);
			this.SaveAlert(alert);
		}
	}
	,__LoadAlert: function()
	{
		var alertID = srch_advGetDecimalAlertID();
		var searchID = srch_advGetDecimalSearchID();
		if(this.__MarkAlertCreate && alertID == 0){
			this.MarkAlertCreate(searchID);
			return;
		}
		if(this.__MarkAlertDelete && alertID > 0){
			this.MarkAlertDelete(searchID);
			return;
		}

		if(alertID>0)
			this.LoadAlert(alertID);
		else
		{
			this.FireMethod("OnBeginRequest", "Load");
			this.FireMethod("OnRequestComplete", "Load");
		}
	}
	,LoadAlert: function(alertId, callBack)
	{
		this.__DoCommand(httpcmd_GetAlertSubscription, "Load", alertId, callBack);
	}
	,SaveAlert: function(alert, callBack)
	{
		Utils.MonitoringHelper.SetMonitoringInfo(MA_SaveAlert);
		this.__DoCommand(httpcmd_SetAlertSubscription, "Save", alert, callBack);
	}
	,DeleteAlert: function(alertId, callBack)
	{
		Utils.MonitoringHelper.SetMonitoringInfo(MA_DeleteAlert);
		this.__DoCommand(httpcmd_DeleteAlert, "Delete", alertId, callBack);
	}
	,__DoCommand: function(command, commandType, param, callBack)
	{
		var fire = this.FireMethod;
		fire("OnBeginRequest", commandType, param);
		new command(param,
			function(result){if(callBack)callBack(result); fire("OnRequestComplete", commandType, result);},
			function(){fire("OnError", commandType);});
	}
	,AttachEvent: function(evtname, func){ return this.__eventContainer.attachEvent(evtname, func); }
});

var __AlertGlobalObject;
function __GetAlertGlobalObject(){ return __AlertGlobalObject||(__AlertGlobalObject = new AlertGlobalObject());}


DeclareClass("UI.Searches.AlertAction", "UI.Controls.CollapsibleControl",
{
	constructor: function()
	{
		this.base(true);
		this.createContent = true;
		__GetAlertGlobalObject().AttachEvent("OnBeginRequest", this.CreateCallback(this.OnBeginRequest));
		__GetAlertGlobalObject().AttachEvent("OnRequestComplete", this.CreateCallback(this.OnRequestComplete));
		__GetAlertGlobalObject().AttachEvent("OnError", this.CreateCallback(this.OnError));
	}
	,GetCurrentAlert: function(param)
	{
		var currentSearchId = srch_advGetDecimalSearchID();
		var currentAlertId = srch_advGetDecimalAlertID();
		if(param==null || param == currentAlertId || param.getValue&&param.getValue(AlertItem.PN_SEARCHID) == currentSearchId)
			return param;
		if(param instanceof Array)
			for(var i=0; i<param.length; i++)
				if(param[i]==currentAlertId || param[i].getValue && param[i].getValue(AlertItem.PN_SEARCHID) == currentSearchId)
					return param[i];
		return null;
	}

	,OnBeginRequest: function(type, param)
	{
		if(param && !this.GetCurrentAlert(param))
			return;
		this.__ApplyFiltersByType(UI.SearchAlertFilter);
		this.Lock();
		if(type!="Delete" && param )
			this.Expand(null, true);
		else
			if (this.__allowCollapse)
				this.Collapse(null, true, type);
	}
	,OnRequestComplete: function(type, param)
	{
		var alert = this.GetCurrentAlert(param);
		if(param && !alert) return;
		this.Unlock();
		srch_advSetSearchAlertId(alert && alert.getValue && alert.getValue(AlertItem.PN_ID)||0);
		alert =  (alert&&alert.IsInstanceOf&&alert.IsInstanceOf(data_XmlDataItem))?alert:null;
		if(this.__contentControl)
			this.__contentControl.SetData(alert);
		else
			this.alert = alert||null;
	}
	,OnError: function(type) { this.Unlock(); }
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.AddUIControlToHeader(new UI.Searches.AlertActionHeader(this));
		if(this.createContent){
			this.__contentControl = new UI.Searches.AlertsControl();
			this.Listeners.AddObjectListener(this.__contentControl, "OnChange", __GetAlertGlobalObject().CreateCallback(__GetAlertGlobalObject().SaveAlert));
			this.AddUIControlToContent(this.__contentControl);
			this.ContentControl.SetCssClass("lmodule-subitem-first lmodule-row");
		}
		this.SetCssClass("lmodule-bseparate lmodule-bottom");
		if(typeof(this.alert)!='undefined'){
			if(this.__contentControl)
				this.__contentControl.SetData(this.alert);
			if(this.alert== null)
				this.Collapse(null, true);
		}
	}]

	,Render : [decl_virtual, function()	{ this.base.Render(); this.__allowCollapse = true; }]
	,Collapse : [decl_virtual, function(fireevent, donotdelete)
	{
		if(!donotdelete)
		{
			var alert = this.__contentControl.GetData();
			if(alert && alert.getValue(AlertItem.PN_ID)!="0")
				__GetAlertGlobalObject().DeleteAlert(alert.getValue(AlertItem.PN_ID));
		}
		else
			this.base.Collapse(fireevent);
	}]
	,Expand : [decl_virtual, function(fireevent, dontCreate)
	{
		if(!dontCreate)
		{
			var alert =  data_createEmptyItem(AlertItem);
			alert.SetNodeValue(AlertItem.PN_SEARCHID, srch_advGetDecimalSearchID());
			__GetAlertGlobalObject().SaveAlert(alert);
		}else
			this.base.Expand(fireevent);
	}]
});
DeclareClass("UI.Searches.AlertActionHeader", "UI.Control",
{
	constructor: function(collapsibleParent)
	{
		this.base();
		this.CollapsibleParent = collapsibleParent;
	}
	,GetTagName : function() {return UI.HtmlTag.Div;}
	,Init : [decl_virtual, function()
	{
		this.__image = new UI.Controls.CollapsibleImageControl("icon-alert-off.gif","icon-alert-on.gif",this.CollapsibleParent.Expanded,this.CollapsibleParent);
		this.__checkbox = new UI.Controls.CollapsibleCheckBoxControl(this.CollapsibleParent.Expanded,this.CollapsibleParent,"Enable Alert");
		this.AddControl(this.__image);
		this.AddControl(this.__checkbox);
	}]
	,Render : [decl_virtual, function(writer)
	{
		var div = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		this.HostElement.appendChild(div);
		div.className = "lmodule-title lmodule-purple";
		this.__image.RenderControl(div);
		this.__image.HostElement.style.marginRight = "3px";
		this.__image.HostElement.style.cursor = "pointer";
		var span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);
		span.innerText = "Alert";
		div.appendChild(span);
		div = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
		div.className = "lmodule-row";
		this.HostElement.appendChild(div);
		this.__checkbox.RenderControl(div);
	}]
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.NOUPDATE;}]
});

DeclareClass("UI.Searches.AlertsControl", "UI.Control",
{
	Init : [decl_virtual, function()
	{
		this.__AlertSubscription;
		var thisObj = this;
		var createDD = function(){
			var dd = new UI.Controls.DropDown();
			dd.SetCssClass("lmodule-search-block-select ddBlock");
			thisObj.Listeners.AddObjectListener(dd, "onselected", thisObj.Save);
			return dd;
		}
		var createText = function(text){
			var ctl = new UI.Controls.LiteralControl(text);
			ctl.SetCssClass("lmodule-search-block-text");
			return ctl;
		}
		this.AddControl(createText("Type:")); this.AddControl( this.cbType = createDD());
		this.AddControl(createText("How often:")); this.AddControl( this.cbRecurrence = createDD());
		this.AddControl(createText("To E-Mail:")); this.AddControl( this.cbEmail = createDD());
		this.FillData();
		evnt_SubscribeOnEvent(EVT_EMAILLIST_UPDATED, this.CreateCallback(this.FillEmails));
	}]

	,Save: function(){ this.FireEvent("OnChange", this.GetData()); }

	,FillData: function()
	{
		var alertTypes = CREData.AlertType().GetValues();
		this.cbType.Clear();
		for(var i=0; i<alertTypes.length; i++)
			this.cbType.AddItem(CREData.AlertType().GetDisplayValue(alertTypes[i]), alertTypes[i]);

		var alertRecurrence = CREData.AlertRecurrence().GetValues();
		this.cbRecurrence.Clear();
		for(var i=0; i<alertRecurrence.length; i++)
			this.cbRecurrence.AddItem(CREData.AlertRecurrence().GetDisplayValue(alertRecurrence[i]), alertRecurrence[i]);

		this.cbEmail.Clear();
		this.cbEmail.AddItem("Loading...", "");
		new httpcmd_GetDataSource("MyEmails", this.CreateCallback(this.FillEmails));
	}
	,FillEmails: function(xml)
	{
		this.cbEmail.Clear();
		if(!xml.SelectNodes)
			xml = new Xml.NodeAccessor(xml);
		var nodes = xml.SelectNodes("//email");
		for(var i=0; i<nodes.length; i++)
			this.cbEmail.AddItem(nodes[i].text, nodes[i].text);
		this.ApplyAlert();

	}
	,ApplyAlert: function()
	{
		if(this.__AlertSubscription)
		{
			this.cbType.SetSelectedValue(this.__AlertSubscription.getValue(AlertItem.PN_TYPE_INT), false);
			var isDesktop = this.cbType.SelectedValue == CREData.AlertType().Desktop;
			if(isDesktop){
				this.cbRecurrence.SetSelectedValue(CREData.AlertRecurrence().AsTheyHappen ,false);
				this.cbRecurrence.Lock(); this.cbEmail.Lock();
			}else{
				this.cbRecurrence.SetSelectedValue(this.__AlertSubscription.getValue(AlertItem.PN_RECURRENCE_INT),false);
				this.cbEmail.SetSelectedValue(this.__AlertSubscription.getValue(AlertItem.PN_EMAIL),false);
				this.cbRecurrence.Unlock(); this.cbEmail.Unlock();
			}
		}
		if(!this.cbEmail.SelectedValue)
				this.cbEmail.Select(0, false);
	}

	,SetData: function(alert)
	{
		this.__AlertSubscription = alert;
		if(alert)
			this.ApplyAlert();
	}
	,GetData: function()
	{
		if(this.__AlertSubscription)
		{
			this.__AlertSubscription.SetNodeValue(AlertItem.PN_TYPE_INT, this.cbType.SelectedValue);
			this.__AlertSubscription.SetNodeValue(AlertItem.PN_RECURRENCE_INT, this.cbRecurrence.SelectedValue);
			this.__AlertSubscription.SetNodeValue(AlertItem.PN_EMAIL, this.cbEmail.SelectedValue||"");
		}
		return this.__AlertSubscription;
	}
});

DeclareClass("UI.Searches.ScrollableAlertsInputControl", "SiteLayout.InputSearchControl",{
	constructor: function(){
		this.base();
		this.__selectedAlertSource = null;
	}
	,CheckLayout : [decl_virtual, function(){
		return true;
	}]
	,LoadFromConfig : [decl_virtual, function(){
		this.searchText = "Search";
		this.showAdvancedSearchLink = false;
		this.showSymbolCheckBox = false;
		this.enablePrompt = true;
		this.showRecentSearches = false;
		return true;
	}]

	,ReloadScope : [decl_virtual, function(pid,ploc, customReload, xmlobj){
		var alertsDD = this.scopeDropDown;
		if(xmlobj){
			var needRefresh = alertsDD.dropDownItems.length !=(xmlobj.GetCount()+1) || alertsDD.__isLoading;
			if(!needRefresh)
				for (var i=0, xItem; xItem = xmlobj.GetByIndex(i); i++){
					var item = alertsDD.dropDownItems[i+1];
					if(item && (item.value!=xItem.GetNodeValue(AlertItem.PN_ID) || item.name!=xItem.GetNodeValue(AlertItem.PN_SOURCE_NAME))){
						needRefresh = true;
						break;
					}
				}
			if(needRefresh){
				alertsDD.Clear();
				alertsDD.AddItem(IS_TMC_USER?"All Profiles":"All Alerts","").className += " alerts_allsearch";
				for (var i=0, xItem; xItem = xmlobj.GetByIndex(i); i++)
					alertsDD.AddItem(xItem.GetNodeValue(AlertItem.PN_SOURCE_NAME),xItem.GetNodeValue(AlertItem.PN_ID)).className += (" al"+xItem.GetNodeValue(AlertItem.PN_ID) + " wsa_grid_background alerts_search_padding");
				alertsDD.SetSelectedValue(this.__selectedAlertSource||"");
			}
			alertsDD.__isLoading = false;
		}else{
			if(customReload  || alertsDD.dropDownItems.length==0){
				if(alertsDD.dropDownItems.length == 0){
					alertsDD.AddItem("Loading...", "");
					alertsDD.SetSelectedValue("");
					alertsDD.__isLoading = true;
				}
				new httpcmd_GetAlertSubscriptions(this.ReloadScope.bind(this, null, null, true));
			}
		}

	}]
	,GetScopeTagName : [decl_virtual, function(){
		return SRCH_TN_ALERTSUBSCRIPTIONID;
	}]
	,GetScopeForCurrentPage : [decl_virtual, function(){
		return this.__selectedAlertSource;
	}]
	,AddSpecialFilters : [decl_virtual, function(){
		if (IS_TMC_USER)
			this.TmcCategorySearch(false);
		return;
	}]
	,ScopeChange : [decl_virtual, function(obj,selectedvalue){
		selectedvalue = selectedvalue || null;
		if (selectedvalue != this.__selectedAlertSource){
			obj.HostElement.firstChild.className = selectedvalue?"dd wsa_grid_background":"dd";
			obj.HostElement.firstChild.children[1].className = selectedvalue?("ddIptRo ddBlock wsa_grid_font_color al"+selectedvalue):"ddIptRo ddBlock";
			this.__selectedAlertSource = selectedvalue;
			this.__DoSearch();
		}
	}]
	,Render :[decl_virtual, function(writer){
		var table, row, cell, span, anchor;

		table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		table.style.tableLayout = "fixed";
		this.HostElement.appendChild(table);
		row = table.insertRow();

		cell = row.insertCell();
		cell.className = "wsa_search_action_bold wsa_search_scol";
		cell.innerHTML = "Search:&nbsp;";

		this.input.className = this.__GetInputCssClass();
		this.input.setAttribute("popup-width","310px");
		if (!IS_TMC_USER){
			cell = row.insertCell();
			cell.className = "wsa_search_iptcol";
			cell.appendChild(this.input);
			this.__scopeDropDownTitle = row.insertCell();
			this.__scopeDropDownTitle.innerHTML = "<span class='wsa_search_action_bold'>&nbsp;in&nbsp;</span>";
			this.__scopeDropDownContainer = row.insertCell();
		}else{
			this.__scopeDropDownContainer = row.insertCell();
			this.__scopeDropDownTitle = row.insertCell();
			this.__scopeDropDownTitle.innerHTML = "<span class='wsa_search_action_bold'>&nbsp;for&nbsp;</span>";
			cell = row.insertCell();
			cell.className = "wsa_search_iptcol";
			cell.appendChild(this.input);
		}
		this.__scopeDropDownTitle.className = "wsa_search_ddtitlecol";
		this.__scopeDropDownContainer.className = "wsa_search_ddcol"

		this.scopeDropDown.RenderControl(this.__scopeDropDownContainer);
		this.scopeDropDown.dropDownObject.BorderCss = "scrlaBorder";
		this.scopeDropDown.dropDownObject.attachEvent('onlistopen', this.ReloadScope.bind(this, null, null, true, null));
		this.scopeDropDown.SetWidth("120");
		new dom_DOMObject(this.scopeDropDown.dropDownObject.GetListElement()).applyClass("alerts_search_padding wsa_grid_font_color");

		cell = row.insertCell();
		cell.style.paddingLeft = "0";
		cell.className = "wsa_search_btncol";
		dom_attachEventForObject(this.searchbutton,"click",this.CreateCallback(this.__DoSearch));
		cell.appendChild(this.searchbutton);

		this.__ChangeClearLinkDisplay("none");
		this.link_clear.className = "blue";
		if (!IS_TMC_USER){
			cell = row.insertCell();
			cell.className = "wsa_search_clearcol";
			cell.appendChild(this.link_clear);
		}

		//this.link_clear.appendChild(this.additional_span);
		anchor = DOMObjectFactory.CreateElement(UI.HtmlTag.A);
		this.link_clear.appendChild(anchor);
		anchor.innerText = "Clear";
		anchor.href = "#";
		anchor.className = "wsa_link";
		dom_attachEventForObject(anchor,"click",function(){srch_ClearSearchResults(true);});
		this.Reload();

		if (IS_TMC_USER){
			cell = row.insertCell();
			cell.className = "wsa_tmc_dispaly_section";
			cell.innerHTML = "<div class='wsa_search_action_bold'>Display</div>";
			cell = row.insertCell();
			var div = DOMObjectFactory.CreateElement(UI.HtmlTag.Div);
			div.className = "wsa_search_displaycol";
			cell.appendChild(div);
			var handler = this.CreateCallback(this.TmcCategorySearch);
			this.cb_research = this.__appendCheckbox(div, "Research", "rsch", "47px", handler, true);
			this.cb_models = this.__appendCheckbox(div, "Models", "mdl", "35px", handler, true);
			this.cb_news = this.__appendCheckbox(div, "News", "news", null, handler, true);
			div.appendChild(DOMObjectFactory.CreateElement(UI.HtmlTag.BR));
			/*this.cb_estimates = this.__appendCheckbox(div, "Estimates", "est", "47px", handler, true);
			this.cb_filings = this.__appendCheckbox(div, "Filings", "flng", "35px", handler, true);
			this.cb_events = this.__appendCheckbox(div, "Events", "evt", null, handler, true);*/
		}

		this.OnControlResize();
		return table;
	}]
	,TmcCategorySearch : function(allowSearch){
		srch_inpDeleteFilters(SRCH_TN_ALERTTYPEFLAGS);
		var allchecked =	this.cb_research.checked &&
							this.cb_models.checked &&
							this.cb_news.checked/* &&
							this.cb_estimates &&
							this.cb_filings &&
							this.cb_events*/;
		var allunchecked = !(	this.cb_research.checked ||
								this.cb_models.checked ||
								this.cb_news.checked/* ||
								this.cb_estimates ||
								this.cb_filings ||
								this.cb_events*/);
		if (allchecked || allunchecked){
		}
		else{
			if (this.cb_research.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_TMC_RESEARCH, null, true);
			if (this.cb_models.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_TMC_MODELS, null, true);
			if (this.cb_news.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_INFONGEN_NEWS, null, true);
			/*if (this.cb_estimates.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_TMC_ESTIMATES, null, true);
			if (this.cb_filings.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_TMC_FILINGS, null, true);
			if (this.cb_events.checked)
				srch_inpAddFilter(SRCH_TN_ALERTTYPEFLAGS, AC_TMC_EVENTS, null, true);*/
		}
		if (allunchecked)
			IMPOSSIBLESEARCH = true;
		else
			IMPOSSIBLESEARCH = false;
		if (allowSearch != false)
			window.setTimeout(srch_inpDoSearch,1);
	}
	,__ChangeSymbolTypeDisplay: function(disp){
		this.symbolTypeControl.SetVisibleState(disp);
	}
	,__appendCheckbox: function(writer, title, id, labelwidth, handler, checked){
		var cb = DOMObjectFactory.CreateElement(UI.HtmlTag.Input);
		cb.type = "checkbox";
		var id = this.GetClientID() + id;
		cb.id = id
		writer.appendChild(cb);
		cb.checked = !!checked;
		if (handler)
			dom_attachEventForObject(cb,"click",handler);
		var label = DOMObjectFactory.CreateElement(UI.HtmlTag.Label);
		label.style.display = "inline-block";
		label.htmlFor = id;
		label.innerText = title;
		if (labelwidth)
			label.style.width = labelwidth;
		writer.appendChild(label);
		return cb;
	}
	,Dispose :[decl_virtual, function() {
		this.base.Dispose();
		this.cb_research =
		this.cb_models  =
		this.cb_news =
		/*this.cb_estimates =
		this.cb_filings =
		this.cb_events = */null;
	}]
	,__DoSearch :[decl_virtual, function(){
		if (IS_TMC_USER){
			srch_inpLoadQueryString(null,this.CreateCallback(this.TmcCategorySearch));
			return false;
		}
		else
			return this.base.__DoSearch();
	}]
});
//--- collection of objects
var metaTMCs = [];

metaTMCs.GetById = function(id)
{
	for (var i = 0; i < this.length; ++i)
	{
		var item = this[i];
		if (item.Id == id) return item;
	}
	return null;
};

//--- metaTMCItem --
function metaTMCItem(parent, id, tp, cache, clientControl)
{
	this.Parent = parent;
	this.Id = id;
	this.Type = tp;
	this.Cache = (!cache) ? [] : cache;
	this.ClientControl = (typeof(clientControl) != "undefined") ? clientControl : null;
}
metaTMCItem.prototype = new Object();
metaTMCItem.prototype.constructor =  metaTMCItem;
function GetCacheSubItems(ctrl, cacheKey)
{
	var selectedElements = mtmc_getValue(ctrl);
	var elements = [];
	var cacheElements = ctrl.Cache;
	if(typeof(cacheKey) != "undefined")
		cacheElements = cacheElements[cacheKey];
	for (var i = 0, ic = cacheElements.length; i < ic; ++i)
	{
		var cacheEl = cacheElements[i];
		for (var j = 0, jc = selectedElements.length; j < jc; ++j)
		{
			var selectedEl = selectedElements[j];
			if (ctrl.Parent.GetCacheObjValue(cacheEl) == selectedEl.value)
			{ 
				for (var k = 0, kc = cacheEl.subitems.length; k < kc; ++k)
					elements.push(cacheEl.subitems[k]);
				continue;
			}
		}
	}
	return elements;
};

//--- object declaration
function metaTMC(id, cache, textParam, valueParam, isClient)
{
	this.Id = id;
	this.Cache = cache;
	this.textParam = textParam == null ? "text" : textParam;
	this.valueParam = valueParam == null ? "value" : valueParam;
	this.SubControls = [];
	this.IsClient = (typeof(isClient) != "undefined") ? isClient : false;
	
	this.SubControlsAdd = function(id, type, cache, clientControl)
	{
		var item = new metaTMCItem(this, id, type, cache, clientControl);
		for(var i = 0, ic = this.SubControls.length; i < ic; i++)
		{
			if(this.SubControls[i].Id == id)
			{
				this.SubControls[i] = item;
				return;
			}
		}
		this.SubControls.push(item);
	};
}
metaTMC.prototype = new Object();
metaTMC.prototype.contructor = metaTMC;
metaTMC.prototype.GetSelected = function()
{
	return (this.LastSelected != null) ? mtmc_getValue(this.LastSelected) : null;
	/*
	var last_selected = null;
	for(var i=0; i<this.SubControls.length; i++)
	{
		var obj = this.SubControls[i];
		var current_values = mtmc_getValue( obj );
		if( current_values.length == 0 ) 
			break; 
		else
			last_selected = current_values;
	}
	return last_selected;
	*/
};

metaTMC.prototype.GetCacheObjValue = function( cacheObj )
{
	if (cacheObj == null) 
		return null;
	switch( this.valueParam )
	{
		case 'value': return cacheObj.value;
		case 'code': return cacheObj.code;
		case 'symbiol': return cacheObj.symbol;
		default: //-- slowest variant
			eval( "return cacheObj."+valueParam+";" );
	}
};

metaTMC.prototype.GetCacheObjDisplayValue = function( cacheObj )
{
	if (cacheObj == null)
		return null;
	switch( this.textParam )
	{
		case 'text': return cacheObj.text;
		case 'name': return cacheObj.name;
		default: //-- slowest variant
			eval( "return cacheObj."+valueParam+";" );
	}
};

//-------------------------------------  FUNCTIONS -----------------------------
function metaTMCValue( id )
{
	var item = metaTMCs.GetById( id );
	if( item != null )
	{
		return item.GetSelected();
	}
	return null;
}

function CreateMTMC( id, cache, textParam, valueParam, isClient )
{
	var mtmc = mtmc_getById( id );
	if(!mtmc)
	{
		mtmc = new metaTMC(id, cache, textParam, valueParam, isClient);
		metaTMCs.push(mtmc);		
	}
	return mtmc;
}

//---------------------------- EXTERNAL ONSELECTED FUNCTION -------
function mtmc_OnSelected( id, level, useUnfiltered, cacheKey )
{
	var mtmc = mtmc_getById( id );
	if( level >=-1 && level < mtmc.SubControls.length )
	{
		if( level !=  mtmc.SubControls.length -1 )
		{
			if(typeof(cacheKey) != "undefined")
				FillMTMC( id, level, false, cacheKey );
			else				
				FillMTMC( id, level );
		}
		if( level != -1 )
			mtmc.LastSelected = mtmc.SubControls[ level ];
	}
}
//---------------------------- FILLING ITEMS -----------------------
function FillMTMC(id, level, useUnfiltered, cacheKey)
{
	var control = mtmc_getById(id);
	if (!control) 
		return;
		
	var subControl = control.SubControls[level + 1];
	if (!subControl) 
		return;
		
	if (level == -1)
	{
		FillMTMCSubControl(subControl, control.Cache, useUnfiltered, cacheKey);
		subControl.Cache = control.Cache;
	}
	else
	{
		//-- finding cache entries to fill
		var parentControl = control.SubControls[level];
		if (!parentControl) 
			return;
		
		var controlSelectedValues = GetCacheSubItems(parentControl, cacheKey);
		subControl.Cache = controlSelectedValues;
		FillMTMCSubControl(subControl, controlSelectedValues);
				
		//-- cleaning subcontrols
		for (var i = level + 2, ic = control.SubControls.length; i < ic; ++i)	
			FillMTMCSubControl(control.SubControls[i], []);
	}
}
//---------------------------- COMMON -----------------------------

function mtmc_StringSubSort(str1, str2)
{
	var s1 = str1.text.trim().toLowerCase(), 
		s2 = str2.text.trim().toLowerCase();
		
	if (s1 > s2) 
		return 1;
	else if (s1 < s2)
		return -1;
	return 0;
}

function FillMTMCSubControl(subControl, cache, includeUnfiltered, cacheKey)
{
	var cacheObject = cache;
	if(cache!=null)
		if(typeof(cacheKey) != "undefined")
			cacheObject = cache[cacheKey];	
	
	var parent = subControl.Parent;
	switch(subControl.Type)
	{
		case 'lb': // list box
			var result = [];
				
			for (var i = 0, ic = cacheObject.length; i < ic; i++) 
				result.push(new select_Item(parent.GetCacheObjDisplayValue(cacheObject[i]), parent.GetCacheObjValue(cacheObject[i])));
			
			if (parent.IsClient)
			{
				//in this case the async. mode may be used 
				var control = subControl.ClientControl;
				if (!control) return;
				control.Clear();
				if (control.IsSorted())
					result = result.sort(mtmc_StringSubSort);
					
				for (var i = 0, ic = result.length; i < ic; ++i)
					control.AddValue(result[i].text, result[i].value, null, false);
			}
			else
			{
				tplb_list_population(subControl.Id, result, true);
			}
			
			break;
		case 'dd': // drop down list
			if (!parent.IsClient) 
			{
				var dd = gettpDropDownById(subControl.Id);
				
				if (includeUnfiltered)
					dd.AddValue('Unfiltered', '');
				
				for(var i = 0, ic = cacheObject.length; i < ic; ++i)	
					dd.AddValue(parent.GetCacheObjDisplayValue(cacheObject[i]), parent.GetCacheObjValue(cacheObject[i]));
				
				if (includeUnfiltered)
					dd.SetValue('');
			}
			else
			{
				var control = subControl.ClientControl;
				if (!control) return;
				
				if (includeUnfiltered)
					control.AddItem('Unfiltered', '');
					
				for(var i = 0, ic = cacheObject.length; i < ic; ++i)	
					control.AddItem(parent.GetCacheObjDisplayValue(cacheObject[i]), parent.GetCacheObjValue(cacheObject[i]));
				
				if (includeUnfiltered)
					control.SetSelectedValue('');
			}
			
			break;
	}
}
//-------------------------- retrieves a value array for a subcontrol ----
function mtmc_getValue( control )
{
	var values = new Array();
	switch( control.Type )
	{
		case 'lb':
			var lbValues = tplb_GetSelectedItems( control.Id );
			if( lbValues != null ) values = lbValues;
			break;
		case 'dd':
			var ddObj = gettpDropDownById( control.Id );
			if( ddObj.GetValue() != '' )
			values.push( new select_Item(ddObj.GetDisplayValue(),ddObj.GetValue()));
			break;
	}
	return values;
}

function mtmc_getById( mtmcId )
{
	return metaTMCs.GetById( mtmcId );
}

//----------------------- copies values of this control to other listbox---
function mtmc_CSLB( mtmcId, lbId )
{
	var mtmc = mtmc_getById( mtmcId );
	if( mtmc == null ) return;
	var mtmcValues = mtmc.GetSelected();
	if( mtmcValues == null ) return;
	for( var i=0; i<mtmcValues.length; i++ )
		tplb_AddRow(lbId,  mtmcValues[i].text, mtmcValues[i].value );
}



DeclareNamespace("AS");
DeclareNamespace("UI.AS");
//------------------ Scope -------------------------
DeclareEnum("UI.AS.Scope", {Any: "Any", All: "All", ExcludeAny: "Excl. any"});

function uiasc_GetDisplayScopeByValue(v, tn, postfix) {
	switch(v) {
		case SRCH_TS_ALL: return UI.AS.Scope.All;
		case SRCH_TS_EXCLUDEANY: return "None" + (postfix ? postfix : "")
		default: return UI.AS.Scope.Any;
	}
}
function uiasc_GetServerByClientScope(v) {
	switch(v) {
		case UI.AS.Scope.All: return SRCH_TS_ALL;
		case UI.AS.Scope.ExcludeAny: return SRCH_TS_EXCLUDEANY;
		default: return SRCH_TS_ANY;
	}
}
function uiasc_GetClientByServerScope(v) {
	switch(v) {
		case SRCH_TS_ALL: return UI.AS.Scope.All;
		case SRCH_TS_EXCLUDEANY: return UI.AS.Scope.ExcludeAny;
		default: return UI.AS.Scope.Any;
	}
}
//-------------------- EventListener -------------------------
DeclareClass("AS.EventListener", "Utils.EventListenerBase", {
	constructor: function(handler, ext) {
		this.base(null, null, handler)
		this.__hdl = this.CreateCallback(this.OnEvent);
		this.__ext = ext;
	}
	,Dispose: [decl_virtual, function() {
		this.Detach();
		this.__hdl = null;
		this.base.Dispose();		
	}]
	,Attach: function() {
		if (this.__ext)
			GlobalAdvancedSearchEventManager.AttachEvent("onclear", this.__hdl);	
		GlobalAdvancedSearchEventManager.AttachEvent("onxmlchange", this.__hdl);	
		GlobalAdvancedSearchEventManager.AttachEvent("ontagdelete", this.__hdl);	
	}	
	,Detach: function() {
		if (this.__ext)
			GlobalAdvancedSearchEventManager.DetachEvent("onclear", this.__hdl);	
		GlobalAdvancedSearchEventManager.DetachEvent("onxmlchange", this.__hdl);
		GlobalAdvancedSearchEventManager.DetachEvent("ontagdelete", this.__hdl);	
	}
	,OnEvent: function() { this.Handler(this) }
});
DeclareClass("AS.EventClearListener", "Utils.EventListenerBase", {
	constructor: function(handler) {
		this.base(null, null, handler)
		this.__hdl = this.CreateCallback(this.OnEvent);
	}
	,Dispose: [decl_virtual, function() {
		this.Detach();
		this.__hdl = null;
		this.base.Dispose();		
	}]
	,Attach: function() {
		GlobalAdvancedSearchEventManager.AttachEvent("onclear", this.__hdl);	
	}	
	,Detach: function() {
		GlobalAdvancedSearchEventManager.DetachEvent("onclear", this.__hdl);	
	}
	,OnEvent: function() { this.Handler(this) }
});
//------------------ Handler ---------------------- 
DeclareClass("AS.Handler", null, {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.moduleForm = moduleForm;
		this.Listeners = new Utils.EventListenersManager(this);
		
		this.tagName = tagName;
		this.tagDisplayName = tagDisplayName;
		this.tagType = tagType;
		this.tagScope = tagScope;
		
		this.attributes = [];
		this.AddAttributes();
		
		if (!AS.Handler.HandlersCollection)
			AS.Handler.HandlersCollection = [];
		AS.Handler.HandlersCollection[tagName] = this;
	}
	,GetHandlerByTagName: [decl_static, function(tagName)
	{
		if (!AS.Handler.HandlersCollection)
			return null;
		return AS.Handler.HandlersCollection[tagName];
	}]
	,Dispose: [decl_virtual, function() {
		this.moduleForm = null;
		this.attributes = null;
		this.Listeners.Dispose();
		this.Listeners = null;
	}]
	,GetTagDisplayNameByTagName: [decl_virtual, function(tagName) {
		var cache = GETSTIBYID(tagName);
		return (cache != null && !str_IsStringEmpty(cache.advdispname)) ? cache.advdispname : null;
	}]
	,IsSelected: function(value) {
		return (!str_IsStringEmpty(value) && value.toLowerCase() != "undefined") ? true : false;
	}
	,GetTagName: function() { return this.tagName }
	,GetTagDisplayName: function() { return this.tagDisplayName }
	,GetTagType: function() { return this.tagType }
	,GetTagScope: function() { return this.tagScope }
	,GetOccurrence: function() { return -1 }
	,SetTagScope: function(tagScope) {
		if (this.tagScope != tagScope) {
			this.tagScope = tagScope;
			this.AddAttribute(SRCH_TP_TAGSCOPE, this.tagScope);
		}
	}
	,AddAttributes: function() {
		this.AddAttribute(SRCH_TP_DISPLAYNAME, this.tagDisplayName);
		this.AddAttribute(SRCH_TP_TAGTYPE, this.tagType);
		this.AddAttribute(SRCH_TP_TAGSCOPE, this.tagScope);
	}
	,AddAttribute: function(name, value) {
		for (var i = 0, ic = this.attributes.length; i < ic; ++i) {
			if (this.attributes[i].name == name) {
				this.attributes[i].value = value;
				return;
			}
		}
		this.attributes[this.attributes.length] = {"name":name,"value":value};
	}
	,DelAttribute: function(name) {
		var res = [];
		for (var i = 0, j = 0, ic = this.attributes.length; i < ic; ++i) {
			if (this.attributes[i].name == name) 
				continue;
			res[j++] = this.attributes[i];
		}
		this.attributes = res;
	}
	,GetAttributes: function() {
		var res = [];
		for (var i = 0, ic = this.attributes.length; i < ic; ++i) 
			res.push(new srch_XSEP(this.attributes[i].name, this.attributes[i].value))
		return res;
	}
});
//------------------ HandlerListener ----------------------
DeclareClass("AS.HandlerListener", "AS.Handler", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.fnXMLCH = this.CreateCallback(this.OnXmlChange);
		this.Listener = new AS.EventListener(this.fnXMLCH);
		this.Listener.Attach();
		this.__onxmlchange = false;
	}
	,Dispose: [decl_virtual, function() {
		this.Listener.Detach();
		this.fnXMLCH = null;
		this.Listener.Dispose();
		this.Listener = null;
		this.base.Dispose();
	}]
	,IsLocked: function() { return this.__onxmlchange }
	,LockXML: function(value) { this.__onxmlchange = value }
	,OnXmlChange: [decl_virtual, function() {
		var nl = !this.IsLocked();
		if (nl) this.LockXML(true);
		
		if (GlASM.GetAUM() && this.moduleForm) 
			this.moduleForm.OnXmlChange();
			
		if (nl) this.LockXML(false);
	}]
	,AddTagsToXML: function(values, scope, ticker) 
	{
		if (this.__onxmlchange) return;
		if (!values || values.length == 0) return;
		
		var name = this.GetTagName();
		
		if (scope)
			this.AddAttribute(SRCH_TP_TAGSCOPE, uiasc_GetServerByClientScope(scope));
			
		if (ticker)
			this.AddAttribute(SRCH_AN_SYMBOLPRIMARYONLY, ticker);
			
		var attributes = this.GetAttributes();
		var occurrence = this.GetOccurrence(); 
		var new_attributes = null;
			
		for(var i=0, ic = values.length, st = ic-1; i<ic; ++i) 
		{
			new_attributes = attributes.slice(0);
			new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_DISPLAYVALUE, values[i].text));
			srch_advAddTag(name, values[i].value, new_attributes, occurrence, i == st);
		}
		
		srch_ShowWarningMessage();
	}
	,DelTagsFromXML: function(values) {
		if (this.__onxmlchange) return;
		if (!values) return;
		var name = this.GetTagName();
		for (var i = 0, ic = values.length, st = ic-1; i < ic; ++i) 
			srch_advDeleteTag(name, values[i].value, i == st);
	}
	,DelAllTagsByNameFromXML: function(fireevent, tagName) {
		if (this.__onxmlchange) return;
		srch_advDeleteTags(tagName, null, fireevent);
	}
	,AddTags: function(values, scope, ticker) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		this.AddTagsToXML(values, scope, ticker);
		if (aum) GlASM.AUM();
	}
	,OnMatchesNotFound: function() {
		if (this.selector)
			this.selector.AddToLeftListBox([{"name":"No matches found or search text too ambiguous.", "value":"@message@"}], false);
	}
});
//------------------ HandlerForDropDown ----------------------
DeclareClass("AS.HandlerForDropDown", "AS.HandlerListener", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.dropDown = null;
	}
	,Dispose: [decl_virtual, function() {
		this.dropDown = null;
		this.base.Dispose();
	}]
	,SetDropDownControl: function(control) {
		this.dropDown = control;
		this.Listeners.AddObjectListener(this.dropDown, "onselected", this.OnSelect);
	}
	,OnSelect: [decl_virtual, function(sender, value) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		this.DelAllTagsByNameFromXML(true, this.GetTagName());
		value = value.trim();
		if (this.IsSelected(value)) {
			var getv = this.dropDown.GetDisplayValue();
			this.AddTags([{"text":getv,"value":value}]);
		}
		
		if (aum) GlASM.AUM();
	}]
});
//------------------ HandlerForSearchScope ----------------------
DeclareClass("AS.HandlerForSearchScope", "AS.HandlerListener", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.gbSearchScope = null;
	}
	,Dispose: [decl_virtual, function() {
		this.grSearchscope = null;
		this.base.Dispose();
	}]
	,SetSearchScopeControl: function(control) {
		this.gbSearchScope = control;
		this.Listeners.AddObjectListener(this.gbSearchScope, "onrbvaluechange", this.OnChangeSearchScope);
	}
	,OnChangeSearchScope: [decl_virtual, function(tagScope, isInit) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		this.SetTagScope(tagScope);
		if (!isInit) {
			var values = this.GetItemsNeededToAdd();
			if (values && values.length != 0) {
				this.DelAllTagsByNameFromXML(false, this.GetTagName());
				this.AddTags(values);
			}
		}
		if (aum) GlASM.AUM();
	}]
	,GetItemsNeededToAdd: function() { return null }
});
//------------------ HandlerForMultiSelector ----------------------
DeclareClass("AS.HandlerForMultiSelector", "AS.HandlerListener", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.selector = null;
	}
	,Dispose: [decl_virtual, function() {
		this.selector = null;
		this.base.Dispose();
	}]
	,AddSelector: function(selector) {
		this.selector = selector;
		this.AttachEventsToSelector(this.selector);
		if (this.selector && this.clearSelectedNoFireEvent)
			this.selector.ClearSelected(true);				
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		if (this.selector) {
			this.Listeners.AddObjectListener(this.selector, "onmoveallitemstoleft", this.OnMoveAllItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "onmoveitemstoleft", this.OnMoveItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "ondeleteallitemsfromright", this.OnMoveAllItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "ondeleteitemsfromright", this.OnMoveItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "onclick", this.AddTags);
		}
	}]
	,OnMoveAllItemsToLeft: function(tagName, scope) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		this.DelAllTagsByNameFromXML(true, tagName);
		if (aum) GlASM.AUM();
	}
	,OnMoveItemsToLeft: function(items, scope) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		this.OnRightDeleteSelected(items);
		if (aum) GlASM.AUM();
	}
	,OnRightDeleteSelected: function(values) { 
		this.DelTagsFromXML(values);
	}
	,GetItemsNeededToAdd: function() { 
		return (this.selector) ? this.selector.GetSelectedItems() : null;
	}
	,ClearSelectedNoFireEvent: function(fireEvent) {
		this.clearSelectedNoFireEvent = true;
		if (this.selector)
			this.selector.ClearSelected(fireEvent);		
	}
});
//------------------ HandlerForSearchScopeSelectorDropDown ----------------------
DeclareClass("AS.HandlerForSearchScopeSelectorDropDown", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.dropDown = null;
	}
	,Dispose: [decl_virtual, function() {
		this.dropDown = null;
		this.base.Dispose();
	}]
	,SetDropDownControl: function(control) {
		this.dropDown = control;
		this.Listeners.AddObjectListener(this.dropDown, "onselected", this.OnSelect);
	}
	,OnSelect: function(sender, value) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		this.DelAllTagsByNameFromXML(true, this.GetTagName());
		value = value.trim();
		if (this.IsSelected(value)) {
			var getv = this.dropDown.GetDisplayValue();
			this.AddTags([{"text":getv,"value":value}]);
		}
		if (aum) GlASM.AUM();
	}
});
//------------------ HandlerForSearchScopeSelector ----------------------
DeclareClass("AS.HandlerForSearchScopeSelector", "AS.HandlerForSearchScope", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.selector = null;
	}
	,Dispose: [decl_virtual, function() {
		this.selector = null;
		this.base.Dispose();
	}]
	,AddSelector: function(selector) {
		this.selector = selector;
		this.AttachEventsToSelector(this.selector);
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		if (this.selector) {
			this.Listeners.AddObjectListener(this.selector, "onmoveallitemstoleft", this.OnMoveAllItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "onmoveitemstoleft", this.OnMoveItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "ondeleteallitemsfromright", this.OnMoveAllItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "ondeleteitemsfromright", this.OnMoveItemsToLeft);
			this.Listeners.AddObjectListener(this.selector, "onclick", this.AddTags);
		}
	}]
	,OnMoveAllItemsToLeft: function(tagName) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
	
		this.DelAllTagsByNameFromXML(true, tagName);
		this.moduleForm.gbSearchScope.SelectRadioButtonByValue(SRCH_TS_ANY, false);
		this.OnChangeSearchScope(SRCH_TS_ANY, true);
		
		if (aum) GlASM.AUM();
	}
	,OnMoveItemsToLeft: function(items) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		this.OnRightDeleteSelected(items);
		
		if (aum) GlASM.AUM();
	}
	,OnRightDeleteSelected: function(values) { this.DelTagsFromXML(values) }
	,GetItemsNeededToAdd: function() { return (this.selector) ? this.selector.GetSelectedItems() : null }
});
//------------------ HandlerForMultiTextBox ----------------------
DeclareClass("AS.HandlerForMultiTextBox", "AS.HandlerListener", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		this.textBox = {};
		moduleForm.AttachEvent("onchange", this.CreateCallback(this.OnTextBoxChange));
	}
	,Dispose: [decl_virtual, function() {
		this.textBox = null;
		this.base.Dispose();
	}]
	,SetTagScopes: function(scopes) { this.scopes = scopes; }
	,SetTextBoxControl: function(control, scope) { this.textBox[scope] = control; }
	,OnTextBoxChange: [decl_virtual, function(value, scope, textBox) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		
		var needAdded = false;
		for (var k = 0, kc = this.scopes.length; k < kc; ++k) {
			var textBoxInfo = this.textBox[this.scopes[k]];
			if (!textBoxInfo) continue;
			var textBox = textBoxInfo.TextBox;
			if (!textBox) continue;
			var vals = textBox.GetValue();
			if (vals.length > 0) {
				needAdded = true;
				break;
			}
		}
		
		if (needAdded == false)
			this.DelAllTagsByNameFromXML(true, this.GetTagName());
		else
		{
			this.DelAllTagsByNameFromXML(false, this.GetTagName());
			
			for (var k = 0, kc = this.scopes.length; k < kc; ++k) {
				var textBoxInfo = this.textBox[this.scopes[k]];
				if (!textBoxInfo) continue;
				var textBox = textBoxInfo.TextBox;
				if (!textBox) continue;
				
				var vals = textBox.GetValue();
						
				var res = []; 
				var added = [];
		
				for (var i = 0, j = 0, ic = vals.length; i < ic; ++i) {
					vals[i] = vals[i].trim();
					var arVal = "item_" + vals[i];
					if (added[arVal] == null) {
						res[j++] = {"text":vals[i],"value":vals[i]};
						added[arVal] = true;
					}
				}
				
				this.AddTags(res, this.scopes[k]);
			}
		}
			
		if (aum) GlASM.AUM();
	}]
});
//------------------ HandlerForDropDownLooker ----------------------
DeclareClass("AS.HandlerForDropDownLooker", "AS.HandlerForSearchScopeSelectorDropDown", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		
		this.fnLRCH = this.CreateCallback(this.OnResolve);
		
		this.looker = new Looker(this.fnLRCH);
		this.looker.OnResolveComplete = this.fnLRCH;
	}
	,Dispose: [decl_virtual, function(){
		this.looker.OnResolveComplete = null;
		this.looker = null;
		this.fnLRCH = null;
		this.base.Dispose();
	}]
	,AddToResolution: function(type, value, params) { this.looker.AddToResolution(type, value, params) }
	,Clear: function() { this.looker.Clear() }
	,GetValueNodeName: function() { return "ID" }
	,GetNameNodeName: function() { return "Title" }
	,Resolve: function() { this.looker.Resolve() }
	,GetResolvedValues: [decl_virtual, function() {
		var res = this.looker.GetResolutions(this.GetTagNameContainer()), values = [];
		if (!res) return;
		for (var i = res.length-1, k = 0; i >= 0; --i) {
			for (var j = 0, jc = res[i].GetCount(); j < jc; ++j) {
				var node = res[i].GetByIndex(j);
				values[k++] = {"name":node.getValue(this.GetNameNodeName()),
					"value":node.getValue(this.GetValueNodeName())};					
			}
		}
		return values;
	}]
	,OnResolve: function() {
		if (this.selector) 
			this.selector.ClearFilter();
			
		var values = this.GetResolvedValues();
		
		if (values && values.length > 0) {
			this.selector.ClearLeftListBox();
			this.selector.AddToLeftListBox(values, false);
			values = null;
		} else 
			this.OnMatchesNotFound();
		this.selector.AddPredefinedValues();
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		this.base.AttachEventsToSelector(selector);
		if (this.selector)
			this.Listeners.AddObjectListener(this.selector, "onfilter", this.OnFilter);
	}]
	,GetTagNameContainer: function() { return this.GetTagName() }
	,GetResolutionParams: function() { return null }
	,OnFilter: function(value) {
		if (str_IsStringEmpty(value)) 
			return;
		if (this.selector) 
			this.selector.LoadingByResolving();
		this.Clear();
		var array = value.split(",");
		var params = this.GetResolutionParams();
		if (!params || params.length == 0)
		{
			for (var i = 0, ic = array.length; i < ic; ++i) {
				array[i] = array[i].trim();
				if (!str_IsStringEmpty(array[i]))
					this.AddToResolution(this.GetTagNameContainer(), array[i]);
			}
		}
		else
		{
			for (var i = 0, ic = array.length; i < ic; ++i) {
				array[i] = array[i].trim();
				if (!str_IsStringEmpty(array[i]))
					this.AddToResolution(this.GetTagNameContainer(), array[i], params);
			}
		}
		this.Resolve();
	}
});
//------------------ HandlerWithLooker ----------------------
DeclareClass("AS.HandlerWithLooker", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		
		this.fnLRCH = this.CreateCallback(this.OnResolve);
		this.looker = new Looker(this.fnLRCH);
		this.looker.OnResolveComplete = this.fnLRCH;
	}
	,Dispose: [decl_virtual, function() {
		this.looker.OnResolveComplete = null;
		this.looker = null;
		this.fnLRCH = null;
		this.base.Dispose();
	}]
	,AddToResolution: function(type, value) { this.looker.AddToResolution(type, value) }
	,Clear: function() { this.looker.Clear() }
	,GetValueNodeName: function() { return "ID" }
	,GetNameNodeName: function() { return "NAME" }
	,Resolve: function() { this.looker.Resolve() }
	,OnResolve: function() {
		if (this.selector)
			this.selector.ClearFilter();
		var res = this.looker.GetResolutions(this.GetTagName());
		if (res != null) {
			var values = [];
			for (var i = res.length-1, k = 0; i >=0; --i) {
				for (var j = 0, jc = res[i].GetCount(); j < jc; ++j) {
					var node = res[i].GetByIndex(j);
					values[k++] = {"name":node.getValue(this.GetNameNodeName()), "value":node.getValue(this.GetValueNodeName())};
				}
			}
			this.selector.ClearLeftListBox();
			if (values.length > 1) {
				this.selector.AddToLeftListBox(values, false);
			}
			else if (values.length == 1) {
				var addedItems = this.selector.AddToRightListBox(values);
				this.AddTags(addedItems);
				addedItems = null;
			}
			else 
				this.OnMatchesNotFound();
		}
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		this.base.AttachEventsToSelector(selector);
		if (this.selector)
			this.Listeners.AddObjectListener(this.selector, "onfilter", this.OnFilter);
	}]
	,OnFilter: function(value) {
		if (str_IsStringEmpty(value)) return;
		if (this.selector) this.selector.LoadingByResolving();
		this.Clear();
		var array = value.split(",");
		for (var i = 0, ic = array.length; i < ic; ++i) {
			array[i] = array[i].trim();
			if (!str_IsStringEmpty(array[i]))
				this.AddToResolution(this.GetTagName(), array[i]);
				
		}
		this.Resolve();
	}
});
//------------------ HandlerWithLookerMultiSelector ----------------------
DeclareClass("AS.HandlerWithLookerMultiSelector", "AS.HandlerForMultiSelector", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		
		this.fnLRCH = this.CreateCallback(this.OnResolve);
		this.looker = new Looker(this.fnLRCH);
		this.looker.OnResolveComplete = this.fnLRCH;
	}
	,Dispose: [decl_virtual, function() {
		this.looker.OnResolveComplete = null;
		this.looker = null;
		this.fnLRCH = null;
		this.base.Dispose();
	}]
	,AddToResolution: function(type, value) { this.looker.AddToResolution(type, value); }
	,Clear: function() { this.looker.Clear(); }
	,GetValueNodeName: function() { return "ID"; }
	,GetNameNodeName: function() { return "NAME"; }
	,Resolve: function() { this.looker.Resolve(); }
	,OnResolve: function() {
		if (this.selector)
			this.selector.ClearFilter();
		var res = this.looker.GetResolutions(this.GetTagName());
		if (res != null) {
			var values = [];
			for (var i = res.length-1, k = 0; i >=0; --i) {
				for (var j = 0, jc = res[i].GetCount(); j < jc; ++j) {
					var node = res[i].GetByIndex(j);
					values[k++] = {"name":node.getValue(this.GetNameNodeName()), "value":node.getValue(this.GetValueNodeName())};
				}
			}
			this.selector.ClearLeftListBox();
			if (values.length > 0) {
				this.selector.AddToLeftListBox(values, false);
			}
			else 
				this.OnMatchesNotFound();
		}
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		this.base.AttachEventsToSelector(selector);
		if (this.selector)
			this.Listeners.AddObjectListener(this.selector, "onfilter", this.OnFilter);
	}]
	,OnFilter: function(value) {
		if (str_IsStringEmpty(value)) return;
		if (this.selector) this.selector.LoadingByResolving();
		this.Clear();
		var array = value.split(",");
		for (var i = 0, ic = array.length; i < ic; ++i) {
			array[i] = array[i].trim();
			if (!str_IsStringEmpty(array[i]))
				this.AddToResolution(this.GetTagName(), array[i]);
				
		}
		this.Resolve();
	}
});
//------------------ HandlerWithLookerSelector ----------------------
DeclareClass("AS.HandlerWithLookerSelector", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm, tagName, tagDisplayName, tagType, tagScope) {
		this.base(moduleForm, tagName, tagDisplayName, tagType, tagScope);
		
		this.fnLRCH = this.CreateCallback(this.OnResolve);
		this.looker = new Looker(this.fnLRCH);
		this.looker.OnResolveComplete = this.fnLRCH;
	}
	,Dispose: [decl_virtual, function() {
		this.looker.OnResolveComplete = null;
		this.looker = null;
		this.fnLRCH = null;
		this.base.Dispose();
	}]
	,AddToResolution: function(type, value) { this.looker.AddToResolution(type, value) }
	,Clear: function() { this.looker.Clear() }
	,GetValueNodeName: function() { return "ID" }
	,GetNameNodeName: function() { return "NAME" }
	,Resolve: function() { this.looker.Resolve() }
	,OnResolve: function() {
		if (this.selector)
			this.selector.ClearFilter();
		var res = this.looker.GetResolutions(this.GetTagName());
		if (res != null) {
			var values = [];
			for (var i = res.length-1, k = 0; i >=0; --i) {
				for (var j = 0, jc = res[i].GetCount(); j < jc; ++j) {
					var node = res[i].GetByIndex(j);
					values[k++] = {"name":node.getValue(this.GetNameNodeName()), "value":node.getValue(this.GetValueNodeName())};
				}
			}
			this.selector.ClearLeftListBox();
			if (values.length > 1) {
				this.selector.AddToLeftListBox(values, false);
			}
			else if (values.length == 1) {
				var addedItems = this.selector.AddToRightListBox(values);
				this.AddTags(addedItems);
				addedItems = null;
			}
			else 
				this.OnMatchesNotFound();
		}
	}
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		this.base.AttachEventsToSelector(selector);
		if (this.selector)
			this.Listeners.AddObjectListener(this.selector, "onfilter", this.OnFilter);
	}]
	,OnFilter: function(value) {
		if (str_IsStringEmpty(value)) return;
		if (this.selector) this.selector.LoadingByResolving();
		this.Clear();
		var array = value.split(",");
		for (var i = 0, ic = array.length; i < ic; ++i) {
			array[i] = array[i].trim();
			if (!str_IsStringEmpty(array[i]))
				this.AddToResolution(this.GetTagName(), array[i]);
				
		}
		this.Resolve();
	}
});
//------------------ ModuleForm -------------------------
DeclareClass("UI.AS.ModuleForm", "UI.Control", {
	constructor: function() {
		this.base();
		this.handler = this.CreateHandler();
		this.AsyncRenderingEnabled = true;
		this.SetCssClass("sa-form");
	}
	,Dispose: [decl_virtual, function()	{
		if (this.handler) {
			this.handler.Dispose();
			this.handler = null;
		}
		this.base.Dispose();
	}]
	,CreateHandler: function() { return new AS.Handler(this, null, null, SRCH_TT_STD, SRCH_TS_ANY) }
	,GetTagName: function() { return UI.HtmlTag.Div }
	,OnShow: function() { this.SetVisible(true) }
	,OnHide: function() { this.SetVisible(false) }
	,Init: [decl_virtual, function() {
		this.InitFormControls();
		this.OnXmlChange();
	}]
	,InitFormControls: [decl_virtual, function() { }]
	,TagsInXml: [decl_virtual, function(tags) { }]
	,GetTagsWithNoInvalid: function(tags) {
		if (!tags) return tags;			
		var res = [];
		for (var i = 0, j = 0, ic = tags.length; i < ic; ++i) {
			if (!tags[i].selectSingleNode(SRCH_AN_TEXTERROR))
				res[j++] = tags[i];	
		}
		return res; 	
	}
	,OnXmlChange: [decl_virtual, function() {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();

		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_NAME, this.handler.GetTagName())]);
		this.TagsInXml(this.GetTagsWithNoInvalid(tags));
		
		if (aum) GlASM.AUM();
	}]
});
//------------------ ModuleFormWithDropDown -------------------------
DeclareClass("UI.AS.ModuleFormWithDropDown", "UI.AS.ModuleForm", {
	constructor: function() {
		this.base();
		this.dropDown = null;
		this.cache = null;
		this.curr_dropDownValue = this.GetSelectedValue();
	}
	,Dispose: [decl_virtual, function() {
		this.dropDown = null;
		this.cache = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.cache = this.GetCache();
		this.dropDown = this.CreateDropDown();
		this.dropDown.SetWidth("205px");
		this.FillDropDown();
		this.SetDropDownValue();
		this.handler.SetDropDownControl(this.dropDown);
		this.base.Init();
	}]
	,CreateDropDown: function() { return new UI.Controls.DropDown() }
	,SetCache: [decl_virtual, function(cache) {
		if (this.cache != cache) {
			this.cache = cache;
			this.FillDropDown();
			this.SetCurrentDropDownValue(this.curr_dropDownValue);
			this.SetDropDownValue();
		}
	}]
	,InitFormControls: [decl_virtual, function() { this.AddControl(this.dropDown) }]
	,Render: [decl_virtual, function(writer) {
		var td1 = new UI.DOMControls.Td(); td1.SetCssClass("sa-form-ddtdl");
		var td2 = new UI.DOMControls.Td(); td2.SetCssClass("sa-form-ddtdr");
		this.HostElement.appendChild(new UI.DOMControls.Table(new UI.DOMControls.Tr(td1, td2)).Obj());
		this.dropDown.RenderControl(td1.Obj());
	}]
	,FillDropDown: [decl_virtual, function() {
		if (this.dropDown && this.cache) {
			this.dropDown.Clear();
			var ic = this.cache.length;
			if (ic > 0) {
				if (typeof(this.cache[0]) == "object") 
					for(var i=0; i<ic; ++i)
						this.dropDown.AddItem(this.cache[i].name, this.cache[i].value);
				else 
					for(var i=0; i<ic; ++i)
						this.dropDown.AddItem(this.cache[i], this.cache[i]);
			}
		}
	}]
	,GetSelectedValue: function() { return (this.cache) ? this.cache[0].value : null }
	,GetCache: function() { return null }
	,SetDropDownValue: function() {
		if (this.dropDown) {
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
				
			if (this.curr_dropDownValue == null)
				this.dropDown.Select(0);
			else
				this.dropDown.SetSelectedValue(this.curr_dropDownValue);
				
			if (needLock) this.handler.LockXML(false);
		}
	}
	,SetCurrentDropDownValue: function(value) {
		this.curr_dropDownValue = value;
		this.SetDropDownValue();
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) 
			this.SetCurrentDropDownValue(this.GetSelectedValue());
		else 
		{
			var tagValue = tags[0].selectSingleNode(SRCH_TP_VALUE);
			if (tagValue) {
				this.SetCurrentDropDownValue(tagValue.text);
				tagValue = null;
			}
		}
	}]
});
//------------------ ModuleFormWithSearchScope -------------------------
DeclareClass("UI.AS.ModuleFormWithSearchScope", "UI.AS.ModuleForm", {
	constructor: function() {
		this.base();
		this.gbSearchScope = null;
		this.curr_SearchScopeValue = SRCH_TS_ANY;	
	}
	,Dispose: [decl_virtual, function() {
		this.gbSearchScope = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.gbSearchScope = this.CreateSearchScopeControl();
		this.handler.SetSearchScopeControl(this.gbSearchScope);
		this.SetSearchScopeValue();
		this.base.Init();
	}]
	,SetSearchScopeValue: function() {
		if (this.gbSearchScope != null) {
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
			
			this.gbSearchScope.SelectRadioButtonByValue(this.curr_SearchScopeValue);
			
			if (needLock) this.handler.LockXML(false);
		}
	}
	,SetCurrentSearchScope: function(value) {
		this.curr_SearchScopeValue = value;
		this.SetSearchScopeValue();						
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
			
		if (!tags || tags.length == 0) 	
			this.SetCurrentSearchScope(SRCH_TS_ANY);
		else 
		{
			var tagRule = tags[0].selectSingleNode(SRCH_TP_TAGSCOPE);
			if (tagRule) {
				this.SetCurrentSearchScope(tagRule.text);
				tagRule = null;
			}
		}
	}]
	,CreateSearchScopeControl: [decl_virtual, function(){
		return new UI.Controls.GroupBox(this.GetGroupBoxId(), "Search type:", 
			this.GetSearchScopeControlWidth(), "100%", this.GetRadioButtons());
	}]
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.All, UI.AS.Scope.ExcludeAny] }
	,GetScopePostfixText: function() { return " of the Items" }
	,GetSRCH_TS: function(scopeTag) {
		switch (scopeTag) {
			case UI.AS.Scope.Any: return SRCH_TS_ANY;
			case UI.AS.Scope.All: return SRCH_TS_ALL;
			case UI.AS.Scope.ExcludeAny: return SRCH_TS_EXCLUDEANY;
		}
		return null;
	}
	,GetScopePrefixText: function(tag) { return uiasc_GetDisplayScopeByValue(uiasc_GetServerByClientScope(tag)) }
	,GetRadioButtons: function() {
		var res = [];
		var tags = this.GetScopeTags();
		for (var i = 0, ic = tags.length; i < ic; ++i)
			res[i] = {'control': new UI.Controls.RadioButton(this.GetScopePrefixText(tags[i]) + this.GetScopePostfixText(), 
				this.GetSRCH_TS(tags[i]), i == 0), 'css': null};
		return res;
	}
	,GetGroupBoxId: function() { return this.handler.GetTagName() + "gb" }
	,GetSearchScopeControlWidth: function() { return "195px" }
});
//------------------ AS.MultiTextBoxInfo -------------------------
DeclareClass("AS.MultiTextBoxInfo", null, {
	constructor: function(scope, textBox) {
		this.Scope = scope;
		this.TextBox = textBox;
		this.TextBoxValue = null;
		this.callback = null;
		this.hdl_OnChange = this.CreateCallback(this.OnChange);
	}
	,Dispose: function() {
		if (this.TextBox) {
			this.TextBox.DetachEvent("onchange", this.hdl_OnChange);
			this.TextBox.Dispose();
			this.TextBox = null;
		}
	}
	,SetTextBox: function(textBox, callback) {
		this.TextBox = textBox;
		this.callback = callback;
		this.TextBox.AttachEvent("onchange", this.hdl_OnChange);
	}
	,OnChange : function(value) { this.callback(value, this.Scope, this.TextBox); }
}); 
//------------------ ModuleFormWithMultiTextBox -------------------------
DeclareClass("UI.AS.ModuleFormWithMultiTextBox", "UI.AS.ModuleForm", {
	constructor: function() {
		this.base();
		
		this.textBoxes = {};		
		var scopes = this.GetScopeTags();
		for (var i =0, ic = scopes.length; i < ic; ++i)
			this.textBoxes[scopes[i]] = new AS.MultiTextBoxInfo(scopes[i], null);
			
		this.hdl_OnChange = this.CreateCallback(this.OnChange);
	}
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.All, UI.AS.Scope.ExcludeAny]; }
	,Dispose: [decl_virtual, function() {
		if (this.textBoxes) {
			var scopes = this.GetScopeTags();
			for (var i = 0, ic = scopes.length; i < ic; ++i) {
				if (this.textBoxes[scopes[i]]) {
					this.textBoxes[scopes[i]].Dispose();
					this.textBoxes[scopes[i]] = null;
				}
			}
			this.textBoxes = null;
		}
		this.hdl_OnChange = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		var scopes = this.GetScopeTags();
		this.handler.SetTagScopes(scopes);
		for (var i =0, ic = scopes.length; i < ic; ++i)
		{
			var scope = scopes[i];
			var textBoxInfo = this.textBoxes[scope];
			textBoxInfo.SetTextBox(this.CreateTextBox(scope), this.hdl_OnChange);
			this.SetTextBoxValue(scope);
			this.handler.SetTextBoxControl(textBoxInfo, scope);
		}
		
		this.base.Init();			
	}]
	,OnChange: function(value, scope, textBox) { this.FireEvent("onchange", value, scope, textBox); }
	,GetScopePrefixText: function(scope) { return uiasc_GetDisplayScopeByValue(uiasc_GetServerByClientScope(scope)); }
	,GetScopePostfixText: function() { return " of the Items"; }
	,CreateTextBox: function(scope) {
		if (scope == UI.AS.Scope.Any)
		{
			var arTitle = [];
			var tbs = [new UI.Controls.TextBoxSpan(this.GetTextBoxTitle() + " (", "tb-title"),
					   new UI.Controls.TextBoxSpan("Separate by comma", "tb-title-gray"),
					   new UI.Controls.TextBoxSpan(") Surround words or phrases with quotation marks for exact text matches.", "tb-title")];
			arTitle[arTitle.length] = new UI.Controls.TextBoxRow(tbs, "tb-title");
			
			var tbs1 = [new UI.Controls.TextBoxSpan(this.GetScopePrefixText(scope) + this.GetScopePostfixText(), "tb-title")];
			arTitle[arTitle.length] = new UI.Controls.TextBoxRow(tbs1, "sa-sel-acl h20");
			
			return new UI.Controls.TextBox(arTitle, null, "100%", "100px");
		}
		else if (scope == UI.AS.Scope.All)
		{
			var arTitle = [];
			
			var tbs1 = [new UI.Controls.TextBoxSpan(this.GetScopePrefixText(scope) + this.GetScopePostfixText(), "tb-title")];
			arTitle[arTitle.length] = new UI.Controls.TextBoxRow(tbs1, "sa-sel-acl h20");
			
			return new UI.Controls.TextBox(arTitle, null, "100%", "100px");
		}
		else if (scope == UI.AS.Scope.ExcludeAny)
		{
			var arTitle = [];
			
			var tbs1 = [new UI.Controls.TextBoxSpan(this.GetScopePrefixText(scope) + this.GetScopePostfixText(), "tb-title")];
			arTitle[arTitle.length] = new UI.Controls.TextBoxRow(tbs1, "sa-sel-acl h20");
			
			return new UI.Controls.TextBox(arTitle, null, "100%", "100px");
		}
		else
			return null;
	}
	,InitFormControls: [decl_virtual, function() {
		var tagScopes = this.GetScopeTags();
		for (var i =0, ic = tagScopes.length; i < ic; ++i) {
			var textBox = this.textBoxes[tagScopes[i]].TextBox;
			this.AddControl(textBox);
		}
	}]
	,Render: [decl_virtual, function() {
		var tagScopes = this.GetScopeTags();
		var rows = [];
		
		for (var i =0, ic = tagScopes.length; i < ic; ++i) {
			var textBox = this.textBoxes[tagScopes[i]].TextBox;
			
			var tdTextBox = new UI.DOMControls.Td(); 
			tdTextBox.SetCssClass("sa-fill");
			
			rows.push(new UI.DOMControls.Tr(tdTextBox));
			
			this.textBoxes[tagScopes[i]].HostElement = tdTextBox;
		}
		
		this.HostElement.appendChild(new UI.DOMControls.Table(rows).Obj());
		
		for (var i =0, ic = tagScopes.length; i < ic; ++i)
		{
			var textBox = this.textBoxes[tagScopes[i]].TextBox;
			var hostElement = this.textBoxes[tagScopes[i]].HostElement;
			
			textBox.RenderControl(hostElement.Obj());
		}
	}]
	,GetTextBoxTitle: function() { return ""; }
	,SetTextBoxValue: function(scope) {
		var textBox = this.textBoxes[scope].TextBox;
		if (textBox != null) 
		{
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
		
			var textBoxValue = this.textBoxes[scope].TextBoxValue;
			if (textBoxValue == null)
				textBox.Clear(false);
			else
				textBox.SetText(textBoxValue, false);
				
			if (needLock) this.handler.LockXML(false);
		}
	}
	,SetCurrentTextBoxValue: function(value, scope) {
		this.textBoxes[scope].TextBoxValue = value;
		this.SetTextBoxValue(scope);
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) {
			var tagScopes = this.GetScopeTags();
			for (var i =0, ic = tagScopes.length; i < ic; ++i)
				this.SetCurrentTextBoxValue(null, tagScopes[i]);
		}
		else
		{
			var values = [];
			var dispval = [];
			var scopes = [];
			
			for (var i = 0, ic = tags.length; i < ic; ++i) 
			{
				values[i] = tags[i].selectSingleNode(SRCH_TP_VALUE);
				dispval[i] = tags[i].selectSingleNode(SRCH_TP_DISPLAYVALUE);
				scopes[i] = tags[i].selectSingleNode(SRCH_TP_TAGSCOPE);
			}
			
			var tagScopes = this.GetScopeTags();
			for (var k =0, kc = tagScopes.length; k < kc; ++k)
			{
				var res = [];
				for (var i = 0, j = 0, ic = values.length; i < ic; ++i) 
				{
					if (uiasc_GetClientByServerScope(scopes[i].text) != tagScopes[k])
						continue;
						
					var name = dispval[i].text;
					var val = values[i].text;
					
					res[j++] = val;
				}
				this.SetCurrentTextBoxValue(res.join(','), tagScopes[k]);
			}
		}
	}]
});
//------------------ ModuleFormWithSearchScopeSelector -------------------------
DeclareClass("UI.AS.ModuleFormWithSearchScopeSelector", "UI.AS.ModuleFormWithSearchScope", {
	constructor: function() {
		this.base();
		this.selector = null;		
		this.curr_SelectorTags = null;
		this.isSetSelectorValue = false;	
	}
	,Dispose: [decl_virtual, function() {
		this.selector = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.selector = this.CreateSelectorControl();
		this.selector.SetHandler(this.handler);
		this.isSetSelectorValue = this.SetSelectorValue();
		this.handler.AddSelector(this.selector);
		this.base.Init();
	}]
	,CreateSelectorControl: function() { return null }
	,SetSelectorValue: function() {
		if (this.selector)
			this.selector.TagsInXml(this.curr_SelectorTags);
		return (this.curr_SelectorTags && this.curr_SelectorTags.length != 0) ? true : false;
	}
	,SetCurrentSelectorTags: function(value) {
		this.curr_SelectorTags = value;
		this.SetSelectorValue();
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.SetCurrentSelectorTags(tags);
		this.base.TagsInXml(tags);
	}]
	,InitFormControls: [decl_virtual, function() {
		this.AddControl(this.gbSearchScope);
		this.AddControl(this.selector);
	}]
	,Render: [decl_virtual, function() {
		var td = new UI.DOMControls.Td(); td.SetCssClass("h100p");
		var tdSelector = new UI.DOMControls.Td(); tdSelector.SetCssClass("sa-fill");
		var tbl = new UI.DOMControls.Table(new UI.DOMControls.Tr(tdSelector, td));
		tbl.Obj().style.height = "100%";
		this.HostElement.appendChild(tbl.Obj());
		
		this.gbSearchScope.RenderControl(td.Obj());
		this.selector.RenderControl(tdSelector.Obj());
	}]
});
//------------------ ModuleFormWithSelector -------------------------
DeclareClass("UI.AS.ModuleFormWithSelector", "UI.AS.ModuleForm", {
	constructor: function() {
		this.base();
		this.selector = null;		
		this.curr_SelectorTags = null;
		this.isSetSelectorValue = false;	
	}
	,Dispose: [decl_virtual, function() {
		this.selector = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.selector = this.CreateSelectorControl();
		this.selector.SetHandler(this.handler);
		this.isSetSelectorValue = this.SetSelectorValue();
		this.handler.AddSelector(this.selector);
		this.base.Init();
	}]
	,CreateSelectorControl: function() { return null; }
	,SetSelectorValue: function() {
		if (this.selector)
			this.selector.TagsInXml(this.curr_SelectorTags);
		return (this.curr_SelectorTags && this.curr_SelectorTags.length != 0) ? true : false;
	}
	,SetCurrentSelectorTags: function(value) {
		this.curr_SelectorTags = value;
		this.SetSelectorValue();
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.SetCurrentSelectorTags(tags);
		this.base.TagsInXml(tags);
	}]
	,InitFormControls: [decl_virtual, function() { this.AddControl(this.selector); }]
	,Render: [decl_virtual, function() {
		var tdSelector = new UI.DOMControls.Td(); 
		tdSelector.SetCssClass("sa-fill");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(tdSelector));
		this.HostElement.appendChild(table.Obj());
		
		this.selector.RenderControl(tdSelector.Obj());
	}]
});
//------------------ CustomSearchScope -------------------------
DeclareClass("UI.AS.CustomSearchScope", "UI.Control", {
	constructor: function() {
		this.base();
		this.gbSearchScope = null;
	}
	,Dispose: [decl_virtual, function() {
		this.gbSearchScope = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.gbSearchScope = this.CreateSearchScopeControl();
		this.Listeners.AddObjectListener(this.gbSearchScope, "onrbvaluechange", this.OnChangeValue);
		GlASM.RegisterCustomScopeControl(this.TopElement.id, this);
		this.AddControl(this.gbSearchScope);
	}]
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.All, UI.AS.Scope.ExcludeAny] }
	,CreateSearchScopeControl : [decl_virtual, function(){
		return new UI.Controls.GroupBox(this.GetGroupBoxId(), "Search type:", 
			this.GetSearchScopeControlWidth(), "100%", this.GetRadioButtons());;
	}]
	,GetScopePostfixText: function() { return " of the Values" }
	,GetSRCH_TS: function(scopeTag) {
		switch (scopeTag) {
			case UI.AS.Scope.Any: return SRCH_TS_ANY;
			case UI.AS.Scope.All: return SRCH_TS_ALL;
			case UI.AS.Scope.ExcludeAny: return SRCH_TS_EXCLUDEANY;
		}
		return null;
	}
	,GetRadioButtons: function() {
		var res = [];
		var tags = this.GetScopeTags();
		for (var i = 0, ic = tags.length; i < ic; ++i) {
			res[i] = {'control': new UI.Controls.RadioButton(tags[i]+ this.GetScopePostfixText(), 
				this.GetSRCH_TS(tags[i]), i == 0), 'css': null};
		}
		return res;
	}
	,GetGroupBoxId: function() { return this.TopElement.id + "_gb" }
	,GetSearchScopeControlWidth: function() { return "195px" }
	,OnChangeValue: function(value, isInitializing) { GlASM.CustomOnChangeSearchScope(value, isInitializing, this.TopElement.id) }
	,SetValue: function(value, fireEvent) {
		if (this.gbSearchScope)
			this.gbSearchScope.SelectRadioButtonByValue(value, fireEvent);
	}
});
//-------------- as_OnAdvSearchCustomControlChange ---------------------
function as_OnAdvSearchCustomControlChange(id, tagName) {
	GlASM.OnCustomControlChange(id, tagName);
}
//------------------ CustomControls -------------------------
DeclareClass("AS.CustomControls", null, {
	constructor: function(id, tagName, getHandler, setHandler, getAttrHandler, scopeControlId, getValidationHandler) {
		this.id = id; 
		this.tagName = tagName;
		this.getHandler = (getHandler && !str_IsStringEmpty(getHandler)) ? eval(getHandler) : null;
		this.setHandler = (setHandler && !str_IsStringEmpty(setHandler)) ? eval(setHandler) : null;
		this.getAttrHandler = getAttrHandler;
		this.getValidationHandler = getValidationHandler;
		this.currentValues = null;
		this.scopeControlId = (typeof(scopeControlId)!="undefined")?scopeControlId:null;
		this.searchScopeValue = SRCH_TS_ANY;
	}
	,Dispose: [decl_virtual, function() {
		this.getHandler = null;
		this.setHandler = null;
		this.getAttrHandler = null;
		this.getValidationHandler = null;
		this.base.Dispose();
	}]
	,GetSearchScopeValue: function() {
		return this.searchScopeValue;
	}
	,OnChangeSearchScope: function(value) {
		if (this.searchScopeValue != value) {
			this.searchScopeValue = value;
			GlASM.AddCustomValues(this.tagName, null, true);	
		}
	}
	,SetCurrentValues: function(values) { this.currentValues = values }
	,GetCurrentValues: function() { return this.currentValues }
	,AddCurrentValue: function(value) {
		if (this.currentValues)
			this.currentValues[this.currentValues.length] = value;
	}
	,AddCurrentValues: function(values) {
		if (this.currentValues) {
			for (var i = 0, ic = values.length; i < ic; ++i)
				this.currentValues[this.currentValues.length] = values[i];	
		}
	}
	,DelCurrentValues: function(values) {
		if (this.currentValues) {
			for (var i = 0, ic = values.length; i < ic; ++i)
				this.DelCurrentValue(values[i]);
		}
	}
	,DelCurrentValue: function(value) {
		if (this.currentValues) {
			var res = [];
			for (var i = 0, j = 0, ic = this.currentValues.length; i < ic; ++i)
				if (value.value == this.currentValues[i].value)
					continue;
				else
					res[j++] = this.currentValues[i];
			this.currentValues = res;
		}
	}
	,IsEqualValues: function(values) {
		if (this.currentValues == null)
			return (values == null)? true : false;
		else
		{
			if (values == null) 
				return false;
			if (this.currentValues.length != values.length)
				return false;
			else
			{
				for (var i = 0, ic = values.length; i < ic; ++i)
					if (values[i].value != this.currentValues[i].value)
						return false;
				return true;
			}
		}
	}
	,GetTagName: function() { return this.tagName }
	,GetValues: function() {
		if (this.getHandler) 
			return this.getHandler(this.id);
	}
	,GetAttributes: function() {
		if (this.getAttrHandler)
			return eval(this.getAttrHandler)(this.id); 
	}
	,SetValues: function(values) {
		if (!this.IsEqualValues(values)) {
			if (this.setHandler) {
				this.setHandler(this.id, values);
				this.SetCurrentValues(values);
			}
		}
	}
});
//---------------- Manager ----------------
DeclareClass("UI.AS.Manager", null, {
	constructor : function() {
		this.__modules = [];
		this.__orders = [];
		this.__expandedmodules = [];
		this.__tagsorder = [];
		this.__customtagsorder = [];
		this.__emptycount = 3;
		this.__uniquePrefix = "__a__";
		this.__ExpandSectiosHandler = this.CreateCallback(this.ExpandSections);
		this.Listener = new Utils.SavedSearchEventListener([SRCH_TN_SAVEDSEARCH], this.__ExpandSectiosHandler);
		this.Listener.Attach();
		this.Listener = new AS.EventClearListener(this.__ExpandSectiosHandler);
		this.Listener.Attach();
		GlobalAdvancedSearchEventManager.AttachEvent("onloaddatafrominput", this.CreateCallback(this.ExpandSections));
		
		this.Listener = new AS.EventListener(this.CreateCallback(this.OnAdvancedSearchXmlChange));
		this.Listener.Attach();
		this.__allowUpdateModule = true;
		this.customcollection = new dm_KeyedCollection();
		this.__lockchangexml = false;
		this.customscopecollection = new dm_KeyedCollection();
		this.__customorders = [];
		
		if (TPSearchTagsOrderArray) {
			for (var i = 0, ic = TPSearchTagsOrderArray.length; i < ic; ++i) {
				var tagname = TPSearchTagsOrderArray[i].name, order = TPSearchTagsOrderArray[i].order;
				this.__orders[this.__GetUniqueTagName(tagname)] = order;
				this.__tagsorder[order] = tagname;
			}
		}
		this.customexpandedmodules = new dm_KeyedCollection();
		this.custommanualopenedmodules = [];
		this.AnalyzeAdvancedSearchXml();
	}
	,RegisterExpandCustomSection: function(tagName, id, formid) {
		this.customexpandedmodules.Add(tagName, {"id": id, "formid":formid});
		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_NAME, tagName)]);
		if (tags.length != 0)
			this.ExpandCustomSection(tagName, true); 
	}
	,GetPID: function () {
		var	pid, spid = null;
		if (nav_IsNavigationEnabled())
			pid = nav_currentNavInfo.GetPageID();	
		if (srch_advGetDecimalSearchID() > 0)
			spid = srch_advGetPID();
		if (!str_IsStringEmpty(spid))
			pid = spid;
		return pid;
	}
	,ExpandCustomSection: function(tagName, isOpen) {
		var section = this.customexpandedmodules.Get(tagName);
		if (!section) return;
		var id = section.id, formid = section.formid;
		if (typeof(isOpen)=="undefined")
		{
			var show;
			var obj = document.getElementById(id);
			if (obj) {
				show = eval(obj.isopen);
				if (show == false)
					this.custommanualopenedmodules[this.__GetUniqueTagName(tagName)] = true;
				else
					this.custommanualopenedmodules[this.__GetUniqueTagName(tagName)] = false;
				
				obj.isopen = !show;
				obj.src = (obj.isopen == true)?cmn_GetImageUrl("icon_tree_minus_15height.gif"):cmn_GetImageUrl("icon_tree_plus_15height.gif");
			}
			var obj = document.getElementById(formid);
			if (obj) {
				obj.style.display = show ? "none" : "block";
				if (!show && obj.tpl_dynamicElement != null)
					obj.tpl_dynamicElement.OnDisplayChange(true);
			}
		}
		else
		{
			if (isOpen == false && this.custommanualopenedmodules[this.__GetUniqueTagName(tagName)] == true)
				return;
			var obj = document.getElementById(id);
			if (obj) {
				obj.isopen = isOpen;
				obj.src = (obj.isopen == true)?cmn_GetImageUrl("icon_tree_minus_15height.gif"):cmn_GetImageUrl("icon_tree_plus_15height.gif");
			}
			var obj = document.getElementById(formid);
			if (obj) {
				obj.style.display = isOpen ? "block" : "none";
				if (!show && obj.tpl_dynamicElement != null)
					obj.tpl_dynamicElement.OnDisplayChange(true);
			}
		}
	}
	,RegisterModuleForTag: function(tags,module) {
		if (!tags) return;
		for(var i = 0, ic = tags.length; i < ic; ++i) {
			var tagname = tags[i], uniqueTagName = this.__GetUniqueTagName(tagname);
			if (module) {
				if (!this.__modules[uniqueTagName])
					this.__modules[uniqueTagName] = [];					
				this.__modules[uniqueTagName].push(module);
				if (this.__expandedmodules[uniqueTagName] == false || this.__counttoshow > 0)
				{
					this.ExpandModule(tagname);
					this.__counttoshow = this.__counttoshow - 1;
				}
			}
		}
	}
	,ResetCustomControls: function() {
		this.customcollection = new dm_KeyedCollection();
		this.__customorders = [];
		this.__customtagsorder = [];
		this.customexpandedmodules = new dm_KeyedCollection();
		this.customscopecollection = new dm_KeyedCollection();
		this.custommanualopenedmodules = [];
	}
	,GetScopeControl: function(id) {
		return this.customscopecollection.Get(id);
	}
	,RegisterCustomScopeControl: function(id, control) {
		this.customscopecollection.Add(id, control);
		for (var i = 0, ic = this.customcollection.getCount(); i<ic; ++i) {
			var ctrl = this.customcollection.GetByIndex(i);
			if (ctrl.scopeControlId == id) {
				control.SetValue(ctrl.searchScopeValue, false);
				break;
			}
		} 
	}
	,CustomOnChangeSearchScope: function(value, isInitializing, id) {
		for (var i = 0, ic = this.customcollection.getCount(); i<ic; ++i) {
			var ctrl = this.customcollection.GetByIndex(i);
			if (ctrl.scopeControlId == id) {
				ctrl.OnChangeSearchScope(value);
				break;
			}
		}
	}
	,RegisterCustomControl: function(tagName,id,getValuesHandler,setValuesHandler,getAttributesHandler, 
		scopeControlId, getValidationHandler)
	{
		var ctr = new AS.CustomControls(id, tagName, getValuesHandler, 
			setValuesHandler, getAttributesHandler, scopeControlId, getValidationHandler);
		this.customcollection.Add(tagName, ctr);
		
		if (!this.__customorders[this.__GetUniqueTagName(tagName)])
		{
			this.__customorders[this.__GetUniqueTagName(tagName)] = this.__tagsorder.length + this.__customtagsorder.length; 
			this.__customtagsorder.push(tagName);
		}
		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_TAGTYPE, SRCH_TT_CUSTOM)]);
		var valxml = [], tagScope = null;
		for (var j = 0, jc = tags.length; j < jc; ++j) {
			var tn = tags[j].selectSingleNode(SRCH_TP_NAME);
			if (tn) {
				if (tn.text != tagName)
					continue;
				else
				{
					var values = tags[j].selectSingleNode(SRCH_TP_VALUE);
					if (values)
					{
						if (!tagScope) {
							tagScope = tags[j].selectSingleNode(SRCH_TP_TAGSCOPE);
							if (tagScope) tagScope = tagScope.text;
						}
						valxml[valxml.length] = values.text;
					}
				}
			}
		}
		this.__lockchangexml = true;
		if (!tagScope) tagScope = SRCH_TS_ANY;
		ctr.searchScopeValue = tagScope;
		var ssctrl = this.customscopecollection.Get(ctr.scopeControlId);
		if (ssctrl) 
			ssctrl.SetValue(tagScope, false);
		if (valxml.length != 0)
			this.ExpandCustomSection(tagName, true);
		ctr.SetValues(valxml);
		this.__lockchangexml = false;
	}
	,GetOrder: function(tagname) {
		var utn = this.__GetUniqueTagName(tagname);
		var order = this.__orders[utn];
		if (order == null)
			order = this.__customorders[utn];
		return order;
	}
	,__GetUniqueTagName: function(tagname) {
		return this.__uniquePrefix + tagname; 
	}
	,__IsUniqueTagName: function(tagname) {
		return tagname.indexOf(this.__uniquePrefix) != -1;
	}
	,__RestoreTagName: function(tagname) {
		return tagname.substr(tagname.indexOf(this.__uniquePrefix) + this.__uniquePrefix.length);
	}
	,ExpandModule: function(tagname) {
		var expandedmodules = null, uniqueTagName = this.__GetUniqueTagName(tagname);
		
		var array = this.__expandedmodules[uniqueTagName]
		if (!array)
			array = this.__modules[uniqueTagName];
		if (array) {
			expandedmodules = [];
			for (var j = 0, jc = array.length; j < jc; ++j) {
				var expandedModule = array[j];
				if (expandedModule && !expandedModule.Expanded)
					expandedModule.Expand();
				 expandedmodules.push(expandedModule);				
			}
			this.__expandedmodules[uniqueTagName] = expandedmodules;	
			return true;
		}
		return false;
	}
	,AnalyzeAdvancedSearchXml: function() {
		var isDefaultSearch = srch_advIsDefaultSearch();
		this.__counttoshow = this.__emptycount;
		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_TAGTYPE, SRCH_TT_STD)]);
		if (!tags) return;
		var count = tags.length, lastTagName = null;
		var tagNames = [];
		if (IS_TMC_USER && isDefaultSearch)
		{
			this.__counttoshow = 1;
		}
		else
		{		
			for (var i = 0; i < count; ++i) {
				var tagname = tags[i].selectSingleNode(SRCH_TP_NAME);
				if (tagname) { 
					tagname = tagname.text;
					if (lastTagName == tagname) continue;
					lastTagName = tagname;
					this.__expandedmodules[this.__GetUniqueTagName(tagname)] = false;
					if (isDefaultSearch && tagname != SRCH_TN_PERIOD && !tagNames[tagname])
					{
						this.__counttoshow = this.__counttoshow - 1;
						tagNames[tagname] = true;
					}
					if (!isDefaultSearch && tagname != SRCH_TN_PERIOD)
					{
						this.__counttoshow = 0;
					}
				}
			}
		}
		
		for (var tagname in this.__modules)
			if (this.__IsUniqueTagName(tagname)) {
				var modules = this.__modules[tagname];
				if (!modules) continue;
				for(var i = 0, ic = modules.length; i < ic; ++i)
					if (modules[i] && modules[i].Expanded)
						modules[i].Collapse();
			}
		/*for (var tagname in this.__expandedmodules) {
			if (this.__IsUniqueTagName(tagname)) {
				var modules = this.__expandedmodules[tagname];
				if (!modules) continue;
				for(var i = 0, ic = modules.length; i < ic; ++i)
					if (modules[i] && modules[i].Expanded)
						modules[i].Collapse();
			}
		}*/
	}	
	,ExpandSections: function() {
		this.AnalyzeAdvancedSearchXml();
		var cntshow = this.__counttoshow;
		if (cntshow > 0) {
			for(var i = 0, to = this.__tagsorder, ic = to.length; i < ic && cntshow > 0; ++i) {
				if (this.ExpandModule(to[i]))
					--cntshow;
			}
		}
		this.__counttoshow = cntshow;
		var em = this.__expandedmodules; 
		for (var tagname in em)
			if (this.__IsUniqueTagName(tagname) && em[tagname] == false)
				this.ExpandModule(this.__RestoreTagName(tagname));
	}
	,DUM: function() {
		this.__allowUpdateModule = false;
	}
	,AUM: function() {
		this.__allowUpdateModule = true;
	}
	,GetAUM: function() {
		return this.__allowUpdateModule;
	}
	,OnCustomControlChange: function(id, tagName) {
		if (this.__lockchangexml)
			return;
		var customControl = this.customcollection.Get(tagName);
		if (!customControl || !this.CheckValues(customControl)) return;
		
	    var values = customControl.GetValues();
	    
	    if ((values == null) || (values.length == 1 && str_IsStringEmpty(values[0].text)))
			values = [];
			
		if (customControl.IsEqualValues(values) == true)
			return;
		else
			customControl.SetCurrentValues(values);		
			
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		srch_advDeleteTags(tagName, null, (values.length != 0) ? false : true);
		
		var attr = customControl.GetAttributes();
		
		var occurrence = null;
		for(var i=0, ic = values.length; i<ic; ++i) {
			var new_attributes = attr.slice(0);
			new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_DISPLAYVALUE, values[i].text));
			new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_TAGSCOPE, customControl.GetSearchScopeValue()));
			srch_advAddTag(tagName, values[i].value, new_attributes, occurrence, i == ic-1);
		}
		srch_ShowWarningMessage();
		
		if (aum) GlASM.AUM();
	}
	,OnAdvancedSearchXmlChange: function()
	{
		if (GlASM.GetAUM()) {
			if (this.customcollection && this.customcollection.getCount() > 0) {
				var customControl = null;
				var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_TAGTYPE, SRCH_TT_CUSTOM)]);
				if (!tags) return;
				for (var i = 0, ic = this.customcollection.getCount(); i < ic; ++i) {
					customControl = this.customcollection.GetByIndex(i);
					var tagName = customControl.GetTagName(), valxml = [], tagScope = null;;
					for (var j = 0, jc = tags.length; j < jc; ++j) {
						var tn = tags[j].selectSingleNode(SRCH_TP_NAME);
						if (tn) {
							if (tn.text != tagName)
								continue;
							else
							{
								var values = tags[j].selectSingleNode(SRCH_TP_VALUE);
								if (values)
								{
									if (!tagScope) {
										tagScope = tags[j].selectSingleNode(SRCH_TP_TAGSCOPE);
										if (tagScope) tagScope = tagScope.text;
									}
									valxml[valxml.length] = values.text;
								}
							}
						}
					}
					this.__lockchangexml = true;
					if (!tagScope) tagScope = SRCH_TS_ANY;
					customControl.searchScopeValue = tagScope;
					var ssctrl = this.customscopecollection.Get(customControl.scopeControlId);
					if (ssctrl) 
						ssctrl.SetValue(tagScope, false);
					customControl.SetValues(valxml);
					this.ExpandCustomSection(customControl.GetTagName(), (valxml.length != 0)?true:false);
					this.__lockchangexml = false;
				}						
			}
		}
	}
	,AddCustomValue: function(tagName, value) {
		if (this.__lockchangexml)
			return;
		if (!value) return;
		var customControl = this.customcollection.Get(tagName);
		if (!customControl || !this.CheckValues(customControl)) 
			return;
		customControl.AddCurrentValue(value);
		
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		var attr = customControl.GetAttributes(), 
			occurrence = null; 
		var new_attributes = attr.slice(0);
		new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_DISPLAYVALUE, value.text));
		new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_TAGSCOPE, customControl.GetSearchScopeValue()));
		srch_advAddTag(tagName, value.value, new_attributes, occurrence, true);
		srch_ShowWarningMessage();
		
		if (aum) GlASM.AUM();
	}
	,DelCustomValue: function(tagName, value) {
		if (this.__lockchangexml)
			return;
		if (!value) return;
		var customControl = this.customcollection.Get(tagName);
		if (!customControl) 
			return;
		customControl.DelCurrentValue(value);
		
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		srch_advDeleteTag(tagName, value.value, true);
		
		if (aum) GlASM.AUM();
	}
	,AddCustomValues: function(tagName, values, force) {
		if (this.__lockchangexml) return;
		var customControl = this.customcollection.Get(tagName);
		if (!customControl || !this.CheckValues(customControl)) return;		
		if (!values)
		{
			var values = customControl.GetValues();
			if ((values == null) || (values.length == 1 && str_IsStringEmpty(values[0].text)))
				values = [];
		}
		force=(typeof(force)!="undefined")?force:false;
		if (!force) {
			if (customControl.IsEqualValues(values) == true)
				return;
			else
				customControl.SetCurrentValues(values);
		}
		
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		srch_advDeleteTags(tagName, null, (values.length != 0) ? false : true);
		
		var attr = customControl.GetAttributes();
		var occurrence = null;
		for(var i=0, ic = values.length; i<ic; ++i) {
			var new_attributes = attr.slice(0);
			new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_DISPLAYVALUE, values[i].text));
			new_attributes.push(new srch_XmlSearchExParam(SRCH_TP_TAGSCOPE, customControl.GetSearchScopeValue()));
			srch_advAddTag(tagName, values[i].value, new_attributes, occurrence, i == ic-1);
		}
		srch_ShowWarningMessage();
		
		if (aum) GlASM.AUM();
	}
	,CheckValues : function(customControl) {
		if (customControl.getValidationHandler)
			return eval(customControl.getValidationHandler)();
		return true;
	}
});
//--------------------- Module ----------------------------
DeclareClass("UI.AS.Module", "UI.Controls.CollapsibleControl", {
	constructor: function(title) {
		this.base(false);
		
		this.header = null;
		this.form = null;
		this.title = title;
		this.AsyncRenderingEnabled = true;
		this.RegisterModule();
		this.SetCssClass("sa-module");
	}
	,RegisterModule : [decl_virtual, function() {
		as_RegisterModuleForTag(this.GetSearchTags(), this);
	}]
	,Dispose: [decl_virtual, function() {
		this.header = null;
		this.form = null;
		this.base.Dispose();
	}]
	,GetTagName: function() { return UI.HtmlTag.Div }
	,GetSearchTags: function() { return null }
	,Init: [decl_virtual, function() {
		this.base.Init();
		
		this.form = this.GetModule();
		this.header = this.CreateHeader();

		this.AddUIControlToHeader(this.header);
		this.AddUIControlToContent(this.form);
	}]
	,CreateHeader: [decl_virtual, function() {
		var header = new UI.Controls.CollapsibleHeaderControl(this.title, this.Expanded, this);
		header.SetCssClass("sa-title");
		header.SetTextCssClass("");
		header.SetImages("icon_tree_plus_15height.gif", "icon_tree_minus_15height.gif");
		return header;
	}]
	,GetModule: function() { return new UI.AS.ModuleForm() }
	,SetHeaderText: function(text) {
		this.title = text;
		if (this.header)
			this.header.SetText(text);
	}
});
//--------------------- Selector ----------------------------
DeclareClass("UI.AS.Selector", "UI.Control", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base();
		this.handler = null;
		this.leftTitle = leftTitle;
		this.rightTitle = rightTitle;
		this.leftCell = null;
		this.rightCell = null;
		this.cache = cache;
		this.leftListBox = null;
		this.rightListBox = null;
		this.isStatic = isStatic;
		this.curr__TagsValue = null;
		this.imgDelete = null;
	}
	,Dispose: [decl_virtual, function() {
		this.handler = null;
		this.cache = null;
		this.leftCell = null;
		this.rightCell = null;
		this.leftListBox = null;
		this.rightListBox = null;
		this.curr__TagsValue = null;
		this.imgDelete = null;
		this.base.Dispose();
	}]
	,SetHandler: function(handler) { this.handler = handler }
	,ClearSelector: [decl_virtual, function() {
		if (this.leftListBox && !this.isStatic)
			this.leftListBox.Clear();
	}]
	,CreateLeftListBox: function() { return new UI.Controls.TPListBox("100%", "125px") }
	,CreateRightListBox: function() { return new UI.Controls.TPListBox("100%", "125px") }
	,LoadFromCache: function() {
		this.leftListBox.Clear();
		if (this.cache) {
			var values = [], ic = this.cache.length;
			if (ic > 0) {
				var items = this.rightListBox.GetItems()
				if (typeof(this.cache[0]) == "object") 
					for(var i = 0, k = 0; i < ic; ++i) {
						var cv = this.cache[i]["value"], flag = true; 
						for (var j = 0, jc = items.length; j < jc; ++j) {
							if (cv == items[j].value) {
								flag = false;
								break;	
							}
						}
						if (flag)
							values[k++] = this.cache[i];  
					}
				else 
					for(var i = 0, k = 0; i < ic; ++i) {
						var cv = this.cache[i], flag = true; 
						for (var j = 0, jc = items.length; j < jc; ++j) {
							if (cv == items[j].value) {
								flag = false;
								break;	
							}						
						}
						if (flag)
							values[k++] = this.cache[i]; 
					}
			}
			this.leftListBox.LoadFromCache(values);
		}
	}
	,Init: [decl_virtual, function() {
		this.leftListBox = this.CreateLeftListBox();
		this.rightListBox = this.CreateRightListBox();

		if (this.leftListBox) {
			this.AddControl(this.leftListBox);
			this.leftListBox.Clear();
			this.leftListBox.AddValue("Loading...", "@loading@");
			window.setTimeout(this.CreateCallback(this.LoadFromCache) , 1000);
		}
		if (this.rightListBox) 
			this.AddControl(this.rightListBox);
		
		this.SetTagsValue();
	}]
	,RenderActionRow: [decl_virtual, function(row) {
		row.insertCell().className = "sa-sel-acl"; 
		row.insertCell().className = "sa-sel-cp"; 
		var	rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		this.imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
	    this.imgDelete.AttachEvent("click", this.CreateCallback(this.OnRightDeleteSelected));
	    
		var td = new UI.DOMControls.Td();
		td.SetCssClass("sa-sel-arcl");
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		
		rightCell.appendChild(table.Obj());
	}]
	,RenderInputRow: [decl_virtual, function(row) {
		var tdLeft = row.insertCell();
		tdLeft.className = "sa-sel-td";
		this.leftListBox.RenderControl(tdLeft);
		
		var tdMiddle = row.insertCell();
		tdMiddle.className = "sa-sel-cp";
		var img = new UI.DOMControls.Image("search-adv-right-arrow.gif", "sa-sel-ari");
	    img.AttachEvent("click", this.CreateCallback(this.OnClick));
	    tdMiddle.appendChild(img.Obj());
	    
		var tdRight = row.insertCell();
		tdRight.className = "sa-sel-td";
		this.rightListBox.RenderControl(tdRight);
	}]
	,Render: [decl_virtual, function() {
		var he = this.HostElement;
		he.className = "sa-sel-t";
		he.cellPadding = 0;
		he.cellSpacing = 2;
		var row = he.insertRow();
		
		this.leftCell = row.insertCell();
		row.insertCell().className = "sa-sel-cp";
		this.rightCell = row.insertCell();

		var row = he.insertRow();
		row.className = "search-action-row";
		this.RenderInputRow(he.insertRow());
		this.RenderActionRow(row);
		
		this.leftCell.innerText = this.leftTitle;
		this.rightCell.innerText = this.rightTitle;
	}]
	,OnRightDeleteSelected: [decl_virtual, function() {
		var items = this.rightListBox.GetSelectedItems();
		if (this.isStatic == true)
		{
			if (this.rightListBox.GetItemCount() == items.length)
				this.FireEvent("onmoveallitemstoleft", this.handler.GetTagName());
			else  
				this.FireEvent("onmoveitemstoleft", items);
			
			this.rightListBox.DeleteSelected();
			if (this.leftListBox)
				this.leftListBox.AddValues(items, false, "text", true);
		}
		else
		{
			if (this.rightListBox.GetItemCount() == items.length)
			{
				var tag = this.handler.GetTagName();
				this.rightListBox.DeleteSelected();
				this.FireEvent("ondeleteallitemsfromright", tag);
			}
			else
			{  
				this.rightListBox.DeleteSelected();
				this.FireEvent("ondeleteitemsfromright", items);
			}	
		}
	}]
	,GetTagName: function() { return UI.HtmlTag.Table }
	,OnClick: [decl_virtual, function() {
		var items = this.leftListBox.GetSelectedItems();
		if (!items) { 
			return;
		}
		else 
		{
			var len = items.length;
			if (len == 0) {
				return;
			}
			else if (len == 1) {
				var v = items[0].value;
				if (v == "@loading@" || v == "@search@" || v == "@message@")
					return;
			}
		}
		var movedItems = this.leftListBox.MoveSelectRows(this.rightListBox, true);
		this.FireEvent("onclick", movedItems);		
	}]
	,SetTagsValue: function() {
		if (this.rightListBox)
			this.__TagsInXml(this.curr__TagsValue);
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.curr__TagsValue = tags;
		this.SetTagsValue();
	}]
	,__TagsInXml: [decl_virtual, function(tags) {
		if (!tags) return;
		var rlb = this.rightListBox, llb = this.leftListBox;
		if (!tags || tags.length == 0) 
		{
			if (rlb) {
				if (this.isStatic) {
					if (this.leftListBox) 
						rlb.MoveAllRows(this.leftListBox);
					else
						rlb.Clear();
				}
				else
					rlb.Clear();
			}
			this.ClearSelector();
		} 
		else 
		{
			var values = [], 
				dispval = [];
			for (var i = 0, ic = tags.length; i < ic; ++i)
			{
				values[i] = tags[i].selectSingleNode(SRCH_TP_VALUE);
				dispval[i] = tags[i].selectSingleNode(SRCH_TP_DISPLAYVALUE);
			}
			
			for (var i = 0, ic = values.length; i < ic; ++i)
			{
				var name = dispval[i].text, val = values[i].text;
				rlb.AddValue(name, val, rlb.GetSortedIndex(name), true);
				if (llb)
					llb.DelByValue(val);
			}			
				
			var items = rlb.GetItems();
			for (var i = 0, ic = items.length; i < ic; ++i)
			{
				var val = items[i].value;
				var flag = false;
				for (var j = 0, jc = values.length; j < jc; ++j)
					if (values[j].text == val)
					{
						flag = true;
						break;
					}
				if (flag == false)
				{
					var name = items[i].text;
					rlb.DelByValue(val);
					if (llb && this.isStatic)
						llb.AddValue(name, val, llb.GetSortedIndex(name), true);
				}
			}
		}
	}]
	,GetSelectedItems: function() { return (this.rightListBox) ? this.rightListBox.GetItems() : null }
	,AddToLeftListBox: function(values, sorted) {
		if (this.leftListBox)
			this.leftListBox.AddValues(values, true, "name", sorted);
	}
	,AddToRightListBox: function(values) {
		if (!values) return;
		
		var res = [], rlb = this.rightListBox;
		for (var i = 0, j = 0, ic = values.length; i < ic; ++i)
		{
			var name = values[i].name, value = values[i].value;
			if (rlb.AddValue(name, value, rlb.GetSortedIndex(name), true))
				res[j++] = {"text":name,"value":value};
		}
		return res;
	}
	,ClearLeftListBox: function() {
		if (this.leftListBox)
			this.leftListBox.Clear();
	}
	,AddPredefinedValues: function() { }
});
//-------------------------------------------------
DeclareClass("UI.AS.ActionBox", null, {
	constructor: function(scope, listBox, AddControl, AddHandler, DelControl, DelHandler) {
		this.Scope = scope;
		this.ListBox = listBox;
		this.AddControl = AddControl;
		this.AddControl.AttachEvent("click", this.CreateCallback(this.OnClick))
		this.AddHandler = AddHandler;
		this.DelControl = DelControl;
		this.DelControl.AttachEvent("click", this.CreateCallback(this.OnDel));
		this.DelHandler = DelHandler;
		this.PrimaryTicker = null;
		this.TickerHandler = null;
	}
	,SetPrimaryTicker: function(primaryTicker, tickerHandler) {
		this.PrimaryTicker = primaryTicker;
		this.TickerHandler = tickerHandler;
		this.PrimaryTicker.AttachEvent("onclick", this.CreateCallback(this.OnPrimaryClick));
	}
	,OnPrimaryClick: function(checked, value, isInst) {
		this.TickerHandler(checked, value, isInst, this.Scope, this.ListBox)		
	}
	,OnClick : function() { this.AddHandler(this.Scope, this.ListBox); }
	,OnDel : function() { this.DelHandler(this.Scope, this.ListBox); }
});
//--------------------- MultiSelector ----------------------------
DeclareClass("UI.AS.MultiSelector", "UI.Control", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base();
		this.handler = null;
		this.leftTitle = leftTitle;
		this.rightTitle = rightTitle;
		this.leftCell = null;
		this.rightCell = null;
		this.cache = cache;
		this.leftListBox = null;
		this.rightListBox = null;
		this.isStatic = isStatic;
		this.curr__TagsValue = null;
		this.imgDelete = null;
		
		this.rightListBoxes = [];
	}
	,Dispose: [decl_virtual, function() {
		this.handler = null;
		this.cache = null;
		this.leftCell = null;
		this.rightCell = null;
		this.leftListBox = null;
		this.rightListBox = null;
		this.curr__TagsValue = null;
		this.imgDelete = null;
		
		this.rightListBoxes = null;
		
		this.base.Dispose();
	}]
	,GetScopePostfixText: function() { return " of the Items"; }
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.All, UI.AS.Scope.ExcludeAny]; }
	,SetHandler: function(handler) { this.handler = handler; }
	,ClearSelector: [decl_virtual, function() {
		if (this.leftListBox && !this.isStatic)
			this.leftListBox.Clear();
	}]
	,ClearSelected: function(fireEvent)
	{
		var scopeTags = this.GetScopeTags();
		for (var k = 0, kc = scopeTags.length; k < kc; ++k)
		{
			var item = this.rightListBoxes[scopeTags[k]];
			if (!item) continue;
				
			var rlb = item.ListBox;
			if (!rlb) continue;
			
			var items = rlb.GetItems();
			
			if (this.isStatic == true)
			{	
				if (this.leftListBox)
					this.leftListBox.AddValues(items, false, "text", true);		
			}
			else
			{
				for (var i = 0, ic = items.length; i < ic; ++i)
					rlb.DelByValue(items[i].value);			
			}
		}
	}
	,CreateLeftListBox: function() { return new UI.Controls.TPListBox("100%", "415px"); }
	,CreateRightListBox: function() { return new UI.Controls.TPListBox("100%", "125px"); }
	,LoadFromCache: function() {
		this.leftListBox.Clear();
		
		if (this.cache) {
			var values = [], ic = this.cache.length;
			if (ic > 0) {
				var items = null;
				var scopeTags = this.GetScopeTags();
				for (var k = 0, kc = scopeTags.length; k < kc; ++k) {
					var item = this.rightListBoxes[scopeTags[k]];
					if (!item) continue;
				
					var rlb = item.ListBox;
					if (!rlb) continue;
					
					if (items == null)
						items = this.rlb.GetItems();
					else
					{
						var listItems = this.rlb.GetItems();
						for (var i = 0, ic = listItems.length; i < ic; ++i)
							items.push(listItems[i]);
					}
				}
				
				if (typeof(this.cache[0]) == "object") { 
					for(var i = 0, k = 0; i < ic; ++i) 
					{
						var cv = this.cache[i]["value"], flag = true; 
						for (var j = 0, jc = items.length; j < jc; ++j) 
						{
							if (cv == items[j].value) 
							{
								flag = false;
								break;	
							}
						}
						if (flag)
							values[k++] = this.cache[i];  
					}
				}
				else 
				{
					for(var i = 0, k = 0; i < ic; ++i) {
						var cv = this.cache[i], flag = true; 
						for (var j = 0, jc = items.length; j < jc; ++j) {
							if (cv == items[j].value) {
								flag = false;
								break;	
							}						
						}
						if (flag)
							values[k++] = this.cache[i]; 
					}
				}
			}
			this.leftListBox.LoadFromCache(values);
		}
	}
	,Init: [decl_virtual, function() {
		this.leftListBox = this.CreateLeftListBox();
		this.rightListBox = this.CreateRightListBox();
		
		this.imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
		
		var scopeTags = this.GetScopeTags();
		for (var i = 0, ic = scopeTags.length; i < ic; ++i) {
			var actionBox = null;
			if (i == 0) {
				var img = new UI.DOMControls.Image("search-adv-right-arrow.gif", "sa-sel-ari");
				actionBox = new UI.AS.ActionBox(scopeTags[i], this.rightListBox, img, 
					this.CreateCallback(this.ActionBoxHandler), this.imgDelete, this.CreateCallback(this.ActionBoxDel));
			}
			else
			{
				var img = new UI.DOMControls.Image("search-adv-right-arrow.gif", "sa-sel-ari");
				var imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
			
				actionBox = new UI.AS.ActionBox(scopeTags[i], this.CreateRightListBox(), img, 
					this.CreateCallback(this.ActionBoxHandler), imgDelete, this.CreateCallback(this.ActionBoxDel));
			}
				
			this.rightListBoxes[scopeTags[i]] = actionBox;
			if (this.rightListBoxes[scopeTags[i]].ListBox)
				this.AddControl(this.rightListBoxes[scopeTags[i]].ListBox);
		}

		if (this.leftListBox) {
			this.AddControl(this.leftListBox);
			this.leftListBox.Clear();
			this.leftListBox.AddValue("Loading...", "@loading@");
			window.setTimeout(this.CreateCallback(this.LoadFromCache) , 1000);
		}
		
		this.SetTagsValue();
	}]
	,ActionBoxHandler: function(scope, listBox) { this.OnClick(scope, listBox); }
	,ActionBoxDel: function(scope, listBox) { this.OnRightDeleteSelected(scope, listBox); }
	,GetScopePrefixText: function(tag) { return uiasc_GetDisplayScopeByValue(uiasc_GetServerByClientScope(tag)); }
	,GetScopeTextClass: function() { return null; }
	,RenderActionRow: [decl_virtual, function(row) {
		row.insertCell().className = "sa-sel-acl"; 
		row.insertCell().className = "sa-sel-cp"; 
		var	rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
	    
	    var scopeTags = this.GetScopeTags();
	    var text = new UI.DOMControls.Text(this.GetScopePrefixText(scopeTags[0]) + this.GetScopePostfixText());
	    if (this.GetScopeTextClass())
			text.SetCssClass(this.GetScopeTextClass());
		var td = new UI.DOMControls.Td(text);
		td.SetCssClass("sa-sel-arcl");
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		
		rightCell.appendChild(table.Obj());
	}]
	,RenderInputRow: [decl_virtual, function(hostElement, scopeTag, num) {
		if (num == 0) {
			var row = hostElement.insertRow();
			var tdLeft = row.insertCell();
			tdLeft.className = "sa-sel-td";
			tdLeft.rowSpan = 5;
			this.leftListBox.RenderControl(tdLeft);
			
			var tdMiddle = row.insertCell();
			tdMiddle.className = "sa-sel-cp";
			tdMiddle.appendChild(this.rightListBoxes[scopeTag].AddControl.Obj());
	    
			var tdRight = row.insertCell();
			tdRight.className = "sa-sel-td";
			this.rightListBoxes[scopeTag].ListBox.RenderControl(tdRight); 
		}
		else
		{
			var row = hostElement.insertRow();
			
			row.insertCell().className = "sa-sel-cp"; 
			var	rightCell = row.insertCell();
			rightCell.className = "sa-sel-acr"; 
	    
			var text = new UI.DOMControls.Text(this.GetScopePrefixText(scopeTag) + this.GetScopePostfixText());
			if (this.GetScopeTextClass())
				text.SetCssClass(this.GetScopeTextClass());
			var td = new UI.DOMControls.Td(text);
			td.SetCssClass("sa-sel-arcl");
			var table = new UI.DOMControls.Table(
				new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.rightListBoxes[scopeTag].DelControl)));
			this.rightListBoxes[scopeTag].LeftCell = td;
		
			rightCell.appendChild(table.Obj());
			
			row = hostElement.insertRow();
			var tdMiddle = row.insertCell();
			tdMiddle.className = "sa-sel-cp";
			tdMiddle.appendChild(this.rightListBoxes[scopeTag].AddControl.Obj());
	    
			var tdRight = row.insertCell();
			tdRight.className = "sa-sel-td";
			this.rightListBoxes[scopeTag].ListBox.RenderControl(tdRight); 
		}
	}]
	,Render: [decl_virtual, function() {
		var he = this.HostElement;
		he.className = "sa-sel-t";
		he.cellPadding = 0;
		he.cellSpacing = 2;
		var row = he.insertRow();
		
		this.leftCell = row.insertCell();
		row.insertCell().className = "sa-sel-cp";
		this.rightCell = row.insertCell();

		var row = he.insertRow();
		row.className = "search-action-row";
		
		var scopeTags = this.GetScopeTags();
		for (var i = 0, ic = scopeTags.length; i < ic; ++i)
			this.RenderInputRow(he, scopeTags[i], i);
		this.RenderActionRow(row);
		
		this.leftCell.innerText = this.leftTitle;
		this.rightCell.innerText = this.rightTitle;
	}]
	,OnRightDeleteSelected: [decl_virtual, function(scope, listBox) {
		var allSelectedItems = 0;
		var scopeTags = this.GetScopeTags();
		for (var i = 0, ic = scopeTags.length; i < ic; ++i) {
			var lb = this.rightListBoxes[scopeTags[i]].ListBox;
			if (lb)
				allSelectedItems += lb.GetItemCount();
		}

		var items = listBox.GetSelectedItems();
		if (this.isStatic == true) {
			if (allSelectedItems == items.length)
				this.FireEvent("onmoveallitemstoleft", this.handler.GetTagName(), scope);
			else  
				this.FireEvent("onmoveitemstoleft", items, scope);
			
			listBox.DeleteSelected();
			if (this.leftListBox)
				this.leftListBox.AddValues(items, false, "text", true);
		}
		else
		{
			if (allSelectedItems == items.length)
			{
				listBox.DeleteSelected();
				this.FireEvent("ondeleteallitemsfromright", this.handler.GetTagName(), scope);
			}
			else
			{  
				listBox.DeleteSelected();
				this.FireEvent("ondeleteitemsfromright", items, scope);
			}	
		}
	}]
	,GetTagName: function() { return UI.HtmlTag.Table; }
	,GetTicker: [decl_virtual, function(scope) { return null; }]
	,AllowAddition: [decl_virtual, function(items) {
		return true;
	}]
	,OnClick: [decl_virtual, function(scope, listBox) {
		var items = this.leftListBox.GetSelectedItems();
		if (!items) 
		{ 
			return;
		}
		else 
		{
			var len = items.length;
			if (len == 0) 
			{
				return;
			}
			else if (len == 1) 
			{
				var v = items[0].value;
				if (v == "@loading@" || v == "@search@" || v == "@message@")
					return;
			}
		}
		
		if (this.AllowAddition(items))
		{
			var scopeTags = this.GetScopeTags();
			for (var k = 0, kc = scopeTags.length; k < kc; ++k)
			{
				var item = this.rightListBoxes[scopeTags[k]];
				if (!item) continue;
				
				var rlb = item.ListBox;
				if (!rlb) continue;
			
				if (rlb == listBox)
					continue;
				
				for (var i = 0, ic = items.length; i < ic; ++i)
					rlb.DelByValue(items[i].value);
			}
			var movedItems = this.leftListBox.MoveSelectRows(listBox, true);
			this.FireEvent("onclick", movedItems, scope, this.GetTicker(scope));
		}
	}]
	,SetTagsValue: function() {
		if (this.rightListBox)
			this.__TagsInXml(this.curr__TagsValue);
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.curr__TagsValue = tags;
		this.SetTagsValue();
	}]
	,__TagsInXml: [decl_virtual, function(tags) {
		if (!tags) return;
		var llb = this.leftListBox;
		
		if (!tags || tags.length == 0) 
		{
			var scopeTags = this.GetScopeTags();
			for (var k = 0, kc = scopeTags.length; k < kc; ++k)
			{
				var item = this.rightListBoxes[scopeTags[k]];
				if (!item) continue;
				
				var rlb = item.ListBox;
				if (!rlb) continue;
				
				if (this.isStatic) 
				{
					if (this.leftListBox) 
						rlb.MoveAllRows(this.leftListBox);
					else
						rlb.Clear();
				}
				else
					rlb.Clear();
			}
			this.ClearSelector();
		} 
		else 
		{
			var values = []; 
			var dispval = [];
			var scopes = [];
			for (var i = 0, ic = tags.length; i < ic; ++i)
			{
				values[i] = tags[i].selectSingleNode(SRCH_TP_VALUE);
				dispval[i] = tags[i].selectSingleNode(SRCH_TP_DISPLAYVALUE);
				scopes[i] = tags[i].selectSingleNode(SRCH_TP_TAGSCOPE);
			}
			
			for (var i = 0, ic = values.length; i < ic; ++i)
			{
				var name = dispval[i].text;
				var val = values[i].text;
				var scope = uiasc_GetClientByServerScope(scopes[i].text);
				
				var item = this.rightListBoxes[scope];
				if (item)
				{
					var listBox = this.rightListBoxes[scope].ListBox;
					if (listBox)
					{
						listBox.AddValue(name, val, listBox.GetSortedIndex(name), true);
						if (llb)
							llb.DelByValue(val);
					}
				}
			}
						
			var scopeTags = this.GetScopeTags();
			for (var k = 0, kc = scopeTags.length; k < kc; ++k)
			{
				var item = this.rightListBoxes[scopeTags[k]];
				if (!item) continue;
				
				var rlb = item.ListBox;
				if (!rlb) continue;
				
				var items = rlb.GetItems();
				for (var i = 0, ic = items.length; i < ic; ++i)
				{
					var val = items[i].value;
					var flag = false;
					for (var j = 0, jc = values.length; j < jc; ++j)
					{
						if (values[j].text == val && 
							uiasc_GetClientByServerScope(scopes[j].text) == scopeTags[k])
						{
							flag = true;
							break;
						}
					}
					if (flag == false)
					{
						var name = items[i].text;
						rlb.DelByValue(val);
						if (llb && this.isStatic)
							llb.AddValue(name, val, llb.GetSortedIndex(name), true);
					}
				}
			}
		}
	}]
	,GetSelectedItems: function() {
		var selectedItems = null;
		var scopeTags = this.GetScopeTags();
		for (var k = 0, kc = scopeTags.length; k < kc; ++k)
		{
			var item = this.rightListBoxes[scopeTags[k]];
			if (!item) continue;
				
			var rlb = item.ListBox;
			if (!rlb) continue;
			
			if (selectedItems == null)
				selectedItems = rlb.GetItems();
			else
			{
				var items = rlb.GetItems();
				for (var i = 0, ic = items.length; i < ic; ++i)
					selectedItems.push(items[i]);
			}
		}
		return selectedItems;
	}
	,AddToLeftListBox: function(values, sorted) {
		if (this.leftListBox)
			this.leftListBox.AddValues(values, true, "name", sorted);
	}
	,AddToRightListBox: function(values) {
		if (!values) return;
		
		var res = [], rlb = this.rightListBox;
		for (var i = 0, j = 0, ic = values.length; i < ic; ++i)
		{
			var name = values[i].name, value = values[i].value;
			if (rlb.AddValue(name, value, rlb.GetSortedIndex(name), true))
				res[j++] = {"text":name,"value":value};
		}
		return res;
	}
	,ClearLeftListBox: function() {
		if (this.leftListBox)
			this.leftListBox.Clear();
	}
	
	,AddPredefinedValues: function() { }
});
//--------------------- SelectorWithDeleteFilter ----------------------------
DeclareClass("UI.AS.SelectorWithDeleteFilter", "UI.AS.Selector", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base(leftTitle, rightTitle, cache, isStatic);
		this.filter = null;
		this.imgFind = null;
	}
	,Dispose: [decl_virtual, function() {
		this.filter = null;
		this.imgFind = null;
		this.base.Dispose();
	}]
	,RenderActionRow: [decl_virtual, function(row) {
		var leftCell = row.insertCell();
		leftCell.className = "sa-sel-acl";
		
		this.imgFind = new UI.DOMControls.Image("search-adv-find.png", "sa-sel-afi");
	    this.imgFind.AttachEvent("click", this.CreateCallback(this.OnFilter));
	    
		this.filter = new UI.DOMControls.InputControl("");
		this.filter.SetCssClass("sa-sel-arclf");
		this.filter.AttachEvent("keydown", this.CreateCallback(this.OnKeyDown));
		
		var tdFilter = new UI.DOMControls.Td(this.filter);
		tdFilter.SetCssClass("sa-sel-arcl");
		var tdImage = new UI.DOMControls.Td(this.imgFind);
		tdImage.SetCssClass("sa-sel-tdi");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(tdFilter, tdImage));
		leftCell.appendChild(table.Obj());
		
		var middleCell = row.insertCell();
		middleCell.className = "sa-sel-cp";
		
		var rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		this.imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
	    this.imgDelete.AttachEvent("click", this.CreateCallback(this.OnRightDeleteSelected));
	    
		var td = new UI.DOMControls.Td();
		td.SetCssClass("sa-sel-arcl");
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		rightCell.appendChild(table.Obj());
	}]
	,OnFilter: function(sender) { this.FireEvent("onfilter", this.filter.GetValue()) }
	,OnKeyDown: function(sender) {
		if (event.keyCode == 13)
			this.FireEvent("onfilter", this.filter.GetValue());
		return true;
	}
	,ClearFilter: function() { this.filter.SetValue("") }
	,LoadingByResolving: function() {
		this.leftListBox.Clear();
		this.leftListBox.AddValue("Search...", "@search@", 0, true);
	}
});
//--------------------- MultiSelectorWithDeleteFilter ----------------------------
DeclareClass("UI.AS.MultiSelectorWithDeleteFilter", "UI.AS.MultiSelector", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base(leftTitle, rightTitle, cache, isStatic);
		this.filter = null;
		this.imgFind = null;
	}
	,Dispose: [decl_virtual, function() {
		this.filter = null;
		this.imgFind = null;
		this.base.Dispose();
	}]
	,RenderActionRow: [decl_virtual, function(row) {
		var leftCell = row.insertCell();
		leftCell.className = "sa-sel-acl";
		
		this.imgFind = new UI.DOMControls.Image("search-adv-find.png", "sa-sel-afi");
	    this.imgFind.AttachEvent("click", this.CreateCallback(this.OnFilter));
	    
		this.filter = new UI.DOMControls.InputControl("");
		this.filter.SetCssClass("sa-sel-arclf");
		this.filter.AttachEvent("keydown", this.CreateCallback(this.OnKeyDown));
		
		var tdFilter = new UI.DOMControls.Td(this.filter);
		tdFilter.SetCssClass("sa-sel-arcl");
		var tdImage = new UI.DOMControls.Td(this.imgFind);
		tdImage.SetCssClass("sa-sel-tdi");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(tdFilter, tdImage));
		leftCell.appendChild(table.Obj());
		
		var middleCell = row.insertCell();
		middleCell.className = "sa-sel-cp";
		
		var rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		var td = new UI.DOMControls.Td();
		var scopeTags = this.GetScopeTags();
		td.Obj().innerText = this.GetScopePrefixText(scopeTags[0]) + this.GetScopePostfixText();
		td.SetCssClass("sa-sel-arcl");
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		
		rightCell.appendChild(table.Obj());
	}]
	,OnFilter: function(sender) { this.FireEvent("onfilter", this.filter.GetValue()); }
	,OnKeyDown: function(sender) {
		if (event.keyCode == 13)
			this.FireEvent("onfilter", this.filter.GetValue());
		return true;
	}
	,ClearFilter: function() { this.filter.SetValue(""); }
	,LoadingByResolving: function() {
		this.leftListBox.Clear();
		this.leftListBox.AddValue("Search...", "@search@", 0, true);
	}
});
//--------------------- SelectorWithDeleteDropDown ----------------------------
DeclareClass("UI.AS.SelectorWithDeleteDropDown", "UI.AS.Selector", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base(leftTitle, rightTitle, cache, isStatic);
		this.dropDown = null;
	}
	,Dispose: [decl_virtual, function() {
		this.dropDown = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.dropDown = new UI.Controls.DropDown();
		this.dropDown.SetWidth("100%");
		this.AddControl(this.dropDown);
		this.base.Init();
	}]
	,RenderActionRow: [decl_virtual, function(row) {
		var leftCell = row.insertCell();
		leftCell.className = "sa-sel-acl";
		
		var td = new UI.DOMControls.Td(new UI.DOMControls.Text(this.GetText()));
		td.SetCssClass("sa-sel-arcr-ddl");
		
		this.tdDropDown = new UI.DOMControls.Td();
		this.tdDropDown.SetCssClass("sa-fill");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, this.tdDropDown));
		leftCell.appendChild(table.Obj());
		this.dropDown.RenderControl(this.tdDropDown.Obj());	
		
		var middleCell = row.insertCell();
		middleCell.className = "sa-sel-cp";
		
		var rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		this.imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
	    this.imgDelete.AttachEvent("click", this.CreateCallback(this.OnRightDeleteSelected));
	    
		var td = new UI.DOMControls.Td();
		td.SetCssClass("sa-sel-arcl");
		table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		rightCell.appendChild(table.Obj());
	}]
	,GetText: function() { return "" }
	,GetDropDown: function() { return this.dropDown }
});
//--------------------- SelectorWithDeleteFilterDropDown ----------------------------
DeclareClass("UI.AS.SelectorWithDeleteFilterDropDown", "UI.AS.SelectorWithDeleteFilter", {
	constructor: function(leftTitle, rightTitle, cache, isStatic) {
		this.base(leftTitle, rightTitle, cache, isStatic);
		this.dropDown = new UI.Controls.DropDown();
		this.dropDown.SetWidth("100%");
	}
	,Dispose: [decl_virtual, function() {
		this.dropDown = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.base.Init();
		this.AddControl(this.dropDown);
	}]
	,RenderActionRow: [decl_virtual, function(row) {
		var leftCell = row.insertCell();
		leftCell.className = "sa-sel-acl";
		
		this.imgFind = new UI.DOMControls.Image("search-adv-find.png", "sa-sel-afi");
	    this.imgFind.AttachEvent("click", this.CreateCallback(this.OnFilter));
	    
		this.filter = new UI.DOMControls.InputControl("");
		this.filter.SetCssClass("sa-sel-arclf");
		this.filter.AttachEvent("keydown", this.CreateCallback(this.OnKeyDown));
		
		var td = new UI.DOMControls.Td(this.filter);
		td.SetCssClass("sa-sel-arcl");
	    var tdFilter = new UI.DOMControls.Td(this.imgFind);
	    tdFilter.SetCssClass("sa-sel-tdi");
	    
	    this.tdDropDown = new UI.DOMControls.Td();
		
		var table = new UI.DOMControls.Table(
			new UI.DOMControls.Tr(new UI.DOMControls.Td(
				new UI.DOMControls.Table(new UI.DOMControls.Tr(td, tdFilter))
			)),
			new UI.DOMControls.Tr(this.tdDropDown)
		);
		
		leftCell.appendChild(table.Obj());
		this.dropDown.RenderControl(this.tdDropDown.Obj());	
		
		var middleCell = row.insertCell();
		middleCell.className = "sa-sel-cp";
		
		var rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		this.imgDelete = new UI.DOMControls.Image("search-adv-action-delete.gif", "sa-sel-adi");
	    this.imgDelete.AttachEvent("click", this.CreateCallback(this.OnRightDeleteSelected));
	    
		var td = new UI.DOMControls.Td();
		td.SetCssClass("sa-sel-arcl");
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(td, new UI.DOMControls.Td(this.imgDelete)));
		rightCell.appendChild(table.Obj());
	}]
	,OnFilter: function(sender) { this.FireEvent("onfilter", this.filter.GetValue()) }
	,OnKeyDown: function(sender) {
		if (event.keyCode == 13)
			this.FireEvent("onfilter", this.filter.GetValue());
		return true;
	}
	,ClearFilter: function() { this.filter.SetValue("") }
	,LoadingByResolving: [decl_virtual, function() {
		this.leftListBox.Clear();
		this.leftListBox.AddValue("Search...", "@search@", 0, true);
	}]
	,GetDropDown: function() { return this.dropDown }
});
//------------------ KeywordsTagsHandler ----------------------
DeclareClass("AS.KeywordsTagsHandler", "AS.HandlerForMultiTextBox", {
	constructor: function(moduleForm) { 
		this.base(moduleForm, SRCH_TN_KEYWORD, this.GetTagDisplayNameByTagName(SRCH_TN_KEYWORD), SRCH_TT_STD, SRCH_TS_ANY);
	}
});
//------------------ InTextHandler ----------------------
DeclareClass("AS.InTextHandler", "AS.HandlerForMultiTextBox", {
	constructor: function(moduleForm) { 
		this.base(moduleForm, SRCH_TN_TEXT, this.GetTagDisplayNameByTagName(SRCH_TN_TEXT), SRCH_TT_STD, SRCH_TS_ANY);
	}
	,OnTextBoxChange: [decl_virtual, function(value, scope, textBox) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		var scopes = this.scopes;
		var scopesLength = scopes.length;
		
		var needAdded = false;
		
		for (var k = 0; k < scopesLength; ++k) {
			var textBoxInfo = this.textBox[scopes[k]];
			if (textBoxInfo) {
				var textBox = textBoxInfo.TextBox;
				if (textBox)
				{
					var vals = textBox.GetValue();
					if (vals.length > 0)
					{
						needAdded = true;
						break;
					}
				}	
			}
		}
		
		if (needAdded == true) {
			this.DelAllTagsByNameFromXML(false, this.GetTagName());
			
			for (var k = 0; k < scopesLength; ++k) {
				var textBoxInfo = this.textBox[scopes[k]];
				if (textBoxInfo) {
					var textBox = textBoxInfo.TextBox;
					if (textBox) {
						var vals = textBox.GetValue();
												
						for (var i = 0, ic = vals.length; i < ic; ++i) 
							vals[i] = vals[i].trim();							
						var res = vals.join(',');
						
						this.AddTags([{"text":res, "value":res}], scopes[k]);
					}
				}
			}
		}
		else
			this.DelAllTagsByNameFromXML(true, this.GetTagName());
		
		if (aum) GlASM.AUM();
	}]
	,GetTagDisplayNameByTagName : [decl_virtual, function(tagName) 
	{
		if (IS_TMC_USER)
			return "Keywords"; 
		else
			return this.base.GetTagDisplayNameByTagName(tagName);
	}]
});
//------------------ IndustryHandler ----------------------
DeclareClass("AS.IndustryHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_INDUSTRY, this.GetTagDisplayNameByTagName(SRCH_TN_INDUSTRY), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ PeriodHandler ----------------------
DeclareClass("AS.PeriodHandler", "AS.HandlerForDropDown", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_PERIOD, this.GetTagDisplayNameByTagName(SRCH_TN_PERIOD), SRCH_TT_STD, SRCH_TS_ANY) }
	,IsCustomValue: function(value) { return (value == "custom") ? true : false }
	,GetOccurrence: function() { return 1 }
	,AddPeriodAttributes: function() {
		this.AddAttribute(SRCH_AN_PERIODDISPLAYSTARTDATE, this.moduleForm.GetDisplayStartDate());
		this.AddAttribute(SRCH_AN_PERIODSTARTDATE, this.moduleForm.GetStartDate());
		this.AddAttribute(SRCH_AN_PERIODDISPLAYENDDATE, this.moduleForm.GetDisplayEndDate());
		this.AddAttribute(SRCH_AN_PERIODENDDATE, this.moduleForm.GetEndDate());
	}
	,DelPeriodAttributes: function() {
		this.DelAttribute(SRCH_AN_PERIODDISPLAYSTARTDATE);
		this.DelAttribute(SRCH_AN_PERIODSTARTDATE);
		this.DelAttribute(SRCH_AN_PERIODDISPLAYENDDATE);
		this.DelAttribute(SRCH_AN_PERIODENDDATE);
	}
	,OnSelect: [decl_virtual, function(sender, selVal) {
		seldVal = selVal.trim();
		if (this.IsCustomValue(selVal)) {
			this.moduleForm.ShowCustomPeriod();
			this.AddPeriodAttributes();
		} else {
			this.moduleForm.HideCustomPeriod();
			this.DelPeriodAttributes();
		}
		this.base.OnSelect(sender, selVal);
	}]
	,OnChangePeriod: function(selectedValue) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		this.DelAllTagsByNameFromXML(true, this.GetTagName());
		selectedValue = selectedValue.trim();
		
		if (this.IsCustomValue(selectedValue)) 
			this.AddPeriodAttributes();
		else
			this.DelPeriodAttributes();
			
		if (this.IsSelected(selectedValue)) {
			var getv = this.dropDown.GetDisplayValue();
			this.AddTags([{"text":getv,"value":selectedValue}]);
		}
		if (aum) GlASM.AUM();
	}
});
//------------------ CategoriesHandler ----------------------
DeclareClass("AS.CategoriesHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_FEEDCATEGORY, this.GetTagDisplayNameByTagName(SRCH_TN_FEEDCATEGORY), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ ProvidersHandler ----------------------
DeclareClass("AS.ProvidersHandler", "AS.HandlerWithLooker", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_PROVIDER, this.GetTagDisplayNameByTagName(SRCH_TN_PROVIDER), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ FeedSourcesHandler ----------------------
DeclareClass("AS.FeedSourcesHandler", "AS.HandlerForDropDownLooker", {
	constructor: function(moduleForm) {
		this.base(moduleForm, this.GetTagName(), this.GetTagDisplayName(), SRCH_TT_STD, SRCH_TS_ANY);
		this.containerScope = null;
	}
	,Update: function() {
		this.tagDisplayName = this.GetTagDisplayName();
		this.AddAttribute(SRCH_TP_DISPLAYNAME, this.tagDisplayName);
		this.AddAttributes();
	}
	,GetTagDisplayName: function() { return UI.AS.FeedSourcesSelector.GetContainerDisplayName() }
	,GetTagNameContainer: function() {
		switch(GlASM.GetPID()) {
			case PID_FEEDS: return SRCH_TN_FEED;
			case PID_FOLDERS: return SRCH_TN_FOLDER;
			case PID_BLOGS: return SRCH_TN_BLOG;	
			case PID_CALENDARS: return SRCH_TN_CALENDAR;
		}
	}
	,GetTagName: function() { 
		if (this.selector) {
			if (this.selector.IsSelectScope())
				return SRCH_TN_CONTAINERSEARCHSCOPE;
		}
		return this.GetTagNameContainer();
	}
	,OnChangeSearchScope: [decl_virtual, function(tagScope, isInitializing) {
		if (tagScope == SRCH_TS_EXCLUDEANY)
		{
			this.moduleForm.UnlockRightDropDown();
			this.SetTagContainerScope(this.moduleForm.GetContainerScope());
		}
		else
		{ 
			this.DelTagContainerScope();
			this.moduleForm.LockRightDropDown();
		}
		this.base.OnChangeSearchScope(tagScope, isInitializing);
	}]
	,SetTagContainerScope: function(value) {
		this.containerScope = value;
		this.AddAttribute(SRCH_AN_CONTAINERSCOPE, this.containerScope);	
	}
	,DelTagContainerScope: function() { this.DelAttribute(SRCH_AN_CONTAINERSCOPE) }
	,GetResolutionParams: function() {
		var scope = this.selector.GetLeftDropDownValue();
		return [new Xml.Attribute(SRCH_AN_CONTAINERSCOPE, scope)];
	}
	,OnResolve: function() {
		if (!this.selector) 
			return;
			
		this.selector.ClearFilter();
		this.selector.ClearLeftListBox();
		
		var values = this.GetResolvedValues();
		if (values.length > 1) {
			this.selector.AddToLeftListBox(values, false);
		}
		else if (values.length == 1) {
			if (!this.selector.IsSelectScope()) {
				var addedItems = this.selector.AddToRightListBox(values);
				this.AddTags(addedItems);
			}
			else
				this.selector.AddToLeftListBox(values, false);
		} 
		else 
			this.OnMatchesNotFound();
			
		this.selector.AddPredefinedValues();
	}
});
//------------------ BlogCategoryHandler ----------------------
DeclareClass("AS.BlogCategoryHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_BLOGCATEGORY, this.GetTagDisplayNameByTagName(SRCH_TN_BLOGCATEGORY), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ CompaniesHandler ----------------------
DeclareClass("AS.CompaniesHandler", "AS.HandlerWithLookerMultiSelector", {
	constructor: function(moduleForm) {
		this.base(moduleForm, SRCH_TN_SYMBOL, this.GetTagDisplayNameByTagName(SRCH_TN_SYMBOL), SRCH_TT_STD, SRCH_TS_ANY);
		this.resolvarManager = new UI.Resolver.AdvancedSearchResolverManager(this.ClearFilter.bind(this));
	}
	,Dispose: [decl_virtual, function() {
		this.tagPrimaryOnly = null;
		this.base.Dispose();
	}]
	,GetNameNodeName: function() { return "Name"; }
	,AttachEventsToSelector: [decl_virtual, function(selector) {
		this.base.AttachEventsToSelector(selector);
		if (this.selector)
			this.Listeners.AddObjectListener(this.selector, "onprimarytikerchange", this.OnPrimaryTickerChange);
	}]
	,OnPrimaryTickerChange: function(value, isInit, scope, items) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		
		var tickerValue = value ? "-1" : "0";
		if (!isInit) {
			if (items && items.length > 0) {
				this.DelTagsFromXML(items);
				this.AddTags(items, scope, tickerValue);
			}
			values = null;
		}
		if (aum) GlASM.AUM();
	}
	,AddTags: function(values, scope, ticker) {
		var needToFireEvent = !(values && values.length > 0);
		this.DelAllTagsByNameFromXML(needToFireEvent, SRCH_TN_PORTFOLIO);
		
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		this.AddTagsToXML(values, scope, ticker);
		if (aum) GlASM.AUM();
	}	
	,OnFilter: function(value) {
		this.resolvarManager.Search("Symbol", value, [new Xml.Attribute('isName', "false")]);
	}
	,ClearFilter: function(){this.selector.ClearFilter();}
});
//------------------ PortfolioHandler ----------------------
DeclareClass("AS.PortfolioHandler", "AS.HandlerForDropDown", {
	constructor: function(moduleForm) {
		this.base(moduleForm, SRCH_TN_PORTFOLIO, this.GetTagDisplayNameByTagName(SRCH_TN_PORTFOLIO), SRCH_TT_STD, SRCH_TS_ANY);
		this.cbPrimaryOnly = null;
		this.tagPrimaryOnly = null;
	}
	,Dispose: [decl_virtual, function() {
		this.cbPrimaryOnly = null;
		this.base.Dispose();
	}]
	,SetPrimaryOnlyControl: function(control) {
		this.cbPrimaryOnly = control;
		this.Listeners.AddObjectListener(this.cbPrimaryOnly, "onclick", this.OnPrimaryOnlyChanged);
	}
	,SetPrimaryOnly: function(value) {
		if (this.tagPrimaryOnly != value) {
			this.tagPrimaryOnly = value;
			this.AddAttribute(SRCH_AN_SYMBOLPRIMARYONLY, this.tagPrimaryOnly);
		}
	}
	,OnPrimaryOnlyChanged: function(isChecked, value, isInit) {
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();

		this.SetPrimaryOnly(isChecked ? "-1" : "0");
		if (!isInit) {
			this.DelAllTagsByNameFromXML(true, this.GetTagName());
			var val = this.dropDown.SelectedValue;
			if (this.IsSelected(val)) {
				var dval = this.dropDown.GetDisplayValue();
				this.AddTags([{"text":dval,"value":val}]);
			}
		}
		if (aum) GlASM.AUM();
	}
	,GetOccurrence: function() { return 1 }
	,OnSelect: [decl_virtual, function(sender, value, oldValue) {
		value = value.trim();
		if (this.IsSelected(value))
		{
			var companyHandler = AS.Handler.GetHandlerByTagName(SRCH_TN_SYMBOL);
			var isAnyCompanyTags = false;
			if (companyHandler)
			{
				if (companyHandler)
				{
					var items = companyHandler.GetItemsNeededToAdd();
					if (items && items.length != 0)
						isAnyCompanyTags = true;
				}
			}
			var cancel = false;
			if (isAnyCompanyTags)
			{
				cancel = !confirm("Search can't be performed by portfolio and company criteria at once. Would you like to remove company search criterion from the search?")
			}
		
			if (cancel)
			{
				this.dropDown.SetSelectedValue(oldValue, false);
				return false;
			}
		}
		
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		if (this.IsSelected(value)) {
			this.DelAllTagsByNameFromXML(false, SRCH_TN_SYMBOL);
		}
		
		this.DelAllTagsByNameFromXML(true, this.GetTagName());
		
		if (this.IsSelected(value)) {
			// clear company tags
			var companyHandler = AS.Handler.GetHandlerByTagName(SRCH_TN_SYMBOL);
			if (companyHandler)
				companyHandler.ClearSelectedNoFireEvent(false);
			
			var getv = this.dropDown.GetDisplayValue();
			this.AddTags([{"text":getv,"value":value}]);
		}
		
		if (aum) GlASM.AUM();
	}]
	,IsSelectedAnyPortfolio: function() {
		if (this.dropDown)
			return this.IsSelected(this.dropDown.SelectedValue);
		else
			return false;
	}
	,DeleteSelected: function() { 
		if (this.dropDown)
			this.dropDown.SetSelectedValue("", false); 
	}
});
//------------------ FileTypeHandler ----------------------
DeclareClass("AS.FileTypeHandler", "AS.HandlerForDropDown", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_FILETYPE, "File Types", SRCH_TT_STD, SRCH_TS_ANY) }
	,GetOccurrence: function() { return 1 }
});
//------------------ TopicsHandler ----------------------
DeclareClass("AS.TopicsHandler", "AS.HandlerForMultiSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_TOPIC, this.GetTagDisplayNameByTagName(SRCH_TN_TOPIC), SRCH_TT_STD, SRCH_TS_ANY); }
});
//------------------ CustomTopicsHandler ----------------------
DeclareClass("AS.CustomTopicsHandler", "AS.HandlerForMultiSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_CUSTOMTOPIC, this.GetTagDisplayNameByTagName(SRCH_TN_CUSTOMTOPIC), SRCH_TT_STD, SRCH_TS_ANY); }
});
//------------------ BrokersHandler ----------------------
DeclareClass("AS.BrokersHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_BROKER, this.GetTagDisplayNameByTagName(SRCH_TN_BROKER), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ LanguageHandler ----------------------
DeclareClass("AS.LanguageHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_LANGUAGE, this.GetTagDisplayNameByTagName(SRCH_TN_LANGUAGE), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ CountryHandler -----------------------
DeclareClass("AS.CountryHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_COUNTRY, this.GetTagDisplayNameByTagName(SRCH_TN_COUNTRY), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ RegionHandler ------------------------
DeclareClass("AS.RegionHandler", "AS.HandlerForSearchScopeSelector", {
	constructor: function(moduleForm) { this.base(moduleForm, SRCH_TN_REGION, this.GetTagDisplayNameByTagName(SRCH_TN_REGION), SRCH_TT_STD, SRCH_TS_ANY) }
});
//------------------ CompaniesModuleForm -------------------------
DeclareClass("UI.AS.CompaniesModuleForm", "UI.AS.ModuleFormWithSelector", {
	constructor: function() {
		this.base();
		
		this.curr_TickerValueAny = false;
		this.curr_TickerValueAll = false;
		this.curr_TickerValueNoneOf = false;
	}
	,Init: [decl_virtual, function() {
		this.base.Init();
		this.SetTickerValue();
	}]
	,CreateHandler: function() { return new AS.CompaniesHandler(this); }
	,CreateSelectorControl: function() { return new UI.AS.CompaniesSelector(); }
	,GetScopePostfixText: function() { return " of the Companies"; }
	,SetTickerValue: function(scope) {
		if (this.selector != null) {
			switch(scope) {
				case UI.AS.Scope.Any:
					this.selector.SetPrimaryTicker(this.curr_TickerValueAny, false, UI.AS.Scope.Any);
					break;
				case UI.AS.Scope.All:
					this.selector.SetPrimaryTicker(this.curr_TickerValueAll, false, UI.AS.Scope.All);
					break;
				case UI.AS.Scope.ExcludeAny:
					this.selector.SetPrimaryTicker(this.curr_TickerValueNoneOf, false, UI.AS.Scope.ExcludeAny);
					break;
			}
		}
	}
	,SetCurrentTickerValue: function(value, scope) {
		switch(scope) {
			case UI.AS.Scope.Any:
				this.curr_TickerValueAny = value;
				break;
			case UI.AS.Scope.All:
				this.curr_TickerValueAll = value;
				break;
			case UI.AS.Scope.ExcludeAny:
				this.curr_TickerValueNoneOf = value;
				break;
		}
		this.SetTickerValue(scope);
	}
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.All, UI.AS.Scope.ExcludeAny]; }
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) {
			var tagScopes = this.GetScopeTags();
			for (var i = 0, ic = tagScopes.length; i < ic; ++i)
				this.SetCurrentTickerValue(IS_TMC_USER, tagScopes[i]);
		}
		else 
		{
			var currScope = null;
			for (var i = 0, ic = tags.length; i < ic; ++i) {
				var tag = tags[i];
				var po = tag.selectSingleNode(SRCH_AN_SYMBOLPRIMARYONLY);
				var scope = tag.selectSingleNode(SRCH_TP_TAGSCOPE);
				if (currScope != scope.text) {
					currScope = scope.text;
					if (po != null) 
						this.SetCurrentTickerValue(po.text == "-1" ? true : false, uiasc_GetClientByServerScope(scope.text));
				}
			}
		}
	}]
	,GetScopePrefixText: function(tag) { return uiasc_GetDisplayScopeByValue(uiasc_GetServerByClientScope(tag), SRCH_TN_SYMBOL); }
});
//------------------ PortfolioModuleForm ----------------------
DeclareClass("UI.AS.PortfolioModuleForm", "UI.AS.ModuleFormWithDropDown", {
	constructor: function() {
		this.base();
		this.cbPrimaryOnly = null;
		this.curr_PrimaryOnlyValue = false;
		this.KeywordsAttach(KEY_PORTFOLIO);
		this.fnRH = this.CreateCallback(this.RefreshCallback);
	}
	,Dispose: [decl_virtual, function() {
		this.cbPrimaryOnly = null;
		this.KeywordsDetach();
		this.fnRH = null;
		this.base.Dispose();
	}]
	,CreateHandler: function() { return new AS.PortfolioHandler(this) }
	,FillDropDown: [decl_virtual, function() {
		if (this.dropDown) 
			this.RefreshList();
	}]
	,RefreshList: function () {
		new httpcmd_GetDataSource("MyPortfolios", this.fnRH);
		if (this.dropDown) {
			this.dropDown.Clear();
			this.dropDown.AddItem("Loading...", "");
		}
	}
	,RefreshCallback: function(porfolio) {
		if (this.dropDown) {
			this.dropDown.Clear();
			this.dropDown.AddItem("Unfiltered","");
			if(porfolio) {
				for(var i = 0, ic = porfolio.GetCount(); i < ic; i++) {
					var xItem = porfolio.GetByIndex(i);
					this.dropDown.AddItem(xItem.GetNodeValue(FilterItem.PN_DISPLAY_VALUE), xItem.GetNodeValue(FilterItem.PN_VALUE));
				}
			}
			this.SetDropDownValue();
		}
	}
	,Init: [decl_virtual, function() {
		this.cbPrimaryOnly = new UI.Controls.CheckBox("Primary Ticker Only", null, false);
		this.handler.SetPrimaryOnlyControl(this.cbPrimaryOnly);
		this.base.Init();
	}]
	,AMLoad: [decl_virtual, function() { this.RefreshList() }]
	,InitFormControls: [decl_virtual, function() {
		this.base.InitFormControls();
		this.AddControl(this.cbPrimaryOnly);
	}]
	,Render: [decl_virtual, function(writer) {
		var td1 = new UI.DOMControls.Td();  td1.SetCssClass("sa-form-ddtdl");
		var td2 = new UI.DOMControls.Td(); td2.SetCssClass("sa-form-ddtdr");
		
		this.HostElement.appendChild(new UI.DOMControls.Table(new UI.DOMControls.Tr(td1, td2)).Obj()); 
		
		this.dropDown.RenderControl(td1.Obj());
		this.cbPrimaryOnly.RenderControl(td2.Obj());
	}]
	,SetPrimaryOnlyValue: function() {
		if (this.cbPrimaryOnly != null) {
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
			
			this.cbPrimaryOnly.SetChecked(this.curr_PrimaryOnlyValue);
			
			if (needLock) this.handler.LockXML(false);
		}
	}
	,SetCurrentPrimaryOnlyValue: function(value) {
		this.curr_PrimaryOnlyValue = value;
		this.SetPrimaryOnlyValue();
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) 
			this.SetCurrentPrimaryOnlyValue(false);
		else
		{
			var tag = tags[0].selectSingleNode(SRCH_AN_SYMBOLPRIMARYONLY);
			if (tag) {
				this.SetCurrentPrimaryOnlyValue(tag.text == "-1" ? true : false);
				tag = null;
			}
		}
	}]
});
//------------------ FileTypeModuleForm ----------------------
DeclareClass("UI.AS.FileTypeModuleForm", "UI.AS.ModuleFormWithDropDown", {
	CreateHandler: function() { return new AS.FileTypeHandler(this) }
	,GetCache: function() { return TPFileTypeFilterValues }
});
//------------------ TopicsModuleForm -------------------------
DeclareClass("UI.AS.TopicsModuleForm", "UI.AS.ModuleFormWithSelector", {
	CreateHandler: function() { return new AS.TopicsHandler(this); }
	,CreateSelectorControl: function() { return new UI.AS.TopicsSelector(); }
	,GetScopePostfixText: function() { return " of the Topics"; }
});
//------------------ CustomTopicsModuleForm -------------------------
DeclareClass("UI.AS.CustomTopicsModuleForm", "UI.AS.ModuleFormWithSelector", {
	CreateHandler: function() { return new AS.CustomTopicsHandler(this); }
	,CreateSelectorControl: function() { return new UI.AS.CustomTopicsSelector(); }
	,GetScopePostfixText: function() { return " of the Topics"; }
});
//------------------ BrokersModuleForm -------------------------
DeclareClass("UI.AS.BrokersModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	constructor: function() {
		this.base();
		this.KeywordsAttach(KEY_BROKER);
		this.fnRH = this.CreateCallback(this.RefreshCallback);
	}
	,Dispose: [decl_virtual, function() {
		this.KeywordsDetach();
		this.fnRH = null;
		this.base.Dispose();
	}]
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.RefreshList();
	}]
	,AMLoad: [decl_virtual, function() { this.RefreshList() }]
	,RefreshList: function () {
		new httpcmd_GetBrokerItems(this.fnRH);
		if (this.selector) {
			this.selector.ClearLeftListBox();
			this.selector.AddToLeftListBox([{"name":"Loading...","value":"@loading@"}], false);
		}
	}
	,LoadValues: function() {
		if (this.selector) {
			this.selector.ClearLeftListBox();
		
			var tmplDS = Data.Helper.CreateCollectionByInfo(BrokerItem, this.xmlDoc);
			if(tmplDS) {
				var values = [], NAME = BrokerItem.PN_NAME, CODE = BrokerItem.PN_CODE, selected = this.selector.GetSelectedItems(), selectedCnt = selected.length;
				for(var i = 0, ic = tmplDS.GetCount(); i < ic; ++i) {
					var xItem = tmplDS.GetByIndex(i), name = xItem.GetNodeValue(NAME), code = xItem.GetNodeValue(CODE), flag = true;
					for (var j = 0; j < selectedCnt; ++j)
						if (code == selected[j].value) {
							flag = false;
							break;
						}
					if (flag)
						values.push({"name":name,"value":code});
				}
				this.selector.AddToLeftListBox(values, true);
			}
		}
	}
	,RefreshCallback: function(xmlDoc) {
		this.xmlDoc = xmlDoc;
		window.setTimeout(this.CreateCallback(this.LoadValues) , 1000);
	}
	,CreateHandler: function() { return new AS.BrokersHandler(this) }
	,CreateSelectorControl: function() { return new UI.AS.BrokersSelector() }
	,GetScopePostfixText: function() { return " of the Brokers" }
});
//------------------ KeywordsTagsModuleForm -------------------------
DeclareClass("UI.AS.KeywordsTagsModuleForm", "UI.AS.ModuleFormWithMultiTextBox", {
	CreateHandler: function() { return new AS.KeywordsTagsHandler(this); }
	,GetScopePostfixText: function() { return " of the Tags"; }
	,GetSearchScopeControlWidth: function() { return "245px"; }
	,GetTextBoxTitle: function() { return "Tags:"; }
});
//------------------ InTextModuleForm -------------------------
DeclareClass("UI.AS.InTextModuleForm", "UI.AS.ModuleFormWithMultiTextBox", {
	CreateHandler: function() { return new AS.InTextHandler(this); }
	,GetScopePostfixText: function() { return !IS_TMC_USER ? " of the Words / Phrases" : " of the Keywords"; }
	,GetSearchScopeControlWidth: function() { return "245px"; }
	,GetTextBoxTitle: [decl_virtual, function() { return !IS_TMC_USER ? "In Text:" : "Keywords:"; }]
});
//------------------ PeriodModuleForm ----------------------
DeclareClass("UI.AS.PeriodModuleForm", "UI.AS.ModuleFormWithDropDown", {
	constructor: function() {
		this.base();
		this.periodRow = null;
		
		this.leftDateSelector = null;
		this.rightDateSelector = null;
		
		this.periodMan = new Utils.PeriodManager();
		this.isCustom = false;
	}
	,Dispose: [decl_virtual, function() {
		this.periodMan = null;
		this.periodRow = null;
		this.leftDateSelector = null;
		this.rightDateSelector = null;
		this.base.Dispose();
	}]
	,CreateHandler: function() { return new AS.PeriodHandler(this) }
	,Update: [decl_virtual, function() {
		this.SetCache(this.GetCache());
		return this.base.Update();			
	}]
	,GetCache: function() 
	{ 
		if (GlASM.GetPID()==PID_CALENDARS)
			return TPCalendarDateFilterValues;
			
		return typeof(TPTMCTempDateFilterValues) != "undefined" ? TPTMCTempDateFilterValues : TPDateFilterValues;
	}
	,FillDropDown: [decl_virtual, function() {
		this.base.FillDropDown();
		if (this.dropDown && (typeof(TPTMCTempDateFilterValues) == "undefined" || TPTMCTempDateFilterValues == TPDateFilterValues))
			this.dropDown.AddItem("Custom date range", "custom");
	}]
	,GetSelectedValue: function() { return srch_getDefaultPeriodValue() }
	,InitFormControls: [decl_virtual, function() {
		this.base.InitFormControls();
		
		this.leftDateSelector = new UI.Controls.TPDateSelector("160px");
		this.Listeners.AddObjectListener(this.leftDateSelector, "onchangedate", this.OnStartDateChange);
		this.rightDateSelector = new UI.Controls.TPDateSelector("160px");
		this.Listeners.AddObjectListener(this.rightDateSelector, "onchangedate", this.OnEndDateChange);
		
		this.AddControl(this.leftDateSelector);
		this.AddControl(this.rightDateSelector);
		
		this.ShowPeriod();
	}]
	,Render: [decl_virtual, function(writer) {
		var td1 = new UI.DOMControls.Td(); td1.SetCssClass("sa-form-ddtdl"); td1.SetColSpan("2");
		var td2 = new UI.DOMControls.Td(); td2.SetCssClass("sa-form-ddtdr"); td2.SetColSpan("2");
		
		var tdFrom = new UI.DOMControls.Td(new UI.DOMControls.Text("From:")); tdFrom.SetCssClass("sa-form-pfrom");
		var tdStartDate = new UI.DOMControls.Td(); tdStartDate.SetCssClass("sa-form-psd");
		var tdTo = new UI.DOMControls.Td(new UI.DOMControls.Text("To:")); tdTo.SetCssClass("sa-form-pto");
		var tdEndDate = new UI.DOMControls.Td(); tdEndDate.SetCssClass("sa-form-ped");
		
		this.periodRow = new UI.DOMControls.Tr(tdFrom, tdStartDate, tdTo, tdEndDate);
		this.periodRow.SetVisibleState(false);
		
		this.HostElement.appendChild(new UI.DOMControls.Table(new UI.DOMControls.Tr(td1, td2), this.periodRow).Obj()); 
		
		this.dropDown.RenderControl(td1.Obj());
		this.leftDateSelector.RenderControl(tdStartDate.Obj());
		this.rightDateSelector.RenderControl(tdEndDate.Obj());
		
		this.SetCustomState();
	}]
	,SetCustomState: function() {
		if (this.periodRow) 
			this.periodRow.SetVisibleState(this.isCustom);
	}
	,ShowCustomPeriod: function() {
		this.isCustom = true;
		this.SetCustomState();	
	}
	,ResetPeriod: function() {
		var dtToday = new Date();
		this.SetCurrentStartDate(dtToday);
		this.SetCurrentEndDate(dtToday);
	}
	,HideCustomPeriod: function() {
		this.isCustom = false;
		this.SetCustomState();
		this.ResetPeriod();
	}
	,__FormatDateToXml: function(date) {
		var res = [], 
			year = date.getFullYear(), 
			month = date.getMonth() + 1, 
			dt = date.getDate();
			
		res[0] = year;
		res[1] = month < 10 ? "0" + month : month;
		res[2] = dt < 10 ? "0" + dt : dt;
		
		return res.join('-');		
	}
	,GetDisplayStartDate: function() { return this.leftDateSelector.GetValue() }
	,GetStartDate: function() { return this.__FormatDateToXml(this.leftDateSelector.GetDate()) }
	,GetDisplayEndDate: function() { return this.rightDateSelector.GetValue() }
	,GetEndDate: function() { return this.__FormatDateToXml(this.rightDateSelector.GetDate()) }
	,SetEndDate: function(date) { this.periodMan.SetEndDate(date) }
	,ShowPeriod: function() {
		if (this.leftDateSelector) this.leftDateSelector.SetDate(this.periodMan.StartDate, false);
		if (this.rightDateSelector) this.rightDateSelector.SetDate(this.periodMan.EndDate, false);
	}
	,OnStartDateChange: function(sender, date) {
		this.periodMan.SetStartDate(date);
		this.ShowPeriod();
		this.handler.OnChangePeriod(this.dropDown.SelectedValue);
	}
	,OnEndDateChange: function(sender, date) {
		this.periodMan.EndDateChange(date);
		this.ShowPeriod();
		this.handler.OnChangePeriod(this.dropDown.SelectedValue);
	}
	,SetCurrentStartDate: function(date) {
		this.periodMan.StartDate = date;
		this.ShowPeriod();
	}
	,SetCurrentEndDate: function(date) {
		this.periodMan.EndDate = date;
		this.ShowPeriod();
	}
	,CheckPeriodValueOnTmcPages: function(tags)
	{
		if (typeof(TPTMCTempDateFilterValues) != "undefined" && tags && tags.length > 0) 
		{
			var tagValue = tags[0].selectSingleNode(SRCH_TP_VALUE);
			if (tagValue && tagValue.text)
			{
				for (var i = 0, ic = TPDateFilterValues.length; i < ic; i++)
				{
					var item = TPDateFilterValues[i];
					var isCustom = this.handler.IsCustomValue(tagValue.text);
					if (item.value.toLowerCase() == tagValue.text.toLowerCase() || isCustom)
					{
						var source = null;
						if (isCustom || i > TPTMCDateFilterValueIndex)
						{
							if (TPTMCTempDateFilterValues != TPDateFilterValues)
								source = TPDateFilterValues;
						}
						else
							if (i <= TPTMCDateFilterValueIndex && TPTMCTempDateFilterValues != TPTMCDateFilterValues)
								source = TPTMCDateFilterValues;
						if (source && TPTMCTempDateFilterValues != source)
						{
							TPTMCTempDateFilterValues = source;
							this.FillDropDown();
						}
						break;
					}
				}
			}
		}
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.CheckPeriodValueOnTmcPages(tags);
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) {
			var today = new Date();
			this.HideCustomPeriod();
			this.SetCurrentStartDate(today);
			this.SetCurrentEndDate(today);
		}
		else 
		{
			var tagValue = tags[0].selectSingleNode(SRCH_TP_VALUE);
			if (this.handler.IsCustomValue(tagValue.text)) {
				var tagStartDate = tags[0].selectSingleNode(SRCH_AN_PERIODSTARTDATE);
				if (tagStartDate) {
					this.SetCurrentStartDate(srch_convertdatetime(tagStartDate.text));
					tagStartDate = null;	
				}
				var tagEndDate = tags[0].selectSingleNode(SRCH_AN_PERIODENDDATE);
				if (tagEndDate) {
					this.SetCurrentEndDate(srch_convertdatetime(tagEndDate.text));
					tagEndDate = null;
				}
				this.ShowCustomPeriod();
			}
		}
	}]
});
//------------------ CategoriesModuleForm -------------------------
DeclareClass("UI.AS.CategoriesModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	constructor: function() {
		this.base();
		this.KeywordsAttach(KEY_FEEDCATEGORY);
		this.fnRH = this.CreateCallback(this.RefreshCallback);
	}
	,Dispose: [decl_virtual, function() {
		this.KeywordsDetach();
		this.fnRH = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		this.base.Init();
		this.RefreshList();
	}]
	,AMLoad: [decl_virtual, function() { this.RefreshList() }]
	,RefreshList: function () {
		new httpcmd_GetFeedCategoriesItems(this.fnRH);
		if (this.selector) {
			this.selector.ClearLeftListBox();
			this.selector.AddToLeftListBox([{"name":"Loading...","value":"@loading@"}], false);
		}
	}
	,RefreshCallback: function(xmlDoc) {
		if (this.selector) {
			this.selector.ClearLeftListBox();
		
			var tmplDS = Data.Helper.CreateCollectionByInfo(FeedCategoryItem, xmlDoc);
			if(tmplDS) {
				var values = [], NAME = FeedCategoryItem.PN_DISPLAYVALUE, CODE = FeedCategoryItem.PN_ID, selected = this.selector.GetSelectedItems(), selectedCnt = selected.length;
				for(var i = 0, k = 0, ic = tmplDS.GetCount(); i < ic; ++i) {
					var xItem = tmplDS.GetByIndex(i), name = xItem.GetNodeValue(NAME), code = xItem.GetNodeValue(CODE), flag = true;
					for (var j = 0; j < selectedCnt; ++j)
						if (code == selected[j].value) {
							flag = false;
							break;
						}
					if (flag)
						values[k++] = {"name":name,"value":code};
				}
				this.selector.AddToLeftListBox(values, true);
			}
		}
	}
	,GetScopeTags: function() { return [UI.AS.Scope.Any] }
	,CreateHandler: function() { return new AS.CategoriesHandler(this) }
	,CreateSelectorControl: function() { return new UI.AS.CategoriesSelector() }
	,GetScopePostfixText: function() { return " of the Categories" }
});
//------------------ ProvidersModuleForm -------------------------
DeclareClass("UI.AS.ProvidersModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateHandler: function() { return new AS.ProvidersHandler(this) }
	,CreateSelectorControl: function() { return new UI.AS.ProvidersSelector() }
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.ExcludeAny] }
	,GetScopePostfixText: function() { return " of the Providers" }
});
//------------------ FeedSourcesModuleForm -------------------------
DeclareClass("UI.AS.FeedSourcesModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	constructor: function() {
		this.base();
		this.ddRight = null;
		this.pid = null;
		this.curr_ddRightValue = null;
		this.curr_tagsScope = null;
		this.curr_predefinedSelected = false;
		this.curr_rightlock = true;
	}
	,Dispose: [decl_virtual, function() {
		this.ddRight = null;
		this.curr_tagsScope = null;
		this.base.Dispose();
	}]
	,CreateSelectorControl: [decl_virtual, function() { return new UI.AS.FeedSourcesSelector() }]
	,GetScopePostfixText: function() { return " of the the Feeds" }
	,CreateHandler: function() { return new AS.FeedSourcesHandler(this) }
	,GetRadioButtonsTitles: function(tagScope) {
		var page = UI.AS.FeedSourcesSelector.GetSelectorTitles();
		page += "s";
		switch(tagScope) {
			case SRCH_TS_EXCLUDEANY: return "None of the " + page + " from";
			default: return "Any of the " + page;						
		}
	}
	,CreateSearchScopeControl: [decl_virtual, function() {
		return new UI.Controls.GroupBox(this.GetGroupBoxId(), "Search type:", "195px", "100%", 
						[{'control': new UI.Controls.RadioButton(this.GetRadioButtonsTitles(SRCH_TS_ANY), SRCH_TS_ANY, true), 'css': null},
						 {'control': new UI.Controls.RadioButton(this.GetRadioButtonsTitles(SRCH_TS_EXCLUDEANY), SRCH_TS_EXCLUDEANY), 'css': null},
						 {'control': this.ddRight, 'css': "sa-form-ddr"}]);
	}]
	,SetPID: function(pid) {
		this.pid = pid;
		var dv = UI.AS.FeedSourcesSelector.GetDisplayContainerScope(this.pid);
		if (dv) 
			for(var i=0, ic = dv.length; i < ic; ++i) 
				this.ddRight.AddItem(dv[i].name, dv[i].value);
	}
	,Update: [decl_virtual, function() {
		if (this.selector && this.selector.IsSelectScope())
			this.gbSearchScope.Lock();
		else
			this.gbSearchScope.Unlock();
			
		var pid = GlASM.GetPID();
		if (this.pid != pid) 
		{
			this.pid = pid;
			this.ddRight.Clear();
			this.SetPID(pid);
			
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
				
			this.ddRight.Select(0);
			
			if (needLock) this.handler.LockXML(false);
		}
		
		this.gbSearchScope.SetRadioButtonTitles([this.GetRadioButtonsTitles(SRCH_TS_ANY), 
			this.GetRadioButtonsTitles(SRCH_TS_EXCLUDEANY)]);
			
		if (this.handler)
			this.handler.Update();
			
		switch(pid) {
			case PID_BLOGS: tagName = SRCH_TN_BLOG; break;	
			case PID_CALENDARS: tagName = SRCH_TN_CALENDAR; break;
			case PID_FOLDERS: tagName = SRCH_TN_FOLDER; break;
			default: tagName = SRCH_TN_FEED;
		}
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
			
		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_NAME, tagName)]);
		if (!tags || tags.length == 0) 
			this.SetCurrentDDRightValue(null);
		else 
		{
			var ts = tags[0].selectSingleNode(SRCH_TP_TAGSCOPE);
			if (ts) {
				this.SetCurrentSearchScope(ts.text);
				if (ts.text == SRCH_TS_EXCLUDEANY) {
					var cs = tags[0].selectSingleNode(SRCH_AN_CONTAINERSCOPE);
					if (cs) this.SetCurrentDDRightValue(cs.text);
					this.curr_rightlock = false;
					this.ddRight.Unlock();
				}
				else
				{
					this.curr_rightlock = true;
					this.ddRight.Lock();
				}
			}
		}
			
		if (aum) GlASM.AUM();
				
		return this.base.Update();
	}]
	,Init: [decl_virtual, function() {
		this.ddRight = new UI.Controls.DropDown();
		this.Listeners.AddObjectListener(this.ddRight, "onselected", this.OnSelectedRight);
			
		this.base.Init();
		
		this.Listeners.AddObjectListener(this.selector, "onpredefinedselected", this.OnPredefinedSelected);
		this.Listeners.AddObjectListener(this.selector, "oncontainerselected", this.OnContainerSelected);
		
		this.SetPID(GlASM.GetPID());
		
		this.SetDDRightValue();
		if (!this.isSetSelectorValue)
			this.SetTagsScopeValue();
	}]
	,GetContainerScope: function() { return this.ddRight.SelectedValue }
	,OnSelectedRight: function() {
		if (this.gbSearchScope.GetRadioButtonValue() == SRCH_TS_EXCLUDEANY)
			this.handler.SetTagContainerScope(this.ddRight.SelectedValue);
		this.gbSearchScope.fireEvent(false);
	}
	,OnPredefinedSelected: function() {
		this.curr_predefinedSelected = true;
		if (this.gbSearchScope) 
			this.gbSearchScope.Lock();
	}
	,OnContainerSelected: function() {
		this.curr_predefinedSelected = false;
		if (this.gbSearchScope) 
			this.gbSearchScope.Unlock();
	}
	,LockRightDropDown: function() {
		this.curr_rightlock = true;
		this.ddRight.Lock();
	}
	,UnlockRightDropDown: function() {
		this.curr_rightlock = false;
		this.ddRight.Unlock();
	}
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		if (this.curr_rightlock)
			this.ddRight.Lock();
		else
			this.ddRight.Unlock();
		this.gbSearchScope.SetLock(this.curr_predefinedSelected);
	}]
	,OnXmlChange: [decl_virtual, function() {
		switch(GlASM.GetPID()) {
			case PID_BLOGS: tagName = SRCH_TN_BLOG; break;	
			case PID_CALENDARS: tagName = SRCH_TN_CALENDAR; break;
			case PID_FOLDERS: tagName = SRCH_TN_FOLDER; break;
			default: tagName = SRCH_TN_FEED;
		}
		var aum = GlASM.GetAUM();
		if (aum) GlASM.DUM();
		
		var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_NAME, tagName)]);
		if (!this.TagsInXml(this.GetTagsWithNoInvalid(tags)))
			this.TagsInXmlContainerScope(srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_NAME, SRCH_TN_CONTAINERSEARCHSCOPE)]));
			
		if (aum) GlASM.AUM();
	}]
	,SetTagsScopeValue: function() {
		if (this.selector)  
			this.selector.TagsInXmlContainerScope(this.curr_tagsScope);
	}
	,TagsInXmlContainerScope: function(tags) {
		this.curr_tagsScope = tags;
		this.SetTagsScopeValue();
		if (tags && tags.length != 0)
			this.OnPredefinedSelected();
	}
	,SetDDRightValue: function() {
		if (this.ddRight != null) {
			var needLock = !this.handler.IsLocked();
			if (needLock) this.handler.LockXML(true);
			
			if (this.curr_ddRightValue == null)
				this.ddRight.Select(0);
			else
			{
				this.ddRight.SetSelectedValue(this.curr_ddRightValue);
				this.OnContainerSelected();
			}
			if (needLock) this.handler.LockXML(false);
		}
	}
	,SetCurrentDDRightValue: function(value) {
		this.curr_ddRightValue = value;
		this.SetDDRightValue();
	}
	,TagsInXml: [decl_virtual, function(tags) {
		this.base.TagsInXml(tags);
		if (!tags || tags.length == 0) {
			this.SetCurrentDDRightValue(null);
			return false;
		}
		else 
		{
			var ts = tags[0].selectSingleNode(SRCH_TP_TAGSCOPE);
			if (ts) {
				this.SetCurrentSearchScope(ts.text);
				if (ts.text == SRCH_TS_EXCLUDEANY) {
					var cs = tags[0].selectSingleNode(SRCH_AN_CONTAINERSCOPE);
					if (cs) this.SetCurrentDDRightValue(cs.text);
				}
			}
			return true;
		}
	}]
});
//------------------ BlogCategoryModuleForm ----------------------
DeclareClass("UI.AS.BlogCategoryModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateSelectorControl: function() { return new UI.AS.BlogCategorySelector() }
	,CreateHandler: function() { return new AS.BlogCategoryHandler(this) }
	,GetScopeTags: function() { return [UI.AS.Scope.Any, UI.AS.Scope.ExcludeAny] }
	,GetScopePostfixText: function() { return " of the Categories" }
});
//------------------ IndustryModuleForm -------------------------
DeclareClass("UI.AS.IndustryModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateSelectorControl: function() { return new UI.AS.IndustrySelector() }
	,CreateHandler: function() { return new AS.IndustryHandler(this) }
	,GetScopePostfixText: function() { return " of the Industries" }
});
//------------------ RegionModuleForm -------------------------
DeclareClass("UI.AS.RegionModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateSelectorControl: function() { return new UI.AS.RegionSelector() }
	,CreateHandler: function() { return new AS.RegionHandler(this) }
	,GetScopePostfixText: function() { return " of the Regions" }
});
//------------------ CountryModuleForm -------------------------
DeclareClass("UI.AS.CountryModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateSelectorControl: function() { return new UI.AS.CountrySelector() }
	,CreateHandler: function() { return new AS.CountryHandler(this) }
	,GetScopePostfixText: function() { return " of the Countries" }
});
//------------------ LanguageModuleForm -------------------------
DeclareClass("UI.AS.LanguageModuleForm", "UI.AS.ModuleFormWithSearchScopeSelector", {
	CreateSelectorControl: function() { return new UI.AS.LanguageSelector() }
	,CreateHandler: function() { return new AS.LanguageHandler(this) }
	,GetScopeTags: function() { return [UI.AS.Scope.Any] }
	,GetScopePostfixText: function() { return " of the Languages" }
});
//--------------------- CompaniesModule ---------------------------
DeclareClass("UI.AS.CompaniesModule", "UI.AS.Module", {
	constructor: function() { this.base("Companies") }
	,GetSearchTags: function() { return [SRCH_TN_SYMBOL] }
	,GetModule: function() { return new UI.AS.CompaniesModuleForm(); }
	,CreateHeader: [decl_virtual, function() {
		var header = this.base.CreateHeader();
		header.SetStyleAttribute("position", "relative");
		header.AddControl(new UI.Controls.ScriptLink("company lookup tool", this.CallLookupTool.bind(this), true, null, "sa-companies-lookup-link"));
		return header;
	}]
	,CallLookupTool: function(){
		this.Expand();
		UI.AS.CompaniesModule.Instanse = this;
		UI.AS.CompaniesModule.LookupXml = [];
		do_showCompanyLookup('UI.AS.CompaniesModule.OnLookupAddItem', UI.AS.CompaniesModule.OnLookupComplete);
		return false;
	}
	,OnLookupAddItem: [decl_static, function(item) {
		item.MarkSelected(false);
		item.SetNodeValue("TEMPID", item.GetNodeValue("ID"));
		UI.AS.CompaniesModule.LookupXml.push(item.GetXml());
	}]
	,OnLookupComplete: [decl_static, function(item) {
		if(UI.AS.CompaniesModule.LookupXml!=null && UI.AS.CompaniesModule.LookupXml.length>0)
			UI.AS.CompaniesModule.Instanse.form.selector.leftListBox.SetXML("<Symbol>~0</Symbol>".format(UI.AS.CompaniesModule.LookupXml.join("")));
	}]
});
//--------------------- PortfolioModule ----------------------------
DeclareClass("UI.AS.PortfolioModule", "UI.AS.Module", {
	constructor: function() { this.base("Portfolio") }
	,GetSearchTags: function() { return [SRCH_TN_PORTFOLIO] }
	,GetModule: function() { return new UI.AS.PortfolioModuleForm() }
});
//--------------------- FileTypeModule ----------------------------
DeclareClass("UI.AS.FileTypeModule", "UI.AS.Module", {
	constructor: function() { this.base("File type") }
	,GetSearchTags: function() { return [SRCH_TN_FILETYPE] }
	,GetModule: function() { return new UI.AS.FileTypeModuleForm() }
});
//--------------------- TopicsModule ----------------------------
DeclareClass("UI.AS.TopicsModule", "UI.AS.Module", {
	constructor: function() { this.base("Topics"); }
	,GetSearchTags: function() { return [SRCH_TN_TOPIC]; }
	,GetModule: function() { return new UI.AS.TopicsModuleForm(); }
});
//--------------------- CustomTopicsModule ----------------------------
DeclareClass("UI.AS.CustomTopicsModule", "UI.AS.Module", {
	constructor: function() { this.base("Custom Topics"); }
	,GetSearchTags: function() { return [SRCH_TN_CUSTOMTOPIC]; }
	,GetModule: function() { return new UI.AS.CustomTopicsModuleForm(); }
});
//--------------------- BrokersModule ----------------------------
DeclareClass("UI.AS.BrokersModule", "UI.AS.Module", {
	constructor: function() { this.base("Brokers") }
	,GetSearchTags: function() { return [SRCH_TN_BROKER] }
	,GetModule: function() { return new UI.AS.BrokersModuleForm() }
});
//--------------------- KeywordTagsModule ----------------------------
DeclareClass("UI.AS.KeywordTagsModule", "UI.AS.Module", {
	constructor: function() { this.base("Tags"); }
	,GetSearchTags: function() { return [SRCH_TN_KEYWORD]; }
	,GetModule: function() { return new UI.AS.KeywordsTagsModuleForm(); }
});
//--------------------- InTextModule ----------------------------
DeclareClass("UI.AS.InTextModule", "UI.AS.Module", {
	constructor: function() { this.base(this.GetHeaderText()); }
	,GetHeaderText: [decl_virtual, function() { return !IS_TMC_USER ? "In text" : "Keywords"; }]
	,GetSearchTags: function() { return [SRCH_TN_TEXT]; }
	,GetModule: [decl_virtual, function() { return new UI.AS.InTextModuleForm(); }]
});
//--------------------- PeriodModule ----------------------------
DeclareClass("UI.AS.PeriodModule", "UI.AS.Module", {
	constructor: function() 
	{ 
		this.base("Period");
		//this.SetVisibleState((typeof(TMC_PAGES) != "undefined" && TMC_PAGES == true) ? false : true);
	}
	,RegisterModule : [decl_virtual, function() {}]
	,GetSearchTags: function() { return [SRCH_TN_PERIOD] }
	,GetModule: function() { return new UI.AS.PeriodModuleForm() }
});
//--------------------- CategoriesModule ----------------------------
DeclareClass("UI.AS.CategoriesModule", "UI.AS.Module", {
	constructor: function() { this.base("Feed Categories") }
	,GetSearchTags: function() { return [SRCH_TN_FEEDCATEGORY] }
	,GetModule: function() { return new UI.AS.CategoriesModuleForm() }
});
//--------------------- ProvidersModule ----------------------------
DeclareClass("UI.AS.ProvidersModule", "UI.AS.Module", {
	constructor: function() { this.base("Feed Providers") }
	,GetSearchTags: function() { return [SRCH_TN_PROVIDER] }
	,GetModule: function() { return new UI.AS.ProvidersModuleForm() }
});
//--------------------- FeedSourcesModule ----------------------------
DeclareClass("UI.AS.FeedSourcesModule", "UI.AS.Module", {
	constructor: function() {
		this.base(this.GetModuleTitle());
		this.InitData();
	}
	,GetSearchTags: function() { return [SRCH_TN_FEED, SRCH_TN_CALENDAR, SRCH_TN_FOLDER, SRCH_TN_BLOG, SRCH_TN_CONTAINERSEARCHSCOPE] }
	,GetModule: [decl_virtual, function() { return new UI.AS.FeedSourcesModuleForm() }]
	,GetModuleTitle: [decl_virtual, function() {
		switch(GlASM.GetPID()) {
			case PID_FEEDS: return "Feed Names";
			case PID_CALENDARS: return "Calendar Names";
			case PID_FOLDERS: return "Folder Names";
			case PID_BLOGS: return "Blog Names";
		}
	}]
	,InitData: [decl_virtual, function() { this.SetHeaderText(this.GetModuleTitle()) }]
	,Update: [decl_virtual, function() {
		this.InitData();
		return this.base.Update();
	}]
});
//--------------------- BlogCategoryModule ----------------------------
DeclareClass("UI.AS.BlogCategoryModule", "UI.AS.Module", {
	constructor: function() { this.base("Blog category") }
	,GetSearchTags: function() { return [SRCH_TN_BLOGCATEGORY] }
	,GetModule: function() { return new UI.AS.BlogCategoryModuleForm() }
});
//--------------------- IndustryModule ----------------------------
DeclareClass("UI.AS.IndustryModule", "UI.AS.Module", {
	constructor: function() { this.base("Industry Groups/Industry") }
	,GetSearchTags: function() { return [SRCH_TN_INDUSTRY] }
	,GetModule: function() { return new UI.AS.IndustryModuleForm() }
});
//--------------------- RegionModule ----------------------------
DeclareClass("UI.AS.RegionModule", "UI.AS.Module", {
	constructor: function() { this.base("Region") }
	,GetSearchTags: function() { return [SRCH_TN_REGION] }
	,GetModule: function() { return new UI.AS.RegionModuleForm() }
});
//--------------------- CountryModule ----------------------------
DeclareClass("UI.AS.CountryModule", "UI.AS.Module", {
	constructor: function() { this.base("Country") }
	,GetSearchTags: function() { return [SRCH_TN_COUNTRY] }
	,GetModule: function() { return new UI.AS.CountryModuleForm() }
});
//--------------------- LanguageModule ----------------------------
DeclareClass("UI.AS.LanguageModule", "UI.AS.Module", {
	constructor: function() { this.base("Language") }
	,GetSearchTags: function() { return [SRCH_TN_LANGUAGE] }
	,GetModule: function() { return new UI.AS.LanguageModuleForm() }
});
//--------------------- CompaniesSelector ----------------------------
DeclareClass("UI.AS.CompaniesSelector", "UI.AS.MultiSelectorWithDeleteFilter", {
	constructor: function() {
		this.base("Filter Companies By:", "Selected Companies:", null, false);
		
		this.primaryOnlyAny = false;
		this.primaryOnlyAll = false;
		this.primaryOnlyNoneOf = false;
		
		this.primaryTicker = null;
	}
	,Dispose: [decl_virtual, function() {
		this.primaryTicker = null;
		this.base.Dispose();
	}]
		
	,Init: [decl_virtual, function() {
		this.primaryTicker = new UI.Controls.CheckBox("Primary Ticker)", null, false);
		this.primaryTicker.SetStyleAttribute("display", "inline");
		this.AddControl(this.primaryTicker);
		
		this.base.Init();
		
		var tagScopes = this.GetScopeTags();
		this.rightListBoxes[tagScopes[0]].SetPrimaryTicker(this.primaryTicker, this.CreateCallback(this.PrimaryTickerChanged));
		
		for (var i = 1, ic = tagScopes.length; i < ic; ++i)
		{
			var pt = new UI.Controls.CheckBox("Primary Ticker)", null, false);
			pt.SetStyleAttribute("display", "inline");
			this.rightListBoxes[tagScopes[i]].SetPrimaryTicker(pt, this.CreateCallback(this.PrimaryTickerChanged));
			this.AddControl(pt);
		} 
	}]
	,CreateLeftListBox: function() {
		var ctrl = new UI.AS.GridSelector("InfoNgen.TouchPoint.Modules.Common.Search.AdvanscedSearchSymbolDataGrid", ResolverSymbolItem.PN_NAME, "TEMPID");
		ctrl.SetCssClass("sa-resolver-grid");
		return ctrl;
	}
	,GetScopePostfixText: function() { return " of the Companies ("; }
	,GetScopePrefixText: function(tag) { return uiasc_GetDisplayScopeByValue(uiasc_GetServerByClientScope(tag), SRCH_TN_SYMBOL); }
	,PrimaryTickerChanged: function(checked, value, isInit, scope, listBox) {this.OnPrimaryTickerChange(checked, value, isInit, scope, listBox); }
	,GetTicker: [decl_virtual, function(scope) {
		var item = this.rightListBoxes[scope];
		if (item) {
			var primaryTicker = item.PrimaryTicker;
			if (primaryTicker) {
				var checked = primaryTicker.IsChecked();
				return (checked == true) ? "-1" : "0";
			}
		}
		return null;
	}]
	,GetScopeTextClass: function() { return "sa-scope-text"; }
	,RenderActionRow: [decl_virtual, function(row) {
		var leftCell = row.insertCell();
		leftCell.className = "sa-sel-acl";
		
		this.imgFind = new UI.DOMControls.Image("search-adv-find.png", "sa-sel-afi");
	    this.imgFind.AttachEvent("click", this.CreateCallback(this.OnFilter));
	    
		this.filter = new UI.DOMControls.TextArea("", "1");
		this.filter.SetAttribute("wrap", "off");
		this.filter.SetAttribute("spellcheck", "false");
		this.filter.AttachEvent("keydown", this.CreateCallback(this.OnKeyDown));
		this.filter.AttachEvent("propertychange", this.CreateCallback(this.OnPaste));
		this.filter.AttachEvent("input", this.CreateCallback(this.OnPaste));
		var textDiv = new UI.DOMControls.Div(this.filter)
		textDiv.SetCssClass("text-box");
		var tdFilter = new UI.DOMControls.Td(textDiv);
		tdFilter.SetCssClass("sa-sel-arcl");
		var tdImage = new UI.DOMControls.Td(this.imgFind);
		tdImage.SetCssClass("sa-sel-tdi");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(tdFilter, tdImage));
		leftCell.appendChild(table.Obj());
		
		row.insertCell().className = "sa-sel-cp";
		
		var rightCell = row.insertCell();
		rightCell.className = "sa-sel-acr"; 
		
		var scopeTags = this.GetScopeTags();
		var text = new UI.DOMControls.Text(this.GetScopePrefixText(scopeTags[0]) + this.GetScopePostfixText());
		text.SetCssClass(this.GetScopeTextClass());
		this.tdPrimaryTicker = new UI.DOMControls.Td(text);
		this.tdPrimaryTicker.SetCssClass("sa-sel-arcl");
		
		var table = new UI.DOMControls.Table(new UI.DOMControls.Tr(this.tdPrimaryTicker, new UI.DOMControls.Td(this.imgDelete)));
		
		rightCell.appendChild(table.Obj());
		this.primaryTicker.RenderControl(this.tdPrimaryTicker.Obj());
	}]
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		
		var scopeTags = this.GetScopeTags();
		for (var i = 1, ic = scopeTags.length; i < ic; ++i) {
			var primaryTicker = this.rightListBoxes[scopeTags[i]].PrimaryTicker;
			this.rightListBoxes[scopeTags[i]].LeftCell.SetCssClass("sa-sel-arcl");
			primaryTicker.RenderControl(this.rightListBoxes[scopeTags[i]].LeftCell.Obj());
		}
		
		for (var i = 0, ic = scopeTags.length; i < ic; ++i) {
			var v = false;
			switch(scopeTags[i]) {
				case UI.AS.Scope.Any:
					v = this.primaryOnlyAny;
					break;
				case UI.AS.Scope.All:
					v = this.primaryOnlyAll;
					break;
				case UI.AS.Scope.ExcludeAny:
					v = this.primaryOnlyNoneOf;
					break;
			}
			this.SetPrimaryTicker(v, false, scopeTags[i]);
		}
		this.Listeners.AddDOMListener(this.leftListBox.ParentElement,"dblclick",this.OnGridDblClick);
	}]
	,OnPrimaryTickerChange: function(checked, value, isInit, scope, listBox) { 
		var items = listBox.GetItems();
		this.FireEvent("onprimarytikerchange", checked, isInit, scope, items);
	}
	,SetPrimaryTicker: function(bValue, v, scope) {
		switch(scope)
		{
			case UI.AS.Scope.Any:
				this.primaryOnlyAny = bValue;
				break;
			case UI.AS.Scope.All:
				this.primaryOnlyAll = bValue;
				break;
			case UI.AS.Scope.ExcludeAny:
				this.primaryOnlyNoneOf = bValue;
				break;
		}
		if (this.rightListBoxes[scope] && this.rightListBoxes[scope].PrimaryTicker)
			this.rightListBoxes[scope].PrimaryTicker.SetChecked(bValue);
	}
	,AllowAddition: [decl_virtual, function(items) {
		var portfolioHandler = AS.Handler.GetHandlerByTagName(SRCH_TN_PORTFOLIO);
		var res = true, isSelectedAnyPortfolio = false;
		if (portfolioHandler) {
			isSelectedAnyPortfolio = portfolioHandler.IsSelectedAnyPortfolio();
			if (isSelectedAnyPortfolio)
				res = confirm("Search can't be performed by portfolio and company criteria at once. Would you like to remove portfolio search criterion from the search?");				
		}
		
		if (res && isSelectedAnyPortfolio) {
			portfolioHandler.DeleteSelected();			
		}
		
		return res;
	}]
	,OnPaste: function(){
		var data = this.filter.GetValue();
		if(data && /\t|\n/.test(data)){
			data = data.replace(/^\s+|\s+$/g, "").replace(/\s*(\t|\n)+/g, ", ").replace(/\s+/g, " ");
			this.filter.SetValue(data);
			//event.returnValue = false;
		}
	}
	,OnGridDblClick: function(){
		this.OnClick(UI.AS.Scope.Any, this.rightListBoxes[UI.AS.Scope.Any].ListBox);
	}
});
//--------------------- TopicsSelector ----------------------------
DeclareClass("UI.AS.TopicsSelector", "UI.AS.MultiSelector", {
	constructor: function() { this.base("Select Topics:", "Selected Topics:", null, true); }
	,LoadFromCache: function() { }
	,GetScopePostfixText: function() { return " of the Topics"; }
	,CreateLeftListBox: function() {		
		var ctrl = new UI.AS.GridSelector("InfoNgen.TouchPoint.Modules.Common.Search.AdvancedSearchTopicsDataGrid", TopicItem.PN_NAME, TopicItem.PN_CODE);
		ctrl.KeywordsAttach(KEY_TOPIC);
		this.Listeners.AddObjectListener(ctrl, "ondataloaded", this.OnDataLoaded);
		this.Listeners.AddObjectListener(ctrl, "onafteritemdelete", this.OnItemDelete);
		ctrl.SetCssClass("sa-resolver-grid");
		return ctrl;
	}
	,OnDataLoaded: function(){
		var selected = this.GetSelectedItems();
		for(var i=0, imax=selected.length; i<imax; i++)
			this.leftListBox.DelByValue(selected[i].value);	
	}
	,OnItemDelete: function(value, wasDeleted){
		if(!wasDeleted)
			this.ReplaceGroup(value);
	}
	,ReplaceGroup: function(groupCode){
		var dataset = this.leftListBox.DataSetHelper.__dataset;
		if(dataset){
			var scope = UI.AS.Scope.Any;
			var topics = [];
			for(var i=0, item; item = dataset.GetByIndex(i); i++)
				if(item.GetNodeValue(TopicItem.PN_GROUP_CODE) == groupCode)
					topics.push({text:item.GetNodeValue(TopicItem.PN_NAME), value:item.GetNodeValue(TopicItem.PN_CODE)});
			if(topics.length>0){
					var nl = this.handler.IsLocked();
					this.handler.LockXML(false);
					srch_advDeleteTag(this.handler.GetTagName(), groupCode, false);
					this.handler.AddTagsToXML(topics, scope);
					this.handler.LockXML(nl);
			}
		}
	}
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.Listeners.AddDOMListener(this.leftListBox.ParentElement,"dblclick",this.OnGridDblClick);
	}]
	,OnGridDblClick: function(){
		this.OnClick(UI.AS.Scope.Any, this.rightListBoxes[UI.AS.Scope.Any].ListBox);
	}
});

//--------------------- CustomTopicsSelector ----------------------------
DeclareClass("UI.AS.CustomTopicsSelector", "UI.AS.MultiSelector", {
	constructor: function() { this.base("Select Custom Topics:", "Selected Custom Topics:", null, true); }
	,LoadFromCache: function() { }
	,GetScopePostfixText: function() { return " of the Topics"; }
	,CreateLeftListBox: function() {
		var ctrl = new UI.AS.GridSelector("InfoNgen.TouchPoint.Modules.Common.Search.AdvancedSearchCustomTopicsDataGrid", TopicItem.PN_NAME, TopicItem.PN_CODE);
		ctrl.KeywordsAttach(KEY_CUSTOMTOPIC);
		this.Listeners.AddObjectListener(ctrl, "ondataloaded", this.OnDataLoaded);
		this.Listeners.AddObjectListener(ctrl, "onafteritemdelete", this.OnItemDelete);
		ctrl.SetCssClass("sa-resolver-grid");
		return ctrl;
	}
	,OnDataLoaded: function(){
		var selected = this.GetSelectedItems();
		for(var i=0, imax=selected.length; i<imax; i++)
			this.leftListBox.DelByValue(selected[i].value);	
	}
	,OnItemDelete: function(value, wasDeleted){
		if(!wasDeleted)
			this.ReplaceGroup(value);
	}
	,ReplaceGroup: function(groupCode){
		var dataset = this.leftListBox.DataSetHelper.__dataset;
		if(dataset){
			var scope = UI.AS.Scope.Any;
			var topics = [];
			for(var i=0, item; item = dataset.GetByIndex(i); i++)
				if(item.GetNodeValue(TopicItem.PN_GROUP_CODE) == groupCode)
					topics.push({text:item.GetNodeValue(TopicItem.PN_NAME), value:item.GetNodeValue(TopicItem.PN_CODE)});
			if(topics.length>0){
					var nl = this.handler.IsLocked();
					this.handler.LockXML(false);
					srch_advDeleteTag(this.handler.GetTagName(), groupCode, false);
					this.handler.AddTagsToXML(topics, scope);
					this.handler.LockXML(nl);
			}
		}
	}
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.Listeners.AddDOMListener(this.leftListBox.ParentElement,"dblclick",this.OnGridDblClick);
	}]
	,OnGridDblClick: function(){
		this.OnClick(UI.AS.Scope.Any, this.rightListBoxes[UI.AS.Scope.Any].ListBox);
	}
});
//--------------------- BrokersSelector ----------------------------
DeclareClass("UI.AS.BrokersSelector", "UI.AS.Selector", {
	constructor: function() { this.base("Filter Brokers By:","Selected Brokers:", null, true) }
	,LoadFromCache: function() { }
});
//--------------------- CategoriesSelector ----------------------------
DeclareClass("UI.AS.CategoriesSelector", "UI.AS.Selector", {
	constructor: function() { this.base("Select Feed Categories:","Selected Feed Categories:", null, true) }
	,LoadFromCache: function() { }
});
//--------------------- ProvidersSelector ----------------------------
DeclareClass("UI.AS.ProvidersSelector", "UI.AS.SelectorWithDeleteFilter", {
	constructor: function() { this.base("Filter Providers By:","Selected Providers:", null, false) }
});
//--------------------- FeedSourcesSelector ----------------------------
DeclareClass("UI.AS.FeedSourcesSelector", "UI.AS.SelectorWithDeleteFilterDropDown", {
	constructor: function() {
		this.base(this.GetLeftTitle(), this.GetRightTitle(), null, false);
		this.pid = null;
		this.messages = ["List of containers and scope can't be specified simultaneously.",
			"You can't choose more than one container scope."]; 
	}
	,GetLeftTitle: [decl_virtual, function() { return "Filter " + UI.AS.FeedSourcesSelector.GetSelectorTitles() + " Names:" }]
	,GetRightTitle: [decl_virtual, function() { return "Selected " + UI.AS.FeedSourcesSelector.GetSelectorTitles() + " Names:" }]
	,LoadFromCache: function() { }
	,GetSelectorTitles: [decl_static, function () {
		switch (GlASM.GetPID()) {
			case PID_FEEDS: return "Feed";
			case PID_BLOGS: return "Blog";
			case PID_CALENDARS: return "Calendar";
			case PID_FOLDERS: return "Folder";
		}		
	}]
	,GetDisplayContainerRule: [decl_static, function(location) {
		switch(location)
		{
			case PSL_AVAILABLEFEEDS:	  return "None of the feeds from available";
			case PSL_AVAILABLECALENDARS:  return "None of the calendars from available";
			case PSL_AVAILABLEUSERBLOGS:  return "None of the blogs from available";
			case PSL_AVAILABLEFOLDERS:    return "None of the folders from available";
				
			case PSL_SUBSCRIBEDFEEDS:     return "None of the feeds from subscribed";
			case PSL_SUBSCRIBEDCALENDARS: return "None of the calendars from subscribed";
			case PSL_SUBSCRIBEDUSERBLOGS: return "None of the blogs from subscribed";
			case PSL_SUBSCRIBEDFOLDERS:   return "None of the folders from subscribed";
				
			case PSL_FAVORITEFEEDS:		  return "None of the feeds from favorite";
			case PSL_FAVORITECALENDARS:   return "None of the calendars from favorite";
			case PSL_FAVORITEUSERBLOGS:   return "None of the blogs from favorite";
				
		}
		return null;
	}]
	,GetScopeDisplayValue: [decl_static, function(sloc) {
		switch(sloc)
		{
			case PSL_AVAILABLEFEEDS: return "All Feeds";
			case PSL_FAVORITEFEEDS: return "All Favorite Feeds";
			case PSL_SUBSCRIBEDFEEDS: return "All Subscribed Feeds";
			case PSL_AVAILABLEUSERBLOGS: return "All Blogs";
			case PSL_FAVORITEUSERBLOGS: return "All Favorite Blogs";
			case PSL_SUBSCRIBEDUSERBLOGS: return "All Subscribed Blogs";
			case PSL_AVAILABLECALENDARS: return "All Calendars";
			case PSL_FAVORITECALENDARS: return "All Favorite Calendars";
			case PSL_SUBSCRIBEDCALENDARS: return "All Subscribed Calendars";
			case PSL_AVAILABLEFOLDERS: return "All Folders";
			case PSL_SUBSCRIBEDFOLDERS: return "All Subscribed Folders";
		}
		return null;
	}]	
	,GetContainerDisplayName: [decl_static, function(location) {
		switch(GlASM.GetPID()) {
			case PID_FOLDERS: return "In Folders";
			case PID_BLOGS: return "In Blogs";	
			case PID_CALENDARS: return "Calendars";
			default: return "In Feeds";
		}
	}]
	,__CreateAttrInfo: [decl_static, function(value) {
		return {"name":UI.AS.FeedSourcesSelector.GetScopeDisplayValue(value),"value":value}
	}]
	,GetDisplayContainerScope: [decl_static, function(pid) {
		var AttrInfo = UI.AS.FeedSourcesSelector.__CreateAttrInfo;
		switch(pid)
		{
			case PID_FEEDS:
				var array = null;
				if (IS_TMC_USER)
					array = [AttrInfo(PSL_AVAILABLEFEEDS), AttrInfo(PSL_SUBSCRIBEDFEEDS)];
				else
					array = [AttrInfo(PSL_AVAILABLEFEEDS), AttrInfo(PSL_FAVORITEFEEDS), AttrInfo(PSL_SUBSCRIBEDFEEDS)];
				return array;
			case PID_BLOGS:
				return [AttrInfo(PSL_AVAILABLEUSERBLOGS), 
						AttrInfo(PSL_FAVORITEUSERBLOGS), 
						AttrInfo(PSL_SUBSCRIBEDUSERBLOGS)];
			case PID_CALENDARS:
				return [AttrInfo(PSL_AVAILABLECALENDARS), 
						AttrInfo(PSL_FAVORITECALENDARS), 
						AttrInfo(PSL_SUBSCRIBEDCALENDARS)];
			case PID_FOLDERS:
				return [AttrInfo(PSL_AVAILABLEFOLDERS), 
						AttrInfo(PSL_SUBSCRIBEDFOLDERS)];
			default:
				return null;
		}
	}]
	,AddItemsFromXML: function() {
		var dv = UI.AS.FeedSourcesSelector.GetDisplayContainerScope(this.pid);
		if (!dv) return;
		var idx = 0;
		for(var i=0; i < dv.length; ++i)
		{
			var name = dv[i].name, value = dv[i].value;
			if (this.rightListBox.GetValueByName(name) == null)
			{
				if (this.leftListBox.GetValueByName(name) == null)
					this.leftListBox.AddValue(name, value, idx++);
				else
					idx++;
			}
		}		
	}
	,SetPID: function(pid) {
		if (this.pid == pid)
			return;
		
		this.pid = pid;
		
		var dd = this.GetDropDown();
		this.leftListBox.Clear();
		dd.Clear();
		
		this.AddItemsFromXML();
		
		var dv = UI.AS.FeedSourcesSelector.GetDisplayContainerScope(this.pid);
		if (dv != null) {
			for(var i=0; i < dv.length; ++i)
			{
				var name = dv[i].name, value = dv[i].value;
				dd.AddItem(name, value);
			}		
		}
		dd.Select(0);
	}
	,Update: [decl_virtual, function() {
		this.SetPID(GlASM.GetPID());
		
		var leftTitle = this.GetLeftTitle();
		var rightTitle = this.GetRightTitle();
		
		if (this.leftCell && leftTitle)
			this.leftCell.innerText = leftTitle;
		if (this.rightCell && rightTitle)
			this.rightCell.innerText = rightTitle;
		
		return this.base.Update();
	}]
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		this.SetPID(GlASM.GetPID());
	}]
	,__IsContainerItem: function(item) { return vld_IsGuidValid(item.value, "N") ? true : false }
	,__IsContainerScopeItem: function(item) { return !this.__IsContainerItem(item) }
	,__GetContainerScopeItems: function(items) {
		var res = [];
		for (var i = 0, j = 0, ic = items.length; i < ic; ++i)
			if (this.__IsContainerScopeItem(items[i]))
				res[j++] = items[i];
		return res;
	}
	,__ValidateItems: function(items) {
		var errCode = 0;
		var arScopes = this.__GetContainerScopeItems(items);
		if (arScopes.length != 0) 
		{
			if (arScopes.length != items.length) 
				errCode = 1;
			else if (arScopes.length > 1) 
				errCode = 2;
		}
		return errCode;		
	}
	,__ShowErrorMessage: function(errCode) { alert(this.messages[errCode-1]) }
	,__MergeItems: function(items1, items2) {
		var merged = [];
		for (var i = 0, ic = items1.length; i < ic; ++i)
			merged[i] = items1[i];
		for (var i = 0, idx = merged.length, ic = items2.length; i < ic; ++i)
			merged[idx++] = items2[i];
		return merged;
	}
	,__IsValidItems: function(items) {
		var errCode = this.__ValidateItems(items);
		if (errCode != 0) 
		{
			this.__ShowErrorMessage(errCode);
			return false;			
		}
		return true;
	}
	,OnClick: [decl_virtual, function() {
		var items = this.leftListBox.GetSelectedItems();
		if (items.length == 0) 
			return;
			
		if (!this.__IsValidItems(items))
			return;
		
		var ritems = this.rightListBox.GetItems();
		var all_items = this.__MergeItems(items, ritems);
		
		if (!this.__IsValidItems(all_items))
			return;
		
		var isContainerScope = this.__GetContainerScopeItems(items).length != 0;
		if (isContainerScope)
		{
			var tag = this.handler.GetTagName();
			this.rightListBox.Clear();
			this.AddItemsFromXML();
			this.FireEvent("onmoveallitemstoleft", tag);
			
			this.FireEvent("onpredefinedselected");			
		}
		else
		{
			if (ritems.length == 1)
			{
				// define is there custom structures or not
				var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_TAGTYPE, SRCH_TT_CUSTOM)]);
				if (tags.length != 0)
				{
					if (confirm("All custom structures will be deleted. Do you really want to add container?")) {
						for (var i = 0, ic = tags.length; i < ic; ++i) {
							var name = tags[i].selectSingleNode(SRCH_TP_NAME);
							if (name) 
								srch_advDeleteTags(name.text,null,false);
						}
					}
					else
						return;
				}		
			}
			this.FireEvent("oncontainerselected");
		}
		
		this.base.OnClick();
		
		if (this.rightListBox.GetItems().length == 0)
			this.FireEvent("oncontainerselected");
	}]
	,AddPredefinedValues: function() {
		this.pid = GlASM.GetPID(); 
		this.AddItemsFromXML();
	}
	,OnRightDeleteSelected: [decl_virtual, function() {
		var ritems = this.rightListBox.GetSelectedItems();
		if (ritems.length == 1 && this.__IsContainerItem(ritems[0])) {
			var tags = srch_advGetTags([new srch_XmlSearchExParam(SRCH_TP_TAGTYPE, SRCH_TT_CUSTOM)]);
			if (tags.length != 0) {
				if (confirm("All custom structures will be deleted. Do you really want to delete the container?")) {
					for (var i = 0, ic = tags.length; i < ic; ++i) {
						var name = tags[i].selectSingleNode(SRCH_TP_NAME);
						if (name) 
							srch_advDeleteTags(name.text,null, i == ic-1);
					}
				}
				else
					return;
			}					
		}
		if (ritems.length > 0 && this.__IsContainerScopeItem(ritems[0])) {
			var tag = this.handler.GetTagName();
			this.rightListBox.Clear();
			this.AddItemsFromXML();
			
			this.FireEvent("onmoveallitemstoleft", tag);
		}
		else
			this.base.OnRightDeleteSelected();
			
		if (this.rightListBox.GetItems().length == 0)
			this.FireEvent("oncontainerselected");
	}]
	,TagsInXmlContainerScope: function(tags) {
		if (!tags) return;
		this.TagsInXml(tags);
		if (this.rightListBox) {
			if (this.rightListBox.GetItems().length == 0)
				this.FireEvent("oncontainerselected");
			else
				this.FireEvent("onpredefinedselected");
		}
	}
	,__TagsInXml: [decl_virtual, function(tags) {
		var rlb = this.rightListBox,
			llb = this.leftListBox;
			
		if (!tags || tags.length == 0) 
		{
			if (this.isStatic)
				rlb.MoveAllRows(this.leftListBox);
			else
			{
				var ritems = this.rightListBox.GetItems();
				if (ritems.length > 0 && this.__IsContainerScopeItem(ritems[0]))
				{
					this.rightListBox.Clear();
					if (this.rightListBox.GetItems().length == 0)
						this.FireEvent("oncontainerselected");
				}
				else
					rlb.Clear();
			}
			this.ClearSelector();
		} 
		else 
		{
			var values = [], dispval = [];
			var handler = UI.AS.FeedSourcesSelector.GetScopeDisplayValue;
			for (var i = 0, ic = tags.length; i < ic; ++i)
			{
				var tagName = tags[i].selectSingleNode(SRCH_TP_NAME);
				if (tagName) {
					values[i] = tags[i].selectSingleNode(SRCH_TP_VALUE);
					dispval[i] = tags[i].selectSingleNode(SRCH_TP_DISPLAYVALUE);
					if (tagName.text == SRCH_TN_CONTAINERSEARCHSCOPE)
					{
						dispval[i] = new Object();
						dispval[i].text = handler(values[i].text);
					}
				}				
			}
			
			for (var i = 0, ic = values.length; i < ic; ++i)
			{
				var name = dispval[i].text, val = values[i].text;
				rlb.AddValue(name, val, rlb.GetSortedIndex(name), true);
				if (llb)
					llb.DelByValue(val);
			}			
				
			var items = rlb.GetItems();
			for (var i = 0, ic = items.length; i < ic; ++i)
			{
				var val = items[i].value;
				var flag = false;
				for (var j = 0, jc = values.length; j < jc; ++j)
					if (values[j].text == val)
					{
						flag = true;
						break;
					}
				if (flag == false)
				{
					var name = items[i].text;
					rlb.DelByValue(val);
					if (llb && this.isStatic)
						llb.AddValue(name, val, llb.GetSortedIndex(name), true);
				}
			}
		}
		this.AddItemsFromXML();
	}]
	,GetLeftDropDownValue: function() { return this.GetDropDown().SelectedValue }
	,IsSelectScope: function() {
		if (!this.rightListBox) return false;
		var ritems = this.rightListBox.GetItems();
		return (ritems.length > 0 && this.__IsContainerScopeItem(ritems[0])) ? true : false;
	}
	,LoadingByResolving: [decl_virtual, function() {
		this.base.LoadingByResolving();
		this.AddItemsFromXML();
	}]
});
//--------------------- BlogCategorySelector ----------------------------
DeclareClass("UI.AS.BlogCategorySelector", "UI.AS.Selector", {
	constructor: function() { this.base("Select Categories:", "Selected Categories:", TPBlogPostCategoryCache, true) }
});
//--------------------- IndustrySelector ----------------------------
DeclareClass("UI.AS.IndustrySelector", "UI.AS.SelectorWithDeleteDropDown", {
	constructor: function() {
		this.base("Select Industries:", "Selected Industries:", null, true);
		
		this.leftTopListBox = null;
		this.leftBottomListBox = null;
		
		this.useGICSIndustries = CREData.BrandsFilter().UseGICSIndustries == "true";
	}
	,Dispose: [decl_virtual, function() {
		this.leftTopListBox = null;
		this.leftBottomListBox = null;
		this.base.Dispose();
	}]
	,Init: [decl_virtual, function() {
		if(this.useGICSIndustries)
		{
			this.leftTopListBox = new UI.Controls.TPListBox("100%", "125px");
			this.AddControl(this.leftTopListBox);
			this.leftBottomListBox = new UI.Controls.TPListBox("100%", "125px");
			this.AddControl(this.leftBottomListBox);
		}
		else
		{
			this.leftTopListBox = new UI.Controls.TPListBox("100%", "250px");
			this.AddControl(this.leftTopListBox);			
		}		
		this.base.Init();
	}]
	,ClearSelector: [decl_virtual, function() {
		this.base.ClearSelector();
		if (this.leftTopListBox) this.leftTopListBox.Clear();
		if (this.leftBottomListBox) this.leftBottomListBox.Clear();
		var dd = this.GetDropDown();
		if (dd) dd.__Select(0, false);
		if(!this.useGICSIndustries)
			FillMTMC(this.GetClientID(), 0, false, "TKBN");
	}]
	,GetText: function() { return "In Industry  " }
	,CreateLeftListBox: function() { return null }
	,CreateRightListBox: function() { return new UI.Controls.TPListBox("100%", "255px") }
	,RenderInputRow : [decl_virtual, function(row) {
		var table = DOMObjectFactory.CreateElement(UI.HtmlTag.Table);
		table.border = table.cellPadding = table.cellSpacing = 0;
		table.style.width = "100%";
		
		var cellTop = table.insertRow().insertCell();
		this.leftTopListBox.RenderControl(cellTop);
		
		var cellBottom = table.insertRow().insertCell();
		cellBottom.className = "sa-sel-ind";
		if (this.leftBottomListBox) this.leftBottomListBox.RenderControl(cellBottom);
		
		var tdLeft = row.insertCell();
		tdLeft.className = "sa-sel-td";
		tdLeft.appendChild(table);
		
		var img = new UI.DOMControls.Image("search-adv-right-arrow.gif", "sa-sel-ari");
		img.AttachEvent("click", this.CreateCallback(this.OnClick));
	    
	    var tdMiddle = row.insertCell();
		tdMiddle.className = "sa-sel-cp";
		tdMiddle.appendChild(img.Obj());
		
		var tdRight = row.insertCell();
		tdRight.className = "sa-sel-td";
		this.rightListBox.RenderControl(tdRight);
	}]
	,Render: [decl_virtual, function(writer) {
		this.base.Render(writer);
		
		var id = this.GetClientID();
		var taxonomyName = this.useGICSIndustries ? "GICS" : "TKBN";
		
		this.leftTopListBox.SetSelectedScript("mtmc_OnSelected('" +id+ "', 1)");
		if (this.leftBottomListBox) this.leftBottomListBox.SetSelectedScript("mtmc_OnSelected('" +id+ "', 2)");
		
		var dd = this.GetDropDown();
		
		this.Listeners.AddObjectListener(dd, "onselected", new Function ("mtmc_OnSelected('" + id + "', 0, false, '" + taxonomyName + "');"));
				
		var mtmc = CreateMTMC(id, TPIndustryCache, "name", "code", true);
		mtmc.SubControlsAdd(this.GetDropDown().GetClientID(), "dd", null, this.GetDropDown());
		mtmc.SubControlsAdd(this.leftTopListBox.GetClientID(), "lb", null, this.leftTopListBox);
		if (this.leftBottomListBox) mtmc.SubControlsAdd(this.leftBottomListBox.GetClientID(), "lb", null, this.leftBottomListBox);
		
		// [AL] we should display either GICS or TKBN industry depending on brand		
		FillMTMC(id, -1, this.useGICSIndustries, taxonomyName);
		if(!this.useGICSIndustries)
		{
			var dd = this.GetDropDown();
			if (dd) dd.__Select(0, false);
			
			FillMTMC(id, 0, false, taxonomyName);
		}
	}]
	,OnClick: [decl_virtual, function() {
		// [AL] we have to delete GICS industries if remapping takes place
		if(!this.useGICSIndustries)
		{	
			var listOfTKBNCodes = ",";
			var subitems = TPIndustryCache["TKBN"][0].subitems;
			for(var c1 = 0; c1<subitems.length; c1++)
				listOfTKBNCodes+=subitems[c1].code+",";
			
			var rightItems = this.rightListBox.GetItems();
			var doClearItems = false;
			for(c1 = this.rightListBox.GetItemCount()-1; c1>=0; c1--)
			{
				var rightItem = rightItems[c1];
				if(listOfTKBNCodes.indexOf(","+rightItem.value+",")<0)
				{
					this.rightListBox.SelectItemByIndex(c1);
					doClearItems = true;
				}
			}
			if(doClearItems)
			{
				this.OnRightDeleteSelected();
				this.rightListBox.Clear();
			}
		}		
		
		var movedItems = metaTMCValue(this.GetClientID());
		var isAdded = false;
		for (var i = 0, ic = movedItems.length; i < ic; ++i) {
			if (this.rightListBox.AddValue(movedItems[i].text, movedItems[i].value, this.rightListBox.GetSortedIndex(movedItems[i].text), true))
			 isAdded = true;
		}
		if (isAdded)
			this.FireEvent("onclick", movedItems);			
	}]
});
//--------------------- RegionSelector ----------------------------
DeclareClass("UI.AS.RegionSelector", "UI.AS.Selector", {
	constructor: function() { this.base("Select Regions:","Selected Regions:", TPRegionCache, true) }
});
//--------------------- CountrySelector ----------------------------
DeclareClass("UI.AS.CountrySelector", "UI.AS.Selector", {
	constructor: function() { this.base("Select Countries:","Selected Countries:", TPCountryCache, true) }
});
//--------------------- LanguageSelector ----------------------------
DeclareClass("UI.AS.LanguageSelector", "UI.AS.Selector", {
	constructor: function() { this.base("Select Languages:","Selected Languages:", TPLanguageCache, true) }
});
//--------------------- UI.AS.CustomControlsSection ---------------------------
DeclareClass("UI.AS.CustomControlsSection", "UI.Controls.ServerControlContainer", {
	constructor: function() {
		this.base("InfoNgen.TouchPoint.Common.Search.Controls.SRCH_SearchCustomMetaStructuresModules");
		this.__ContainerID = null;
		if (!IS_TMC_USER)
			this.DataLoadText = "Loading...";
		this.OnXmlChange();
		this.fnXMLCH = this.CreateCallback(this.OnXmlChange);
		this.Listener = new AS.EventListener(this.fnXMLCH, true);
		this.Listener.Attach();
	}
	,Dispose: [decl_virtual, function() {
		this.Listener.Detach();
		this.fnXMLCH = null;
		this.Listener.Dispose();
		this.Listener = null;
		this.base.Dispose();
	}]
	,SetContainerID: function(cnt_id) {
		if (!cnt_id) {
			if (!str_IsStringEmpty(this.__ContainerID))
			{
				var nav_cnt_id = nav_currentNavInfo.GetContainerLocation();
				
				if (nav_cnt_id == this.__ContainerID && !MANUALLYSELECTEDCONTAINERID)
				{
					nav_ChangePageParams(P_CONTAINER_ID);
					srch_advSetCID(null);
				}
			}
		}
		if (this.__ContainerID != cnt_id) {
			this.__ContainerID = cnt_id;
			as_ResetCustomControls();
			this.RemoveParameter(P_CONTAINER_ID);			
			this.AddParameter(P_CONTAINER_ID,str_IsStringEmpty(this.__ContainerID) ? "" : this.__ContainerID);
			this.Refresh(this.DataLoadText);
		}
	}
	,OnXmlChange: function() {
		SkipAdvancedSearchConfirmation = true;
		this.SetContainerID(srch_GetSingleContainerFromSearch(GlASM.GetPID()));
		SkipAdvancedSearchConfirmation = false;
	}
});


//--------------------------------------------------------------------------------------------
DeclareClass("UI.AS.GridSelector", "UI.Controls.ServerControlContainer", {
	constructor: function(ctlType, nameNodeName, valueNodeName){
		this.base(ctlType);
		this.nameNodeName = nameNodeName;
		this.valueNodeName = valueNodeName;
		this.DataSetHelper = new Data.DataSetHelper();
		this.eventID = data_attachEvent("ondatasetregistered", this.onDatasetRegister.bind(this));
	}
	,AMLoad : [decl_virtual, function(txt, params) {
		this.eventID = data_attachEvent("ondatasetregistered", this.onDatasetRegister.bind(this));
		this.Refresh(txt, params);
	}]
	,AddValue: function(name, value) {
		this.AddValues([{name:name, value:value}])
	}
	,AddValues: function(values) {
		if(this.DataCache && values && values.length>0){
			var collection = this.DataSetHelper.GetData();
			var xDoc = this.DataCache.GetXmlDocument();
			for(var i=0; i<values.length; i++){
				var item = xDoc.selectSingleNode("//~0[~1='~2']".format(this.DataCache.xdata.itemQuery, this.valueNodeName, values[i].value));
				if(item)
					collection.AddXmlItem(item.xml);
			}
			this.DataSetHelper.SetXml(collection.GetXml());
		}
	}
	,DelByValue: function(value){
		if(this.DataCache){
			var item = this.DataCache.GetXmlDocument().selectSingleNode("//~0[~1='~2']".format(this.DataCache.xdata.itemQuery, this.valueNodeName, value));
			if(item)
				this.DataSetHelper.DeleteXmlItem(item.xml);
			this.FireEvent("onafteritemdelete", value, item!=null);
		}
	}
	,GetSortedIndex: function(name){
		return 0;
	}
	,GetSelectedItems: function() {
		var selectedValues = this.DataSetHelper.GetSelectedData();
		var values = [];
		if (selectedValues != null)
			for (var i = 0, imax = selectedValues.GetCount(); i < imax; i++) {
				var node = selectedValues.GetByIndex(i);
				values[i] = {"name":node.getValue(this.nameNodeName), "value":node.getValue(this.valueNodeName)};
			}
		return values;
	}
	,MoveSelectRows: function(dest, onlyUnique) {
		var res = [];
		var selectItems = this.GetSelectedItems();
		for (var i = 0, item; item = selectItems[i]; i++)
			if (dest.AddValue(item.name, item.value, dest.GetSortedIndex(item.name), onlyUnique==true)) 
				res.push({text:item.name, value:item.value});
		if (selectItems.length > 0) {
			this.DataSetHelper.RemoveSelectedData();
			tplb_ClearSelections(dest);
		}
		return res;
	}
	,SetXML: function(xml) {
		this.DataSetHelper.SetXml(xml);
	}
	,Clear: function() {
		this.SetXML(null);
	}
	,onDatasetRegister: function(ds){
		if(ds.name == this.GetClientID()+"_c"){
			this.DataSetHelper.__dataset = ds;
			data_detachEvent("ondatasetregistered", this.eventID);
			this.DataCache = ds.CreateCopy(true);
			this.FireEvent("ondataloaded");
		}
	}
});
DeclareNamespace("UI.Filters");
UI.Filters.FilterItems = [];
UI.Filters.DoFilter = function()
{
	for (var i=0; i< UI.Filters.FilterItems.length; i++)
	{
		var item =UI.Filters.FilterItems[i];
		if(item.IsVisible())
		{
			item.DeleteFiltersFromInpPan();
			var tag = item.GetTag();
			var values = item.GetValues();
			if(values)
				for(var j=0; j<values.length; j++)
					if(typeof(values[j])=="object")
						srch_inpAddFilter(tag, values[j].value, values[j].text);
					else
						srch_inpAddFilter(tag, values[j], values[j]);		
		}
	}
	srch_inpDoSearch();
}

DeclareClass("UI.Filters.FilterItem", "UI.Controls.NavFilterControl",
{
	constructor : function( filter, titleHTML, tagName)
	{
		this.base(filter);
		this.titleHtml = titleHTML;
		this.tagName = tagName;
		UI.Filters.FilterItems.push(this);
		this.SetCssClass("action-filter");
		this.SetAttribute("cellSpacing", 0);
		this.SetAttribute("cellPadding", 0);
	}		
	,GetTagName : function() {return UI.HtmlTag.Table;}
	,GetCssClassName : function() {return UI.HtmlTag.Table;}
	,Render :[decl_virtual, function(writer)
	{
		var row = this.HostElement.insertRow();
		var cell = row.insertCell();
		cell.innerHTML = this.titleHtml;
		cell = row.insertCell();
		for (var i = 0; i < this.__controls.length; i++)
			this.__controls[i].RenderControl(cell);
	}]
	
	,GetValues :[decl_virtual, function(){return null; }]
	,GetTag :[decl_virtual, function(){return this.tagName; }]
	,DeleteFiltersFromInpPan :[decl_virtual, function(){ srch_inpDeleteFilters(this.GetTag()); }]
	,Dispose :[decl_virtual, function(){ UI.Filters.FilterItems.removeItem(this); this.base.Dispose();}]
	,OnFilterChange : function() {UI.Filters.DoFilter();}
});

DeclareClass("UI.Filters.DropDownFilterItem", "UI.Filters.FilterItem",
{
	constructor : function( filter, titleHTML, tagName)
	{
		this.base(filter, titleHTML, tagName);
		this.DropDown = new UI.Controls.DropDown();
	}

	,Init : [decl_virtual, function()
	{
		this.DropDown.ID = "dd";
		this.DropDown.SetCssClass("f02");
		this.DropDown.AttachEvent("onselected", this.CreateCallback(this.OnFilterChange));
		this.AddControl(this.DropDown);
		
	}]
	,GetValues :[decl_virtual, function(){ return this.DropDown.SelectedValue?[{"text":this.DropDown.GetDisplayValue(), "value":this.DropDown.SelectedValue}]:[];}]
	,SetValue : function(value, fireevent)
	{
		this.DropDown.SetSelectedValue(value, fireevent);
	}
	,FillFromCache: function (cache, undefinedValue, selectedValue, textField, valueField)
	{
		if(undefinedValue!=null)
			this.DropDown.AddItem(undefinedValue,"");
		if(cache==null)
			return;
		for(var i=0; i<cache.length; i++)
			if(typeof(cache[i])=='object')
				this.DropDown.AddItem(cache[i][textField], cache[i][valueField]);
			else
				this.DropDown.AddItem(cache[i], cache[i]);
		if(selectedValue!=null)
			this.DropDown.SetSelectedValue(selectedValue);	
	}
});

DeclareClass("UI.Filters.PortfolioFilter", "UI.Filters.DropDownFilterBarItem",
{
	constructor : function( filter, titleHTML)
	{
		this.base(filter, titleHTML, SRCH_TN_PORTFOLIO, "tool-filter-select-portf");
		this.KeywordsAttach(KEY_PORTFOLIO);
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.RefreshList();
	}]
	,AMLoad :[decl_virtual, function()
	{
		this.RefreshList();
	}]
	,GetSearchTagName : [decl_virtual, function()
	{
		return SRCH_TN_PORTFOLIO;
	}]
	,RefreshCallback: function(porfolio)
	{
		this.DropDown.Clear();
		this.DropDown.AddItem("Unfiltered","");
		this.DropDown.SetSelectedValue("", false);
			
		if(porfolio)
			for(var i=0; i< porfolio.GetCount(); i++)
			{
				var xItem = porfolio.GetByIndex(i);
				this.DropDown.AddItem(xItem.GetNodeValue(FilterItem.PN_DISPLAY_VALUE), xItem.GetNodeValue(FilterItem.PN_VALUE));
			}
	}
	,RefreshList: function ()
	{
		new httpcmd_GetDataSource("MyPortfolios",this.CreateCallback(this.RefreshCallback));
		this.DropDown.Clear();
		this.DropDown.AddItem("Loading...", "");
	}
});

DeclareClass("UI.Filters.DropDownFilterBarItem", "UI.Filters.DropDownFilterItem",
{
	constructor : function( filter, title, tagName, cssclass)
	{
		this.base(filter, "<span class='tool-filter-label'>" + title + "</span>", tagName);
		this.cssclass = str_IsStringEmpty(cssclass) ? "tool-filter-select" : cssclass;
	}
	,Init : [decl_virtual, function()
	{
		this.base.Init();
		this.DropDown.SetCssClass(this.cssclass);
		this.Listeners.AddCustomListener(new Utils.SearchEventListener([this.GetSearchTagName()],this.AnalyzeSearchState))
	}]
	,GetSearchTagName : [decl_virtual, function()
	{
		return null;
	}]
	,AnalyzeSearchState : [decl_virtual, function(listener)
	{		
		this.SetValue(listener.GetTagValue(this.GetSearchTagName()),false);
	}]
	,LoadData : [decl_virtual, function()
	{
	}]	
});

DeclareClass("UI.Filters.PeriodFilterBarItem", "UI.Filters.DropDownFilterBarItem",
{
	constructor : function( filter )
	{
		this.base(filter, "Period", SRCH_TN_PERIOD);
	}
	,LoadData : [decl_virtual, function()
	{
		this.FillFromCache(TPCalendarDateFilterValues, null, null, "name", "value");
		this.DropDown.AddItem("Custom", "");
		this.SetValue("",false);		
	}]
	,GetValues : [decl_virtual, function(){ return this.DropDown.SelectedValue?[this.DropDown.SelectedValue]:[];}]
	,GetSearchTagName : [decl_virtual, function()
	{
		return SRCH_TN_PERIOD;
	}]
});

DeclareClass("UI.Filters.EventsFilterBarHeader", "UI.Controls.ItemBarBase",
{
	constructor: function(collapsibleParent)
	{
		this.base();
		this.CollapsibleParent = collapsibleParent;
	}
	,Init : [decl_virtual, function()
	{
		var clps = new UI.Controls.CollapsibleHeaderControl("Event types",this.CollapsibleParent.Expanded,this.CollapsibleParent);
		clps.SetStyleAttribute("paddingRight", "13px");
		this.AddItem(clps);
		this.AddItem(new UI.Controls.EventTypesControl());
		
		if (!IS_ANONYMOUS_USER)
		{
			this.AddItem(new UI.Filters.FilterBarSeparator(),null,"filter-separator");
			this.AddItem(new UI.Filters.PortfolioFilter("", "Portfolio"));						
		}
		this.AddItem(new UI.Filters.FilterBarSeparator("100%"),UI.Controls.ItemBarAlign.RIGHT,"filter-separator");
		var filter = new UI.Filters.PeriodFilterBarItem("");
		this.AddItem(filter, UI.Controls.ItemBarAlign.RIGHT, "calendar-rightheadercell");
		filter.LoadData();
		this.AddItem(new UI.Controls.CollapsibleImageControl("calendar.png","calendar.png",this.CollapsibleParent.Expanded,this.CollapsibleParent),UI.Controls.ItemBarAlign.RIGHT,"calendar-link");
	}]
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.NOUPDATE;}]
});

DeclareClass("UI.Filters.EventsFilterBarContent", "UI.Controls.ItemBarBase",
{
	constructor: function(collapsibleParent)
	{
		this.base();
		this.CollapsibleParent = collapsibleParent;
		this.AsyncRenderingEnabled = true;
	}
	,Init : [decl_virtual, function()
	{
		this.AddItem(new UI.Controls.EventSubTypesControl(),null,"calendar-leftcell");
		this.AddItem(new UI.Filters.FilterBarSeparator("100%"),UI.Controls.ItemBarAlign.RIGHT,"filter-separator");
		this.AddItem(new UI.Controls.ServerControlContainer("InfoNgen.TouchPoint.Modules.Common.DateTime.TPNavigationCalendar"), UI.Controls.ItemBarAlign.RIGHT, "calendar-rightcontentcell");
	}]
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.CHILDREN_REFRESH;}]
});

DeclareClass("UI.Filters.EventsTypeInfoBase", null,
{
	constructor: function(code, name, state)
	{
		this.code = code;
		this.state = state;
		this.name = name;
		this.events = new cmn_EventContainer();
	}
	,__InternalSetState : function(val)
	{
		if (this.state != val)
		{
			this.state = val;
			this.events.fireEvent("onstatuschange",  this.GetCode(), this.GetState());
			return true;
		}
		return false;
	}
	,AttachEvent: function(evtname, func)
	{
		 return this.events.attachEvent(evtname, func); 
	}
	,DetachEvent: function(evtname, id)
	{ 
		return this.events.detachEvent(evtname, id); 
	}
	,GetCode : function()
	{
		return this.code;
	}
	,GetName : function()
	{
		return this.name;
	}
	,GetState : function()
	{
		return this.state;
	}
	,SetState : [decl_virtual, function(val)
	{
		return this.__InternalSetState(val);
	}]
});

DeclareClass("UI.Filters.EventsTypeInfo", "UI.Filters.EventsTypeInfoBase",
{
	constructor: function(item)
	{
		this.base(item.code, item.name, item.state);
		this.InitSubTypes(item.subgroups);
	}
	,InitSubTypes : function(subtypes)
	{
		this.checkedcount = 0;
		this.subtypes = new dm_KeyedCollection();
		if (subtypes != null)
		{
			for(var i=0; i < subtypes.length; i++ )
			{
				var item = new UI.Filters.EventsSubTypeInfo(subtypes[i]);
				item.AttachEvent("onstatuschange", this.CreateCallback(this.OnStatusSubTypeChange));
				this.subtypes.Add(subtypes[i].code, item);
			}
		}
	}
	,__InternalSetSubTypeStatus : function(code, status)
	{
		var item = this.subtypes.Get(code)
		if (item != null && item.SetState(status))
		{
			if (status == UI.CheckBoxStates.CHECKED)	
				this.checkedcount++;
			else
				this.checkedcount--;
			return true;
		}
		return false;
	}
	,OnStatusSubTypeChange : function(code, state)
	{
		this.events.fireEvent("onstatussubtypechange", code, state);
	}
	,GetSubTypes : function()
	{
		return this.subtypes;
	}
	,SetState : [decl_virtual, function(val)
	{
		if (this.state != val)
		{
			this.state = val;
			if (val == UI.CheckBoxStates.CHECKED || val == UI.CheckBoxStates.UNCHECKED)
				for(var i=0; i < this.subtypes.getCount(); i++)
					this.__InternalSetSubTypeStatus(this.subtypes.GetByIndex(i).GetCode(), val);
			this.events.fireEvent("onstatuschange",  this.GetCode(), this.GetState());
			return true;
		}
		return false;
	}]
	,GetSubTypeStatus : function(code)
	{
		var item = this.subtypes.Get(code)
		if (item != null)
			return item.GetState();
		return UI.CheckBoxStates.UNCHECKED;
	}
	,SetSubTypeStatus : function(code, status)
	{
		if (this.__InternalSetSubTypeStatus(code, status))
		{
			switch(this.checkedcount)		
			{
				case 0:
					this.__InternalSetState(UI.CheckBoxStates.UNCHECKED);
					break;
				case this.subtypes.getCount():
					this.__InternalSetState(UI.CheckBoxStates.CHECKED);
					break;
				default:
					this.__InternalSetState(UI.CheckBoxStates.PARTIALCHECKED);
					break;
			}
			return true;
		}
		return false;
	}
});

DeclareClass("UI.Filters.EventsSubTypeInfo", "UI.Filters.EventsTypeInfoBase",
{
	constructor: function(item)
	{
		this.base(item.code, item.name, UI.CheckBoxStates.UNCHECKED);
	}
});

DeclareClass("UI.Filters.EventsTypeManager", null,
{
	constructor: function()
	{
		this.events = new cmn_EventContainer();
		this.InitTypes();
		srch_seAttachEvent("onstatechange", this.CreateCallback(this.OnSearchChange));
		this.__isSearchProhibited = false;
	}
	,GetInstance : [decl_static, function()
	{
		if (UI.Filters.EventsTypeManager.instance == null)
			UI.Filters.EventsTypeManager.instance = new UI.Filters.EventsTypeManager();
		return UI.Filters.EventsTypeManager.instance;
	}]
	,AttachEvent: function(evtname, func)
	{
		 return this.events.attachEvent(evtname, func); 
	}
	,DetachEvent: function(evtname, id)
	{ 
		return this.events.detachEvent(evtname, id); 
	}
	,InitTypes : function()
	{
		this.types = new dm_KeyedCollection();
		for(var i=0, ic = TPEventGroupCache.length; i < ic; i++)
		{
			var item = new UI.Filters.EventsTypeInfo(TPEventGroupCache[i])
			item.AttachEvent("onstatuschange", this.CreateCallback(this.OnStatusTypeChange));
			item.AttachEvent("onstatussubtypechange", this.CreateCallback(this.OnStatusSubTypeChange));
			this.types.Add(item.code, item);
		}
	}
	,SetEventTypeStatus : function(code, status)
	{
		var item = this.types.Get(code);
		if (item != null)
			return item.SetState(status);
		return false;
	}
	,GetEventSubTypeStatus : function(code, subcode)
	{
		var item = this.types.Get(code);
		if (item != null)
			return item.GetSubTypeStatus(subcode);
		return UI.CheckBoxStates.UNCHECKED;
	}
	,SetEventSubTypeStatus : function(code, subcode, status)
	{
		var item = this.types.Get(code);
		if (item != null)
			return item.SetSubTypeStatus(subcode, status);
		else
			for(var i=0; i<this.types.getCount(); i++)
				if (this.types.GetByIndex(i).GetSubType(subcode) != null)
					return this.types.GetByIndex(i).SetSubTypeStatus(subcode, status);
		return false;
	}
	,SomeChecked : function()
	{
		for(var i=0; i < this.types.getCount(); i++)
			if (this.types.GetByIndex(i).GetState() != UI.CheckBoxStates.UNCHECKED)
				return true;
		return false;
	}
	,DoSearch : function()
	{
		if (this.__isSearchProhibited == true) return;
		srch_inpDeleteFilters(SRCH_TN_EVENTSUBTYPE);
		for(var i=0, ic = this.types.getCount(); i < ic; i++)
		{
			var type = this.types.GetByIndex(i);
			if (type.GetState() != UI.CheckBoxStates.UNCHECKED)
			{
				var subtypes = type.GetSubTypes();
				for(var j = 0, jc = subtypes.getCount(); j < jc; j++)
				{
					var item = subtypes.GetByIndex(j);
					if (item.GetState() == UI.CheckBoxStates.CHECKED)
						srch_inpAddFilter(SRCH_TN_EVENTSUBTYPE, item.GetCode(), item.GetName(), true);
				}
			}
		}
		window.setTimeout(srch_inpDoSearch,1);
	}
	,Reset : function()
	{
		for(var i=0, ic = this.types.getCount(); i<ic; i++)
		{
			var type = this.types.GetByIndex(i);
			if (type.GetState() != UI.CheckBoxStates.UNCHECKED)
				type.SetState(UI.CheckBoxStates.UNCHECKED);
		}
	}
	,OnSearchChange : function(state)
	{
		if ((state == SRCH_SES_NONE && !this.SomeChecked())||
			(state != SRCH_SES_NONE && state != SRCH_SES_FILTER))
			return;
		if (srch_inpGetTag(new Array(new srch_XmlSearchExParam(SRCH_TP_NAME,SRCH_TN_SAVEDSEARCH))) != null)
		{
			this.__isSearchProhibited = true;
			this.Reset();
			this.__isSearchProhibited = false;
			return;
		}	
		this.__isSearchProhibited = true;
		for(var i=0, ic = this.types.getCount(); i < ic; i++)
		{
			var type = this.types.GetByIndex(i);
			var subtypes = type.GetSubTypes();
			for(var j = 0, jc = subtypes.getCount(); j < jc; j++)
			{
				var item = subtypes.GetByIndex(j);
				var tag = srch_inpGetTag([new srch_XmlSearchExParam(SRCH_TP_NAME,SRCH_TN_EVENTSUBTYPE), new srch_XmlSearchExParam(SRCH_TP_VALUE, item.GetCode())])
				var status = tag == null ? UI.CheckBoxStates.UNCHECKED : UI.CheckBoxStates.CHECKED;
				type.SetSubTypeStatus(item.GetCode(), status);
			}
		}
		this.__isSearchProhibited = false;
	}
	,OnStatusTypeChange : function(code, state)
	{
		this.events.fireEvent("oneventtypestatuschange",  code, state);
	}
	,OnStatusSubTypeChange : function(code, state)
	{
		this.events.fireEvent("oneventsubtypestatuschange",  code, state);
	}
});

DeclareClass("UI.Filters.FeedsCategoryFilterBarHeader", "UI.Controls.ItemBarBase",
{
	constructor: function(collapsibleParent)
	{
		this.base();
		this.CollapsibleParent = collapsibleParent;
	}
	,Init : [decl_virtual, function()
	{
		this.__contentControls = [];
		if (this.CollapsibleParent)
		{
			this.CollapsibleParent.AttachEvent("collapse",this.CreateCallback(this.HideContent));
			this.CollapsibleParent.AttachEvent("expand",this.CreateCallback(this.ShowContent));
		}
		this.AddItem(new UI.Controls.CollapsibleHeaderControl("Categories",this.CollapsibleParent.Expanded,this.CollapsibleParent));
		this.__contentControls.push(new UI.Controls.ScriptLink("Subscribe All", 
			this.CreateCallback(this.Subscribe)));
		this.__contentControls[this.__contentControls.length-1].UpdateRule = UI.UpdateStatus.FULL_REFRESH;
		this.AddItem(this.__contentControls[this.__contentControls.length-1]);
		this.__contentControls.push(new UI.Controls.Label(" - "));
		this.AddItem(this.__contentControls[this.__contentControls.length-1]);
		this.__contentControls.push(new UI.Controls.ScriptLink("Unsubscribe All", 
			this.CreateCallback(this.Unsubscribe)));
		this.__contentControls[this.__contentControls.length-1].UpdateRule = UI.UpdateStatus.FULL_REFRESH;
		this.AddItem(this.__contentControls[this.__contentControls.length-1]);		
		if (!this.CollapsibleParent.Expanded)
			this.HideContent();
	}]
	,HideContent : function()
	{
		this.ShowContent(false);
	}
	,ShowContent : function(vis)
	{
		vis = vis == false ? false : true;
		for (var i=0; i < this.__contentControls.length; i++)
			this.__contentControls[i].SetVisibleState(vis);
	}
	,Subscribe : function(subscr)
	{
		if (!AuthorizationNeeded()) 
		{
			this.CollapsibleParent.Lock();
			this.__subscr = subscr == false ? false : true;
			new httpcmd_FeedCategoryChangeSubscription(-1, this.__subscr, this.CreateCallback(this.SubscribeCallback));
		}
		return false;
	}
	,Unsubscribe : function()
	{
		return this.Subscribe(false);
	}
	,SubscribeCallback : function(isOk)
	{
		if (isOk)
		{
			nav_RefreshWorkspaceModules(KEY_FEEDCATEGORY);
			this.__subscr ? this.CollapsibleParent.SubscribeAll() : this.CollapsibleParent.UnsubscribeAll();
		}
		this.CollapsibleParent.Unlock();
	}
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.NOUPDATE;}]
});

DeclareClass("UI.Filters.FeedsCategoryFilterBarContent", "UI.Controls.ItemBarBase",
{
	constructor: function(collapsibleParent)
	{
		this.base();
		this.CollapsibleParent = collapsibleParent;
		this.__categoriescontrol = null;
	}
	,Init : [decl_virtual, function()
	{
		this.__categoriescontrol = new UI.Controls.FeedCategoryTypesControl();
		this.AddItem(this.__categoriescontrol,null,"calendar-leftcell");
	}]
	,Update :[decl_virtual, function(writer){return UI.UpdateStatus.CHILDREN_REFRESH;}]
	,Render :[decl_virtual, function(writer)
	{
		this.base.Render();
		this.HostElement.style.width = "100%";
	}]
	,SubscribeAll : function()
	{
		if (this.__categoriescontrol)
			this.__categoriescontrol.SubscribeAll();
	}
	,UnsubscribeAll : function()
	{
		if (this.__categoriescontrol)
			this.__categoriescontrol.UnsubscribeAll();
	}
});


DeclareClass("UI.Filters.FilterBarSeparator", "UI.Control",
{
	constructor: function(height)
	{
		this.base();
		this.__heigth = height;
		this.SetCssClass("filter-separator");
		if (this.__heigth)
			this.SetStyleAttribute("height", this.__heigth);
	}
	,GetTagName : function() 
	{
		return UI.HtmlTag.Div;
	}
});
DeclareClass("UI.SpecialRenderer.RegisterWorkspaceModule", null,
{
	GetObjectType : [decl_static, function()
	{
		return "WorkspaceModule";
	}]
	,RegisterObjects : [decl_static, function(uiObjects)
	{
		if (!uiObjects || uiObjects.length == 0) return;
		var i = uiObjects.length - 1;
		while(i >= 0)
		{
			var dOb = uiObjects[i--], obj=dOb.Obj(), psid=obj.previousSibling.id;
			if (!str_IsStringEmpty(psid))
			{
				var module = nav_RegisterWorkspaceModule(psid, dOb.getAttribute("ModuleName"), 
					dOb.getAttribute("Keywords"), dOb.getAttribute("QueryFilter"), 
					dOb.getAttribute("Preferences"), dOb.getAttribute("DSName"));
				new UI.WorkspaceModuleInfo(module.Obj(), module);
			}
			obj.removeNode();
		}
	}]
});
UI.SpecialRenderer.RegisterProcessingObject(UI.SpecialRenderer.RegisterWorkspaceModule);

DeclareClass("UI.WorkspaceModuleInfo", "UI.ItemInfo",{ 
	constructor : function(htmlobj, obj)
	{
		this.base(htmlobj, obj);
	}
	,AdditionalDispose : function()
	{
		if (this.obj && this.obj.id && !str_IsStringEmpty(this.obj.id))
			nav_DisposeWorkspaceModule(this.obj.id);
	}
});

var UIObjects = new Object();

function ui_ChangeCollapse(isCollapsed)
{
	this.base = UI.RenderableObject;
	this.isCollapsed = isCollapsed == "true";
	this.hasChildren = !(isCollapsed == "null" || isCollapsed=="");
	
	var elemRow;
	var level;

	this.Render=function()
	{	
		this.obj.className = "treeClsp";
		//this.obj.style.display = "block";
		elemRow = this.obj.parentElement;
		level = elemRow.getAttribute("level");
		elemRow.setAttribute("collapsed", (!!this.isCollapsed).toString());

		var prev = elemRow;
		do{
			prev = prev.previousSibling;
		}while(prev!=null && prev.getAttribute("level")>=level)
		
		if(prev!=null && (prev.runtimeStyle.display=="none" || prev.getAttribute("collapsed")=="true"))
			elemRow.runtimeStyle.display="none";
		else
			elemRow.runtimeStyle.display="";
		
		elemRow.runtimeStyle.marginLeft = 15 * level;
		this.SetObjectInnerHtml("");
		if(this.hasChildren)
		{
			this.obj.style.backgroundImage = "url("+cmn_GetImageUrl(this.isCollapsed? "icon_tree_plus.gif" : "icon_tree_minus.gif")+")";
			dom_attachEventForObject(this.obj, "click", this.toggleCollapse);
			
			var next = elemRow.nextSibling;
			while(next!=null && next.getAttribute("level")>level)
			{
				next.runtimeStyle.display = this.isCollapsed?"none": "block";
				if(next.getAttribute("collapsed")=="true")
				{
					var collvl = Number(next.getAttribute("level"));
					do{
						next = next.nextSibling;
					}while(next!=null && next.getAttribute("level")>collvl)
				}
				else
					next = next.nextSibling;
			}			
		}
	}
	
	this.toggleCollapse = function()
	{	
		data_ChangeItemAttribute(elemRow.getAttribute("dSrc"), elemRow.getAttribute("itemID"), "clsp", elemRow.getAttribute("collapsed")!="true");
		event.cancelBubble = true;
	}
	
}
ui_ChangeCollapse.prototype = new UI.RenderableObject;
ui_ChangeCollapse.prototype.constructor = ui_ChangeCollapse;

function ui_TreeNode(selcted, nodeName)
{
	this.base = UI.RenderableObject;
	this.nodeName = nodeName;
	this.selcted = selcted;
	var elemRow;
	var thisObj = this;
	var span;
	
	this.IsRoot = function()
	{
		return elemRow.getAttribute("itemID")=='root';
	}
	this.Render=function()
	{	
		elemRow = this.obj.parentElement;
		span = document.createElement('span');
		span.className = (this.selcted=="true")?"treeSlTxt":"treeTxt";
		span.innerText = elemRow.getAttribute("nodeTitle");
		
		
		this.SetObjectInnerHtml("");
		this.obj.appendChild(span);
		
		if(!this.IsRoot())
		{
			dom_attachEventForObject(span, "dblclick", this.edit);
			
			var anchor = document.createElement('a');
			anchor.innerText="x";
			anchor.title="Remove";
			anchor.style.paddingLeft=5;
			anchor.style.fontWeight='bold';
			anchor.href = "#";
			dom_attachEventForObject(anchor, "click", this.deleteNode);
			this.obj.appendChild(anchor);
		}		
	}
	
	this.deleteNode = function()
	{
		var next, current = elemRow;
		var level = Number(elemRow.getAttribute('level'));
		do{
			next = current.nextSibling;
			data_DeleteDSItem(current.getAttribute('dSrc'), data_SelectSingleItem(current.getAttribute('dSrc'),current.getAttribute('itemID')));
			current = next;
		}while(next!=null && Number(next.getAttribute('level'))>level)
		event.cancelBubble = true;
	}
	this.edit = function()
	{
		var input = document.createElement('input');
		input.value = span.innerText;
		input.className = "f02";		
		thisObj.obj.insertBefore(input, span);
		span.style.display = 'none';
		
		// TO DO: Viacheslav Kopichev (Memory leak problem)	
		dom_attachEventForObject(input, "blur", thisObj.setChange);
		dom_attachEventForObject(input, "keypress", function(){if(event.keyCode==13)thisObj.setChange()});
		input.focus();
	}
	
	this.setChange = function()
	{
		if(event.srcElement.value == span.innerText)
			thisObj.Render();			
		else
		{
			var xItem = data_GetDataset(elemRow.getAttribute('dSrc')).Get(elemRow.getAttribute('itemID'));
			data_ChangeItemProperty(elemRow.getAttribute('dSrc'),xItem, thisObj.nodeName, event.srcElement.value);
		}
	}
}

ui_TreeNode.prototype = new UI.RenderableObject;
ui_TreeNode.prototype.constructor = ui_TreeNode;


function ui_TreeMultySelectCBox(p_selctable, p_selected)
{
	this.base = UI.RenderableObject;
	var selctable = p_selctable != 'false';	
	var selected = p_selected == 'true';

	this.Render=function()
	{
		this.SetObjectInnerHtml("");	
		var cb = document.createElement('input');
		cb.type='checkbox';
		this.obj.appendChild(cb);
		cb.checked = selected;
		if(!selctable)
			cb.disabled = !selctable;
	}
}
ui_TreeMultySelectCBox.prototype = new UI.RenderableObject;
ui_TreeMultySelectCBox.prototype.constructor = ui_TreeMultySelectCBox;


function ui_ChangeCollapseGroup(collapsed)
{
	this.base = UI.RenderableObject;
	this.isCollapsed = collapsed == "true";
	this.row = null;
}
ui_ChangeCollapseGroup.prototype = new UI.RenderableObject;
ui_ChangeCollapseGroup.prototype.constructor = ui_ChangeCollapseGroup;
ui_ChangeCollapseGroup.prototype.Render=function()
{
	this.row = this.GetRow();
	this.domObj = DOMObjectFactory.CreateDOMObject("img", false);
	dom_attachEventForObject(this.domObj.Obj(), "click", this.CreateCallback(this.ChangeCollapse));
	this.isCollapsed = !this.isCollapsed;
	this.ChangeCollapse();
	this.AddHtmlChild(this.domObj.Obj());
}
ui_ChangeCollapseGroup.prototype.GetRow=function()
{
	if (this.obj != null)
	{
		var row = this.obj;
		while(row != null)
		{
			if (row.getAttribute("isGroupRow") != null)
				return row;
			row = row.parentElement;
		}
	}
}
ui_ChangeCollapseGroup.prototype.ChangeCollapse=function()
{
	this.isCollapsed = !this.isCollapsed;
	if (this.isCollapsed)
		this.domObj.setAttribute("src", cmn_GetImageUrl("icon_tree_plus.gif")); 
	else
		this.domObj.setAttribute("src", cmn_GetImageUrl("icon_tree_minus.gif"));
		
	if (this.row != null)
	{
		var item = this.row.nextSibling;
		var val = this.isCollapsed ? "none" : "";
		while(item != null && item.getAttribute("isGroupRow") == null)
		{
			item.style.display = val;
			item = item.nextSibling;
		}
	}
}

function ui_ChangeFavorite(cntid, isfavorite)
{
	this.base = UI.RenderableObject;
	this.cntid = cntid;
	this.isfavorite = isfavorite;
}
ui_ChangeFavorite.prototype = new UI.RenderableObject;
ui_ChangeFavorite.prototype.constructor = ui_ChangeFavorite;
ui_ChangeFavorite.prototype.Render=function()
{
	var imgPath = this.isfavorite == "true" ? "directory-fav.gif" : "directory-fav-disable.gif";
	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "' onclick='if (this.disabled == true) return false; if (new httpcmd_ChangeFavorite(\"" + this.cntid + "\"," + (this.isfavorite == "true" ? "false" : "true")+ ") instanceof httpcmd_ChangeFavorite) { this.disabled = true; } return cmn_cancelEvent(event);' >";
	this.SetObjectInnerHtml(html);
}

function ui_ChangeSubscription(cntid, issubscribed)
{
	this.base = UI.RenderableObject;
	this.cntid = cntid;
	this.issubscribed = issubscribed;
}
ui_ChangeSubscription.prototype = new UI.RenderableObject;
ui_ChangeSubscription.prototype.constructor = ui_ChangeSubscription;
ui_ChangeSubscription.prototype.Render=function()
{
	var script = "";
	var imgPath = "icon_check.gif";
	var cid = nav_currentNavInfo.GetContainerLocation();
	var pid = nav_currentNavInfo.GetPageID();
	
	
		script = "if (this.disabled == true) return false; 	if (new httpcmd_ChangeSubscription(\"" + this.cntid + "\"," + (this.issubscribed == "true" ? "false" : "true")+ ") instanceof httpcmd_ChangeSubscription) { this.disabled = true; } return cmn_cancelEvent(event);";
		switch(pid)
		{
			case PID_FEEDS:
				imgPath = this.issubscribed == "true" ? "category-subscribed.gif" : "category-unsubscribed.gif"; 
				break;
			case PID_FOLDERS:
				imgPath = this.issubscribed == "true" ? "category-subscribed.gif" : "category-unsubscribed.gif"; 
				break;
			case PID_CALENDARS:
				imgPath = this.issubscribed == "true" ? "category-subscribed.gif" : "category-unsubscribed.gif"; 
				break;
			case PID_BLOGS:
				imgPath = this.issubscribed == "true" ? "category-subscribed.gif" : "category-unsubscribed.gif"; 
				break;
			default:
		imgPath = this.issubscribed == "true" ? "icon_check.gif" : "icon_check_grey.gif"; 
				break;
		}
		
	
	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "'	onclick='"+script+"'>";
	this.SetObjectInnerHtml(html);
}

function ui_ModuleCollapse(moduleid, iscollapsed)
{
	this.base = UI.RenderableObject;
	this.moduleid = moduleid;
	this.isCollapsed = iscollapsed;
}
ui_ModuleCollapse.prototype = new UI.RenderableObject;
ui_ModuleCollapse.prototype.constructor = ui_ModuleCollapse;
ui_ModuleCollapse.prototype.Render=function()
{
	var domObj = DOMObjectFactory.CreateTempDOMObject("img");
	if (this.isCollapsed == "true")
		domObj.setAttribute("src", cmn_GetImageUrl("icon_tree_plus.gif")); 
	else
		domObj.setAttribute("src", cmn_GetImageUrl("icon_tree_minus.gif"));
	domObj.setAttribute("onclick", "nav_ChangeModuleSettings('" +this.moduleid+"','IsCollapsed','" + (this.isCollapsed == "true" ? "false" : "true") + "')" );
	this.SetObjectInnerHtml(domObj.getOuterHTML());	
}

function ui_ModuleAdjustItemCount(moduleid, iscollapsed, itemsCount)
{
	this.base = UI.RenderableObject;
	this.moduleid = moduleid;
	this.isCollapsed = iscollapsed;
	this.itemsCount = itemsCount;
	
	this.linkCSS = "text-14pix-bold";
	this.plusLinkText = "+";
	this.minusLinkText = "-";
	
}

ui_ModuleAdjustItemCount.prototype = new UI.RenderableObject;
ui_ModuleAdjustItemCount.prototype.constructor = ui_ModuleAdjustItemCount;
ui_ModuleAdjustItemCount.prototype.Render=function()
{
	if (this.isCollapsed == "true")
		this.SetObjectInnerHtml("");	
	else
		this.SetObjectInnerHtml(this.GetAdjustLink("+") + "&nbsp;" + this.GetAdjustLink("-"));	
}

ui_ModuleAdjustItemCount.prototype.GetAdjustLink=function(op)
{
	var domObj = DOMObjectFactory.CreateTempDOMObject("a");
	domObj.setInnerText( op == "+" ? this.plusLinkText : this.minusLinkText);
	domObj.setAttribute("href", "#");
	domObj.applyClass(this.linkCSS);
	if (op == "-")
	{
		domObj.setAttribute("onclick", "nav_ChangeModuleSettings('" +this.moduleid+"','ItemCount','-');return false;" );
		domObj.setAttribute("title", "Display fewer items");
	}
	else
	{
		domObj.setAttribute("title", "Display more items");
		domObj.setAttribute("onclick", "nav_ChangeModuleSettings('" +this.moduleid+"','ItemCount','+');return false;" );
	}
	return domObj.getOuterHTML();	
}


function ui_ModuleRefreshLink(moduleid, iscollapsed)
{
	this.base = UI.RenderableObject;
	this.moduleid = moduleid;
	this.isCollapsed = iscollapsed;
	
	this.linkText = "Refresh";
}
ui_ModuleRefreshLink.prototype = new UI.RenderableObject;
ui_ModuleRefreshLink.prototype.constructor = ui_ModuleRefreshLink;
ui_ModuleRefreshLink.prototype.Render=function()
{
	html = "";	
	if (this.isCollapsed != "true") {
		html = this.GetHTMLContent();
	}
	this.SetObjectInnerHtml(html);	
}

ui_ModuleRefreshLink.prototype.GetHTMLContent = function() {
	return this.GetRefreshLink();
}

ui_ModuleRefreshLink.prototype.GetRefreshLink = function() {
	var domObj = DOMObjectFactory.CreateTempDOMObject("a");
	domObj.setInnerText(this.linkText);
	domObj.setAttribute("href", "#");
	domObj.setAttribute("title", "Refresh current panel");
	domObj.setAttribute("onclick", "nav_RefreshWorkspaceModule('" +this.moduleid+"','Loading...');return false;" );
	return domObj.getOuterHTML()
}

function ui_MessageCommentsLink(docid, mstype, commentsCount)
{
	this.base = UI.RenderableObject;
	this.docid = docid;
	this.mstype = mstype;
	this.commentsCount = commentsCount;
}
ui_MessageCommentsLink.prototype = new UI.RenderableObject;
ui_MessageCommentsLink.prototype.constructor = ui_MessageCommentsLink;
ui_MessageCommentsLink.prototype.Render=function()
{
	var domObj = DOMObjectFactory.CreateTempDOMObject("a");
	var txt;
	var counttxt="";
	/*
	if (this.commentsCount > 1)
		txt = this.commentsCount+" Comments";
	else if (this.commentsCount == 1)
		txt = "1 Comment";
	else
		txt = "Comment Here";
	*/
	if (this.commentsCount > 0)
		counttxt = " (" + this.commentsCount + ")";
	
	txt = "Comment Here";

		
	domObj.setInnerText(txt);
		domObj.setAttribute("href", "#");
	domObj.setAttribute("onclick", "do_CommentMessage(" +this.docid+",\"" + this.mstype + "\",\"commentscroll\");return false;" );
	
	this.SetObjectInnerHtml("<span class='blogs-sep'>" + domObj.getOuterHTML()+counttxt+"</span>");	
}

function ui_ClusterLink(title, clusterID, relatedCount, clusterName, pid, urlparams)
{
	this.base = UI.RenderableObject;	
	this.title = title;
	this.clusterName = clusterName ? clusterName : this.title;
	this.clusterID = clusterID;
	this.relatedCount = relatedCount;	
	this.pid = pid == null ? "" : pid;
	this.urlparams = urlparams;
}
ui_ClusterLink.prototype = new UI.RenderableObject;
ui_ClusterLink.prototype.constructor = ui_ClusterLink;
ui_ClusterLink.prototype.Render = function()
{
	var html = "";
	html += this.GetLink();
	this.SetObjectInnerHtml(html); 
}
ui_ClusterLink.prototype.GetLink = function(sBefore,sAfter,tooltip,cssclass,showBrackets, showNumber, showClusterFunction) {
	var cluster_id = nav_currentNavInfo && nav_currentNavInfo.GetParameter(P_CLUSTER_ID)
	var rCount = parseInt(this.relatedCount);
	if (this.clusterID 
		&& this.clusterID != "0" 
		&& this.relatedCount 
		&& this.relatedCount != "0" 
		&& str_IsStringEmpty(cluster_id)
		&& rCount!= NaN
		&& rCount>0)
	{
		if (!cssclass) cssclass = "cluster_relatedcount_headlines";
		if (!sBefore) sBefore = "";
		if (!sAfter) sAfter = "";
		if(showNumber)
			sBefore = this.relatedCount+" ";		
		if (tooltip == null)
			tooltip = this.relatedCount + " related " + (this.relatedCount == "1" ? "story" : "stories");
			//tooltip = "Related stories";
					
		var click = (showClusterFunction||"do_showCluster")+"(\"" + this.clusterID + "\",\"" + cmn_scriptEncodeString(this.clusterName) + "\",\"" + this.pid + "\", \"" + this.urlparams + "\");";
		var result = ui_CreateScriptLinkHtml(this.relatedCount, click, str_IsStringEmpty(tooltip) ? false : true, tooltip, cssclass);
		
		if ( showBrackets )
		{
			var spnObj = DOMObjectFactory.CreateTempDOMObject("span");
			spnObj.setInnerHTML( result );
			spnObj.setAttribute("class", cssclass);
			
			result= spnObj.getOuterHTML();
		}
		return result;
	}
	return "";
}

	
function ui_ClusterLinkText(title, clusterID, relatedCount, clusterName, pid, urlparams)
{
	this.base = UI.RenderableObject;	
	this.title = title;
	this.clusterName = clusterName ? clusterName : this.title;
	this.clusterID = clusterID;
	this.relatedCount = relatedCount;	
	this.pid = pid == null ? "" : pid;
	this.urlparams = urlparams;
}
ui_ClusterLinkText.prototype = new UI.RenderableObject;
ui_ClusterLinkText.prototype.constructor = ui_ClusterLinkText;
ui_ClusterLinkText.prototype.Render = function()
{
	var html = "";
	html += this.GetLink();
	this.SetObjectInnerHtml(html); 
}
ui_ClusterLinkText.prototype.GetLink = function(sBefore,sAfter,tooltip,cssclass,showBrackets, showNumber, showClusterFunction) {	
	var cluster_id = nav_currentNavInfo && nav_currentNavInfo.GetParameter(P_CLUSTER_ID)
	var rCount = parseInt(this.relatedCount);
	if (this.clusterID 
		&& this.clusterID != "0" 
		&& this.relatedCount 
		&& this.relatedCount != "0" 
		&& str_IsStringEmpty(cluster_id)
		&& rCount!=NaN
		&& rCount>0)
	{
		if (!cssclass) cssclass = "cluster_relatedcount_headlines";
		if (!sBefore) sBefore = "";
		if (!sAfter) sAfter = "";
		if(showNumber)
			sBefore = this.relatedCount+" "+sBefore;
		if (tooltip == null)
			tooltip = this.relatedCount + " related " + (this.relatedCount == "1" ? "story" : "stories");
			//tooltip = "Related stories";

		var click = (showClusterFunction||"do_showCluster")+"(\"" + this.clusterID + "\",\"" + cmn_scriptEncodeString(this.clusterName) + "\",\"" + this.pid + "\", \"" + this.urlparams + "\")";
		var result = ui_CreateScriptLinkHtml(sBefore + (showNumber ? "" : ">>") + sAfter, click, str_IsStringEmpty(tooltip) ? false : true, tooltip, cssclass);		
		
		if ( showBrackets )
		{
			var spnObj = DOMObjectFactory.CreateTempDOMObject("span");
			spnObj.setInnerHTML( "(" + result + ")" );
			spnObj.setAttribute("class", cssclass);
			
			result= spnObj.getOuterHTML();
		}
		return result;
	}
	return "";
}


function ui_ShowLink(title, link, showTooltip)
{
	this.base = UI.RenderableObject;
	this.title = title;
	this.link = link;
	this.showTooltip = showTooltip;
}
ui_ShowLink.prototype = new UI.RenderableObject;
ui_ShowLink.prototype.constructor = ui_ShowLink;
ui_ShowLink.prototype.Render = function()
{
	var click = "do_showLink(" + "\"" + cmn_scriptEncodeString(this.link) + "\")";
	this.SetObjectInnerHtml(ui_CreateScriptLinkHtml(this.title, click, this.showTooltip));
}

function ui_SubjectLink(docid, mstype, link, title, unread, bodyType, isEmail, showTooltip, clusterID, relatedCount, css, tilePrefix)
{
	this.base = UI.RenderableObject;	
	this.docid = docid;
	this.mstype = mstype;
	this.link = link;	
	this.titlewithprefix = this.title = title;
	this.unread = unread;
	this.bodyType = bodyType;
	this.isEmail = isEmail=='true';
	this.showTooltip = showTooltip;
	this.clusterID = clusterID;
	this.relatedCount = relatedCount;	
	this.restURL = do_showDocument(docid, mstype, "", isEmail, false, true);
	this.css = css;
	this.tilePrefix = tilePrefix;
	if (this.tilePrefix && this.title)
		this.titlewithprefix = this.tilePrefix + this.title;
}
ui_SubjectLink.prototype = new UI.RenderableObject;
ui_SubjectLink.prototype.constructor = ui_SubjectLink;
ui_SubjectLink.prototype.Render = function()
{
	var html = "";
	
	if (this.mstype == MT_DOCUMENT)	{
		var bType = this.isEmail?".msg":this.bodyType;
		var imagePath = GetIconFileName(bType);
		
		if (imagePath.length > 0)
			html += "<img src='" + imagePath +"' />&nbsp;";
	}		
	var newCss = (this.unread.toLowerCase() == 'true' /*&& BrowserInfo.IsFF()*/) ? "newItem" : "";	

	html += getShowDocumentLink(this.docid, this.titlewithprefix, this.mstype, this.link, this.isEmail, this.showTooltip, "~0 ~1".format(this.css, newCss), this.restURL);	

	var clusterLink = new ui_ClusterLinkText(this.title, this.clusterID, this.relatedCount).GetLink("","related >>","","cluster_relatedcount",false, true);
	if (!str_IsStringEmpty(clusterLink)) 
		html += " " + clusterLink;

	if (this.unread.toLowerCase() == 'true' && BrowserInfo.IsIE()) {
		html += "&nbsp;<img  src='" + cmn_GetImageUrl("unread-item-icon.gif") +"' />";
	}
	
	this.SetObjectInnerHtml(html); 
}


function ui_SubjectLinkWithManullyAdded(isManuallyAdded, docid, mstype, link, title, unread, bodyType, isEmail, showTooltip, clusterID, relatedCount, css, tilePrefix)
{
	this.base = UI.RenderableObject;	
	this.docid = docid;
	this.mstype = mstype;
	this.link = link;	
	this.titlewithprefix = this.title = title;
	this.unread = unread;
	this.bodyType = bodyType;
	this.isEmail = isEmail=='true';
	this.showTooltip = showTooltip;
	this.clusterID = clusterID;
	this.relatedCount = relatedCount;	
	this.restURL = do_showDocument(docid, mstype, "", isEmail, false, true);
	this.css = css;
	this.tilePrefix = tilePrefix;
	this.isManuallyAdded = isManuallyAdded=='true';
	if (this.tilePrefix && this.title)
		this.titlewithprefix = this.tilePrefix + this.title;
}
ui_SubjectLinkWithManullyAdded.prototype = new UI.RenderableObject;
ui_SubjectLinkWithManullyAdded.prototype.constructor = ui_SubjectLinkWithManullyAdded;
ui_SubjectLinkWithManullyAdded.prototype.Render = function()
{
	var html = "";
	
	if (this.isManuallyAdded)	{
		var imagePath = cmn_GetImageUrl("add_small.gif");		
		if (imagePath.length > 0)
			html += "<img src='" + imagePath +"' />&nbsp;";
	}	
	if (this.mstype == MT_DOCUMENT)	{
		var bType = this.isEmail?".msg":this.bodyType;
		var imagePath = GetIconFileName(bType);
		
		if (imagePath.length > 0)
			html += "<img src='" + imagePath +"' />&nbsp;";
	}		
	var newCss = (this.unread.toLowerCase() == 'true' /*&& BrowserInfo.IsFF()*/) ? "newItem" : "";	

	html += getShowDocumentLink(this.docid, this.titlewithprefix, this.mstype, this.link, this.isEmail, this.showTooltip, "~0 ~1".format(this.css, newCss), this.restURL);	

	var clusterLink = new ui_ClusterLinkText(this.title, this.clusterID, this.relatedCount).GetLink("","related >>","","cluster_relatedcount",false, true);
	if (!str_IsStringEmpty(clusterLink)) 
		html += " " + clusterLink;

	if (this.unread.toLowerCase() == 'true' && BrowserInfo.IsIE()) {
		html += "&nbsp;<img  src='" + cmn_GetImageUrl("unread-item-icon.gif") +"' />";
	}
	
	this.SetObjectInnerHtml(html); 
}


function getShowDocumentLink(docid, title, type, link, isEmail, showTooltip, css, url) {
	var click = "do_showDocument(" + docid + ",\"" + type + "\",\"" + cmn_scriptEncodeString(link) + "\", "+ isEmail+"); return cmn_cancelEvent(event)";
	return ui_CreateScriptLinkHtml(title, click, showTooltip, null, css, true, url);
}

DeclareClass("UI.HeadlineLink", "UI.RenderableObject",
{
	constructor : function (id, title, type, isEmail, titlePrefix) {
		this.id = id;
		this.title = title;
		this.type = type;
		this.isEmail = isEmail;
		this.titlePrefix = titlePrefix;
		if (this.titlePrefix && this.title)
			this.title = this.titlePrefix + this.title;
		this.restURL = do_showDocument(id, type, "", isEmail, false, true);
	}
	,Render : function() {
		var html = getShowDocumentLink(this.id, this.title, this.type, "", this.isEmail, true, null, this.restURL);
		this.SetObjectInnerHtml(html);
	}
});

DeclareClass("UI.ViewMessageContentLink", "UI.RenderableObject",
{
	constructor : function (id, title, type, isEmail, titlePrefix, link, scriptFunction) {
		this.id = id;
		this.title = title;
		this.type = type;
		this.isEmail = isEmail;
		this.titlePrefix = titlePrefix;
		if (this.titlePrefix && this.title)
			this.title = this.titlePrefix + this.title;
		this.scriptFunction = scriptFunction;
		this.link = link;
	}
	,Render : function() {
		var click = this.scriptFunction+"(" + this.id + ",\"" + this.type + "\",\"" + cmn_scriptEncodeString(this.link) + "\", "+ this.isEmail +"); return cmn_cancelEvent(event)";
		var html = ui_CreateScriptLinkHtml(this.title, click, true, null, null, true, null);
		this.SetObjectInnerHtml(html);
	}
});

/**************************************************************/
function ui_TextBoxPEditor( ds, id, propName, val, clName )
{
	this.base = UI.RenderableObject;
	this.val = val;
	this.ds = ds;
	this.propName = propName;
	this.ds_id = id;
	this.clName = clName;
}
ui_TextBoxPEditor.prototype = new UI.RenderableObject;
ui_TextBoxPEditor.prototype.constructor = ui_TextBoxPEditor;
ui_TextBoxPEditor.prototype.Render=function()
{
	var input = document.createElement("input");
	var domObj = new dom_DOMObject(input);
	input.type = "text";
	if ( this.clName )
		input.className = this.clName;
	else
	{
		input.style.pixelHeight = 20;
		input.style.width = "100%";
	}
	input.value = this.val;
	input.ds_id = this.ds_id;
	input.ds = this.ds;
	input.propName = this.propName;
	this.AddHtmlChild(input);
	
	// TO DO: Viacheslav Kopichev (Memory leak problem)
	dom_attachEventForObject(input,"blur",function(){ui_TextBoxPEditor_changeData( input.ds, input.ds_id, input.propName, input.value )});
}
function ui_TextBoxPEditor_changeData( ds, id, propName, val )
{
	var dsInfo = data_GetDataset(ds);
	dsInfo.ChangeItemProperty(id, propName, val, false );
}
function ui_TextBoxPEditor_clearData( ds, idpropName, id  )
{
	var dsInfo = data_GetDataset(ds);
	var xItem = dsInfo.Get(id);
	if (xItem) xItem.ClearValues( idpropName );
	data_UpdateDSItem(ds, xItem);
//	UpdateIframeSizeFSO(ds);	
}
function ui_TextBoxPEditor_deleteData( ds, id  )
{
	var dsInfo = data_GetDataset(ds);
	var xItem = dsInfo.Get(id);
	data_DeleteDSItem(ds, dsInfo.Get(id));
	UpdateIframeSize(null,ds);
}

/**************************************************************/
var ui_DynamicTextBoxPEditor_IsEditMode = false;
function ui_DynamicTextBoxPEditor( ds, id, propName, val, clName, EmptyText, ActionAfterChange, maxLength)
{
	this.base = UI.RenderableObject;
	this.val = val;
	this.ds = ds;
	this.propName = propName;
	this.ds_id = id;
	this.clName = clName;
	this.carentMode = "label";
	this.textObj = null;
	this.maxLength = maxLength;
	this.labelObj = null;
	this.emptyText = EmptyText ? EmptyText : "";
	this.actionAfterChange = ActionAfterChange ? ActionAfterChange : null;
}
ui_DynamicTextBoxPEditor.prototype = new UI.RenderableObject;
ui_DynamicTextBoxPEditor.prototype.constructor = ui_DynamicTextBoxPEditor;
ui_DynamicTextBoxPEditor.prototype.Render=function()
{
	this.OnCreate();
	if (ui_DynamicTextBoxPEditor.IsEditMode())
	{
		this.labelObj.click();
		this.textObj.focus();
		ui_DynamicTextBoxPEditor.IsEditMode(false);
	}
}
ui_DynamicTextBoxPEditor.IsEditMode = function(value)
{
	if (value != null)
		ui_DynamicTextBoxPEditor_IsEditMode = value;
	return ui_DynamicTextBoxPEditor_IsEditMode;
}
ui_DynamicTextBoxPEditor.prototype.OnCreate=function(){
	//var domObj = new dom_DOMObject(input);
	var main_div = document.createElement("div");
	var thisVar = this;
	if (this.textObj == null && this.labelObj == null)
	{
		this.textObj = document.createElement("input");//document.createElement("input");
		if (this.maxLength)
			this.textObj.maxLength = this.maxLength;
		
		this.textObj.type = "text";
		this.SetClass(this.textObj);
		this.textObj.value =  this.val;
		this.textObj.ds_id = this.ds_id;
		this.textObj.ds = this.ds;
		this.textObj.style.display = "none";
		
		this.textObj.propName = this.propName;

		main_div.innerHTML = "";
		main_div.appendChild(this.textObj);

		//TODO: Viacheslav Kopichev (Memory leak problem)
		dom_attachEventForObject(this.textObj,"blur",this.CreateCallback(this.ChangeStatus))
		dom_attachEventForObject(this.textObj,"keydown",this.CreateCallback(this.ChangeStatus));
		
		this.labelObj = document.createElement("div");
		//this.labelObj.style.height="100%";
		//this.labelObj.style.width="100%";
		this.labelObj.className = "ActionTextBoxLabel";
		
		this.SetLabelText(this.val);
		
		main_div.appendChild(this.labelObj);
		this.AddHtmlChild(main_div);
		dom_attachEventForObject(this.labelObj,"click",this.CreateCallback(this.ChangeStatus));//function(){ui_DynamicTextBoxPEditor_changeData( input.ds, input.ds_id, input.propName, input.value, this )});
	}
}
ui_DynamicTextBoxPEditor.prototype.SetLabelText=function(text){
	
	var t1 = text;
	if (t1 == null) 
		t1="";
	else 
		t1 = str_Trim(t1);
	
	if (t1 == ""){
		if (this.emptyText != "")
			t1 = this.emptyText;
		else
			t1 ="";// "&nbsp;";
			
		this.labelObj.style.color="#999";
	}else
		this.labelObj.style.color="";
		
	if (this.labelObj.textContent != null)
		this.labelObj.textContent = t1;
	else
		this.labelObj.innerText = t1;
}
ui_DynamicTextBoxPEditor.prototype.GetLabelText=function(){
	if (this.labelObj.textContent != null)
		return this.labelObj.textContent;
	else
		return this.labelObj.innerText;
}
ui_DynamicTextBoxPEditor.prototype.SetClass=function(obj){
	if  (obj!=null){
		if ( this.clName )
			obj.className = this.clName;
	}
}
ui_DynamicTextBoxPEditor.prototype.SetEmptyAction=function(emptyAction){
	this.emptyAction = emptyAction;
}

ui_DynamicTextBoxPEditor.prototype.ChangeStatus=function(){
	switch(this.carentMode){
		case "label":
			if (event.srcElement.tagName.toLowerCase() == "input")
				break;
			this.labelObj.style.display="none";
			this.textObj.style.display="";
			try {this.textObj.focus();}
			catch(e) {};
			this.carentMode = "text";
			break;
		/* - - - - - - - - - - - - - -*/
		case "text":
			if (event.srcElement.tagName.toLowerCase() == "input" &&(( event.keyCode == 13 &&  event.type=="keydown")|| event.type=="blur" ))
			{
				this.textObj.value = str_Trim(this.textObj.value);
				if (this.emptyAction && str_IsStringEmpty(this.textObj.value))
					this.emptyAction();
				else
				{
					this.labelObj.style.display="";
					this.textObj.style.display="none";
					this.carentMode = "label";
					if (this.GetLabelText() != this.textObj.value){
						
						ui_DynamicTextBoxPEditor_changeData( this.textObj.ds, this.textObj.ds_id, this.textObj.propName, this.textObj.value);
						if (this.actionAfterChange != null){
							var res = eval(this.actionAfterChange+ "('" +this.ds +"','"+this.ds_id+"');");
							if (typeof(res)=='undefined' || !res){
								this.labelObj.style.display="none";
								this.textObj.style.display="";
								try {this.textObj.focus();}
								catch(e) {};
								this.carentMode = "text";
							}else this.SetLabelText(this.textObj.value);
						}else this.SetLabelText(this.textObj.value);
					}
				}
			}else
			{
				return;
			}
			break;
		/* - - - - - - - - - - - - - -*/
	}		
	event.returnValue = false;
	event.cancelBubble = true;
}
function ui_DynamicTextBoxPEditor_changeData( ds, id, propName, val )
{
	var dsInfo = data_GetDataset(ds);
	dsInfo.ChangeItemProperty(id, propName, val, false );
}
function ui_DynamicTextBoxPEditor_clearData( ds, idpropName, id  )
{
	var dsInfo = data_GetDataset(ds);
	var xItem = dsInfo.Get(id);
	if (xItem) xItem.ClearValues( idpropName );
	data_UpdateDSItem(ds, xItem);
}
/**************************************************************/
function ui_CheckBoxEditor( ds, id, propName, val, clName )
{
	this.base = UI.RenderableObject;
	this.val = ui_CheckBoxEditorTransformValue(val);
	this.ds = ds;
	this.propName = propName;
	this.ds_id = id;
	this.clName = clName;
}
ui_CheckBoxEditor.prototype = new UI.RenderableObject;
ui_CheckBoxEditor.prototype.constructor = ui_CheckBoxEditor;
ui_CheckBoxEditor.prototype.Render=function()
{
	var input = document.createElement("input");
	input.type = "checkbox";
	if ( this.clName )
		input.className = this.clName;
	input.ds_id = this.ds_id;
	input.ds = this.ds;
	input.propName = this.propName;
	this.AddHtmlChild(input);
	input.checked = this.val;
	
	dom_attachEventForObject(input,"blur",function(){ui_CheckBoxEditor_changeData( input.ds, input.ds_id, input.propName, input.checked )});
}
function ui_CheckBoxEditorTransformValue(val)
{
	if (val == "-1" || val == -1 || val == true || (val + "").toLowerCase() == "true") return true;
	return false
}
function ui_CheckBoxEditor_changeData( ds, id, propName, val )
{
	var dsInfo = data_GetDataset(ds);
	dsInfo.ChangeItemProperty(id, propName, ui_CheckBoxEditorTransformValue(val)+"", false );
}

function ui_FileToUpload(id, name, selected, dsName)
{
	this.base = UI.RenderableObject;	
	this.id = id;
	this.name = name;
	this.selected = selected;
	this.dsName = dsName;
}

ui_FileToUpload.prototype = new UI.RenderableObject;
ui_FileToUpload.prototype.constructor = ui_FileToUpload;

ui_FileToUpload.prototype.Render = function()
{	
	var checked = this.selected == 'true' ? 'checked' : '';
	var html = "<input class='chkUpload' type='checkbox' "+ checked +" onclick='ui_FileToUpload.toggleChecked(\""
					+ this.dsName + "\",\"" + this.id +"\")'>" + cmn_htmlEncode(this.name);
	this.SetObjectInnerHtml(html); 
}

ui_FileToUpload.toggleChecked = function(dsName, id) {
	
	var ds = data_GetDataset(dsName);
	if (ds) {
		var xItem = ds.Get(id);
		if (xItem) {
			var checked = xItem.GetNodeValue(FileToUpload.PN_SELECTED);
			xItem.SetNodeValue(FileToUpload.PN_SELECTED, checked == 'true' ? 'false' : 'true');
			 data_UpdateDSItem(dsName, xItem);
		}
	}
}

function ui_ChangeAuthorship(id, isauthorship, dsName)
{
	this.base = UI.RenderableObject;	
	this.id = id;
	this.isauthorship = isauthorship;
	this.dsName = dsName;
}
ui_ChangeAuthorship.prototype = new UI.RenderableObject;
ui_ChangeAuthorship.prototype.constructor = ui_ChangeAuthorship;
ui_ChangeAuthorship.prototype.Render = function()
{	
	var imgPath = this.isauthorship == "true" ? "icon_check.gif" : "icon_check_grey.gif"; 
	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "'	onclick='ui_ChangeAuthorship.Change(\""+ this.dsName + "\",\"" + this.id +"\"); return false'>";
	this.SetObjectInnerHtml(html);
}
ui_ChangeAuthorship.Change = function(dsName, id) {
	
	var ds = data_GetDataset(dsName);
	if (ds) {
		var xItem = ds.Get(id);
		if (xItem) {
			var isauthorship = xItem.GetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISAUTHORSHIP);
			var flag = isauthorship == 'true' ? 'false' : 'true';
			xItem.SetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISAUTHORSHIP, flag);
			if (flag == 'false')
				xItem.SetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISOWNER, flag);
			 data_UpdateDSItem(dsName, xItem);
		}
	}
}

function ui_ChangeOwner(id, isowner, dsName)
{
	this.base = UI.RenderableObject;	
	this.id = id;
	this.isowner = isowner;
	this.dsName = dsName;
}
ui_ChangeOwner.prototype = new UI.RenderableObject;
ui_ChangeOwner.prototype.constructor = ui_ChangeOwner;
ui_ChangeOwner.prototype.Render = function()
{	
	var imgPath = this.isowner == "true" ? "icon_check.gif" : "icon_check_grey.gif"; 
	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "'	onclick='ui_ChangeOwner.Change(\""+ this.dsName + "\",\"" + this.id +"\"); return false'>";
	this.SetObjectInnerHtml(html);
}
ui_ChangeOwner.Change = function(dsName, id) {
	
	var ds = data_GetDataset(dsName);
	if (ds) {
		var xItem = ds.Get(id);
		if (xItem) {
			var isowner = xItem.GetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISOWNER);
			var flag = isowner == 'true' ? 'false' : 'true';
			xItem.SetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISOWNER, flag);
			if (flag == 'true')
				xItem.SetNodeValue(SecurityPrincipalAssignmentsItem.PN_ISAUTHORSHIP, flag);
			data_UpdateDSItem(dsName, xItem);
		}
	}
}
function ui_ChangeSelection(id, dsName)
{
	this.base = UI.RenderableObject;	
	this.id = id;
	this.ds = data_GetDataset(dsName);
	this.dsName = dsName;
}
ui_ChangeSelection.prototype = new UI.RenderableObject;
ui_ChangeSelection.prototype.constructor = ui_ChangeSelection;
ui_ChangeSelection.prototype.Render = function()
{	
	var isselected = false;
	if(this.ds != null)
	{
		var xItem = this.ds.Get(this.id);
		isselected = xItem.IsSelected();
	}
	var imgPath = isselected == true ? "icon_check.gif" : "icon_check_grey.gif"; 
	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "' >";
	this.SetObjectInnerHtml(html);
}

function ui_FileTypeIcon(mstype, bodyType, isEmail)
{
	this.mstype = mstype;
	this.bodyType = bodyType;
	this.isEmail = isEmail=='true';
}

ui_FileTypeIcon.prototype = new UI.RenderableObject;
ui_FileTypeIcon.prototype.constructor = ui_FileTypeIcon;

ui_FileTypeIcon.prototype.Render = function()
{
	var html = "&nbsp;";
	
	if (this.mstype == MT_DOCUMENT)	{
		var bType = this.isEmail?".msg":this.bodyType;
		var imagePath = GetIconFileName(bType);		
		if (imagePath.length > 0)
			html = "<img src='" + imagePath +"' />&nbsp;";
	}	
	this.SetObjectInnerHtml(html); 
}

function ui_ManuallyAddedIcon(isManuallyAdded)
{
	this.isManuallyAdded = isManuallyAdded=='true';
}
ui_ManuallyAddedIcon.prototype = new UI.RenderableObject;
ui_ManuallyAddedIcon.prototype.constructor = ui_ManuallyAddedIcon;
ui_ManuallyAddedIcon.prototype.Render = function()
{
	var html = "&nbsp;";
	if (this.isManuallyAdded)	{
		var imagePath = cmn_GetImageUrl("add_small.gif");		
		if (imagePath.length > 0)
			html = "<img src='" + imagePath +"' />";
	}	
	this.SetObjectInnerHtml(html); 
}

function ui_NewsletterCommentIcon(isCommentPresent, msgId)
{
	this.isCommentPresent = isCommentPresent=='true';
	this.msgId = msgId;
}
ui_NewsletterCommentIcon.prototype = new UI.RenderableObject;
ui_NewsletterCommentIcon.prototype.constructor = ui_NewsletterCommentIcon;
ui_NewsletterCommentIcon.prototype.Render = function()
{
	var html = "&nbsp;";
	
	//try to load from DS
	var isHeadlinesView = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState();	
	var dsName = isHeadlinesView ? "Subscriptions.Latest" : "Subscriptions.LatestS";	
	var ds = data_GetDataset(dsName);
		if(ds!=null)
		{
			var oItem = ds.Get(this.msgId);
			this.isCommentPresent = oItem.GetNodeValue(MessageItem.PN_IS_COMMENT_PRESENT)=='true';
		}
	var display = this.isCommentPresent ? "visible" : "hidden";	
		var imagePath = cmn_GetImageUrl("icons_16x16_discussions.gif");		
		if (imagePath.length > 0)
		html = "<img style='visibility:" +display+ ";' src='" + imagePath +"' id='"+MessageItem.PN_IS_COMMENT_PRESENT+this.msgId+"' />";
	this.SetObjectInnerHtml(html); 
}

function ui_EventTypeIcon(evgroup, evsbgroup)
{
	this.evgroup = evgroup;
	this.evsbgroup = evsbgroup;
}

ui_EventTypeIcon.prototype = new UI.RenderableObject;
ui_EventTypeIcon.prototype.constructor = ui_EventTypeIcon;
ui_EventTypeIcon.prototype.Render = function()
{
	var html = "&nbsp;";
	var imagePath = GetIconForEventGroup(this.evgroup, this.evsbgroup);		
	if (imagePath.length > 0) {
		html = "<img src='" + imagePath +"' />&nbsp;";
	} else {
		html = "<span class='evtType'></span>";
	}
	this.SetObjectInnerHtml(html); 
}

function ui_EventFullTime(startDate, endDate)
{
	this.startDate = new Date(Date.parse(startDate));
	this.endDate = new Date(Date.parse(endDate));
}
ui_EventFullTime.prototype = new UI.RenderableObject;
ui_EventFullTime.prototype.constructor = ui_EventFullTime;
ui_EventFullTime.prototype.Render = function()
{
	var html = "<div class=\"event-datetime\">~0</div>";
	var tmp = "";
	if (this.startDate.getDate() == this.endDate.getDate() && 
		this.startDate.getMonth() == this.endDate.getMonth() && 
		this.startDate.getFullYear() == this.endDate.getFullYear())
	{
		tmp = "<strong>~0</strong><br>~1 - ~2".format(this.startDate.ToString("dddd, MMM dd, yyyy"), this.startDate.ToString(GeneralPreferences.TimeFormatExpression||"hh:mm tt"), this.endDate.ToString(GeneralPreferences.TimeFormatExpression||"hh:mm tt"))
	}
	else
	{
		tmp = "<strong>~0 - ~1</strong><br>".format(this.startDate.ToString("dd, MMM, yyyy"), this.endDate.ToString("dd, MMM, yyyy"));
	}

	html = html.format(tmp);
	this.SetObjectInnerHtml(html); 
}

//folder
function ui_ContainerProperties(folderid, isShared, isowner, contType)
{
	this.folderid = folderid;
	this.isShared = eval(isShared);
	this.isowner = eval(isowner);
	this.contType = contType;
}

ui_ContainerProperties.prototype = new UI.RenderableObject;
ui_ContainerProperties.prototype.constructor = ui_ContainerProperties;
ui_ContainerProperties.prototype.Render = function()
{
	if (this.isowner == false) return;
	var html = "<a href='#' onclick=\"do_modifyContainer('"+this.folderid+"','"+this.contType+"')\">Properties</a>";
	if (this.isShared == true)
			html += " (shared)";
	this.SetObjectInnerHtml(html); 
}
function ui_Paging(moduleName, pageSize, pageNumber, hasNextPage, showPagingAlways)
{
	this.moduleName = moduleName;
	this.pageSize = parseInt(pageSize);
	this.pageNumber = parseInt(pageNumber);
	this.hasNextPage = hasNextPage;
	this.showPagingAlways = showPagingAlways;
	var modulePrefs = ModulesPreferencesStorage.getModulePreferences(this.moduleName, null);
	
	if (modulePrefs) {
		this.maxPageNumber = modulePrefs.getMaxPageNumber();
		if (this.maxPageNumber) {
			this.maxPageNumber = parseInt(this.maxPageNumber);
		} 
	}
	
	if (!this.maxPageNumber) {
		this.maxPageNumber = this.pageNumber;
	}	
	this.pageRange = 10;
	this.previousLinkText = "Previous";
	this.nextLinkText = "Next";
}

ui_Paging.prototype = new UI.RenderableObject;
ui_Paging.prototype.constructor = ui_Paging;

ui_Paging.prototype.Render = function() {
	var html = "";
	if (!(this.pageNumber == 1 && this.hasNextPage == "false") || this.showPagingAlways == "true") {
		var pageMonitoringCall = "Utils.MonitoringHelper.SetMonitoringInfo(MA_ChangeDataPage);";
		html += this.getSpanHTML("Pages: ", true);

		var firstPageNumber = Math.max(1, this.maxPageNumber - (this.pageRange - 1));
		var decreaseMaxPageNumber = this.pageNumber == firstPageNumber;
		
		html += this.pageNumber == 1 ? this.getSpanHTML(this.previousLinkText, true) 
			: this.getSpanHTML(UIObjects.getLinkHTML(this.previousLinkText, 
			pageMonitoringCall + "nav_ChangeModuleSettingsBatch('~0', { PageNumber: ~1, MaxPageNumber: ~2 });".format(
						 this.moduleName, this.pageNumber-1,
						 decreaseMaxPageNumber ? this.maxPageNumber - 1 : this.maxPageNumber)), false, true);
			
		var linksContent = "";
		
		for (var i=firstPageNumber; i<=this.maxPageNumber; i++) {			
			linksContent += i == this.pageNumber ? this.getSpanHTML(" "+i+" ") 
				: UIObjects.getLinkHTML(i, "nav_ChangeModuleSettings('" +this.moduleName+"', 'PageNumber', " + i + ");", false, "p01");
		}
		
		html += linksContent;
		html += this.getSpanHTML(" - ", false);	
		
		// We always set HasNextPage to false originally so that disable Next link. We don't know whether there is next page during first rendering phase.
		// This setting 'HasNextPage' will be overridden on actual data parsing rendering phase.
		var linkHTML = UIObjects.getLinkHTML(this.nextLinkText, pageMonitoringCall + "nav_ChangeModuleSettingsBatch('" +this.moduleName+"', { HasNextPage: false, PageNumber : " + (this.pageNumber + 1) + " });");
		html += this.hasNextPage == "true" ? this.getSpanHTML(linkHTML, false, true)
							: this.getSpanHTML(this.nextLinkText, true);
	}
	this.SetObjectInnerHtml(html);
}

ui_Paging.prototype.getSpanHTML = function(text, disabled, setHTML) {

	var oSpan = DOMObjectFactory.CreateTempDOMObject("span");
	oSpan.applyClass(disabled ? "p02" : "p01");	
	if (setHTML) {
		oSpan.Obj().innerHTML = text;
	} else {
	  oSpan.setInnerText(text);
	}
	return oSpan.getOuterHTML();	
}

function ui_ShowExtraItems(hasNextPage, popupId)
{	
	this.popupId = popupId;
	this.hasNextPage = hasNextPage;
}

ui_ShowExtraItems.prototype = new UI.RenderableObject;
ui_ShowExtraItems.prototype.constructor = ui_ShowExtraItems;

ui_ShowExtraItems.prototype.Render = function() 
{
	var html = "";
	if (this.hasNextPage == "true")
	{
		var action = "";
		if (!str_IsStringEmpty(this.popupId))
			action = "ui_ShowExtraItems.ShowItems('~0', this); return false;".format(this.popupId);
		html = UIObjects.getLinkHTML("more ...", action, null, "lmodule-more");
	}
	this.SetObjectInnerHtml(html);
}

ui_ShowExtraItems.ShowItems = function(popupId, obj) 
{
	var popup = UI.Popuparea.Find(popupId);
	var wsModule = popup.ContentCtrl.firstChild.tpl_dynamicElement;
	wsModule.ChangeDisplay(true);	
	wsModule.OnDisplayChange(true);
	var options = new UI.PopupareaOptions(obj);
	options.objVAlignment = UI.VAlignment.Center;
	options.objHAlignment = UI.HAlignment.Right;
	options.vAlignment = UI.VAlignment.Center;
	options.hAlignment = UI.HAlignment.Right;
	popup.showPopupFromObject(options);	
}

function ui_PagingControl(moduleName, itemCount, pageSize, pageNumber, hasNextPage, totalItemCount)
{
	this.moduleName = moduleName;
	this.itemCount = parseInt(itemCount);
	this.pageSize = parseInt(pageSize);	
	this.pageNumber = parseInt(pageNumber);
	this.hasNextPage = hasNextPage;
	this.totalItemCount = parseInt(totalItemCount);
	
	this.previousLinkText = "Prev";
	this.nextLinkText = "Next";
}

ui_PagingControl.prototype.Render = function() {
	var pageMonitoringCall = "Utils.MonitoringHelper.SetMonitoringInfo(MA_ChangeDataPage);";
	var sb = new Utils.StringBuilder();
	
		sb.Append(this.pageNumber == 1 || isNaN(this.pageNumber)? this.getSpanHTML(this.previousLinkText, true, false, true) + " " 
			: this.getSpanHTML(UIObjects.getLinkHTML(this.previousLinkText, 
					pageMonitoringCall + "nav_ChangeModuleSettingsBatch('~0', { PageNumber: ~1 });".format(
						 this.moduleName, this.pageNumber-1)) + "&nbsp;", false, true, true));

		var minNumber = (this.pageNumber - 1) * this.pageSize + 1;
		var	maxNumber = minNumber + this.itemCount - 1;
		minNumber = Math.min(minNumber, maxNumber);
		
		if (isNaN(minNumber) || isNaN(maxNumber)) {
			minNumber = maxNumber = 0;
		}
		
		sb.Append(this.getSpanHTML(minNumber +"-" + maxNumber, true, false));
		
		// We have to set HasNextPage to false originally so that disable Next link. We don't know whether there is next page during first rendering phase.
		// This setting 'HasNextPage' will be overridden on actual data parsing rendering phase.
		var linkHTML = UIObjects.getLinkHTML(this.nextLinkText, pageMonitoringCall + "nav_ChangeModuleSettingsBatch('" + this.moduleName 
		+ "', { HasNextPage: false, PageNumber : ~0 }".format(this.pageNumber + 1)  + ");");
		sb.Append(" " + (this.hasNextPage == "true" ? this.getSpanHTML(linkHTML, false, true)
							: this.getSpanHTML(this.nextLinkText, true)));

		if(this.totalItemCount>0)							
			sb.Append(this.getSpanHTML(" (total "+this.totalItemCount+")", true, false));

	return sb.ToString();
}

ui_PagingControl.prototype.getSpanHTML = function(text, disabled, setHTML, first) {

	var oSpan = DOMObjectFactory.CreateTempDOMObject("span");
	if (first) {
		oSpan.applyClass("pgOfst");
	}
	if (setHTML) {
		oSpan.Obj().innerHTML = text;
	} else {
	  oSpan.setInnerText(text);
	}
	return oSpan.getOuterHTML();	
}

function ui_PagingControlNSArchive(itemCount, pageSize, pageNumber, hasNextPage, totalCount)
{
	this.itemCount = parseInt(itemCount);
	this.pageSize = parseInt(pageSize);	
	this.pageNumber = parseInt(pageNumber);
	this.hasNextPage = hasNextPage;
	this.totalCount = totalCount;
	
	this.previousLinkText = "Prev";
	this.nextLinkText = "Next";
}
ui_PagingControlNSArchive.prototype.Render = function() 
{
	var sb = new Utils.StringBuilder();	
	sb.Append(this.pageNumber == 1 || isNaN(this.pageNumber)? 
		this.getSpanHTML(this.previousLinkText, false) + " " : 
		this.getSpanHTML(this.getAnchorHTML(this.previousLinkText + " ", "nav_ChangeNSArchiveSetting(~0);".format(this.pageNumber-1)), true)
	);

	var minNumber = (this.pageNumber - 1) * this.pageSize + 1;
	var	maxNumber = minNumber + this.itemCount - 1;
	minNumber = Math.min(minNumber, maxNumber);
		
	if (isNaN(minNumber) || isNaN(maxNumber))
		minNumber = maxNumber = 0;		
	sb.Append(this.getSpanHTML(minNumber +"-" + maxNumber, false));
	sb.Append(" ");
	
	sb.Append(this.hasNextPage ? 
		this.getSpanHTML(this.getAnchorHTML(this.nextLinkText, "nav_ChangeNSArchiveSetting(~0);".format(this.pageNumber + 1)), true) : 
		this.getSpanHTML(this.nextLinkText, false)
	);
	
	if(this.totalCount)
		sb.Append(" (total ~0)".format(this.totalCount));
	return sb.ToString();
}
ui_PagingControlNSArchive.prototype.getSpanHTML = function(text, setHTML) {

	var oSpan = DOMObjectFactory.CreateTempDOMObject("span");
	if (setHTML)
		oSpan.Obj().innerHTML = text;
	else
	  oSpan.setInnerText(text);
	  
	return oSpan.getOuterHTML();	
}
ui_PagingControlNSArchive.prototype.getAnchorHTML = function(text, action)  {
	var oAnchor = DOMObjectFactory.CreateTempDOMObject("a");
	oAnchor.setInnerText(text);
	oAnchor.Obj().href = "javascript:void(0);";	
	
	if (action)
		oAnchor.Obj().setAttribute("onclick",  action);
	return oAnchor.getOuterHTML();	
}



UIObjects.getLinkHTML = function(text, actionString, setHTML, cssClass, tooltip) {

	var oLink = DOMObjectFactory.CreateTempDOMObject("a");
	oLink.setAttribute("href", "javascript:void(0);");
	if (cssClass)
		oLink.setAttribute("class", cssClass);
	oLink.setAttribute("onclick", actionString);
	if (setHTML) {
		oLink.Obj().innerHTML = text;		
	}
	else {
		oLink.setInnerText(text);
	}
	if (tooltip)
		oLink.setAttribute("title",tooltip);
	return oLink.getOuterHTML();	
}

function ui_FoldersPopup(containerid)
{	
	this.base = UI.RenderableObject;
	this.containerid = containerid;		
	var thisObj = this;
	
	this.click = function()
	{
		var bPos = dom_findXY(event.srcElement);		
		var lpos = bPos.x + event.srcElement.clientWidth
		var tpos = bPos.y + event.srcElement.clientHeight;
		var options = new UI.PopupareaOptions(thisObj.obj);
		options.hideTimeout = 500;
		tree_GetNavigationTree().Show(options, thisObj.containerid);
		tree_GetNavigationTree().popup.DeleteTimeout();		
	}
	this.mouseout = function()
	{		
		tree_GetNavigationTree().popup.SetHideTimeout(500);
	}
}
ui_FoldersPopup.prototype = new UI.RenderableObject;
ui_FoldersPopup.prototype.constructor = ui_FoldersPopup;
ui_FoldersPopup.prototype.Render=function()
{
	this.SetObjectInnerHtml("");
	this.obj.className = "fd01";
	// TO DO: Viacheslav Kopichev (Memory leak problem)
	dom_attachEventForObject(this.obj, "click", this.click)
	dom_attachEventForObject(this.obj, "mouseout", this.mouseout)
}

function ui_AttachmentItem(id, name, contentType)
{
	this.id = id;
	this.base = UI.RenderableObject;	
	this.name = name;
	this.contentType = contentType;
}

ui_AttachmentItem.prototype = new UI.RenderableObject;
ui_AttachmentItem.prototype.constructor = ui_AttachmentItem;

ui_AttachmentItem.prototype.Render = function()
{
	var html = '';
	var imagePath = GetIconFileName("." + ContentType.GetExtByMime(this.contentType));	
	if (imagePath.length > 0)
			html += "<img style='vertical-align:middle' src='" + imagePath +"' />&nbsp;";
	html += "<a href='javascript:void(0);'" +
	" onclick = 'do_showDocument(\"" + this.id+ "\", MT_DOCUMENT,null,null,\"attachment\");return cmn_cancelEvent(event);' >" + cmn_htmlEncode(this.name) + "</a>";
	this.SetObjectInnerHtml(html); 
}

DeclareClass("UI.SetAdmin", "UI.RenderableObject",
{
	constructor : function(groupId, groupType, userId, type, isAdmin)
	{
		this.__groupId = groupId;
		this.__groupType = groupType;
		this.__userId = userId;
		this.__isAdmin = ( typeof(isAdmin) == "string" && isAdmin != null && isAdmin.toLowerCase() == 'true' );
		this.__disabled = ( type != "User" );
	}
	,OnClick : function()
	{
		if ( this.__disabled ) return;
		new httpcmd_SetAdmin(this.__groupId, this.__groupType, this.__userId, !this.__isAdmin, this.CreateCallback(this.OnRightsChange));
	}
	,OnRightsChange : function(dsName, userId, txt, isMyRights)
	{
		if (isMyRights)
		{
			window.TopWindow.nav_NavigateTo(PID_MYACCOUNT);
			window.TopWindow.location.reload();
		}
	}
	,Render : function()
	{
		var imgPath = this.__isAdmin ? "icon_check.gif" : "icon_check_grey.gif"; 
		var img = document.createElement('img');
		img.src = cmn_GetImageUrl(imgPath);
		dom_attachEventForObject(img, "click", this.CreateCallback(this.OnClick));
		this.SetObjectInnerHtml("");
		this.obj.appendChild(img);	
	}
});
//ui_SPProperties
function ui_SPProperties(id, type)
{
	this.base = UI.RenderableObject;
	this.spId = id;
	this.type = type;
	this.disabled = ( type != "User" );
	
	var thisObj = this;	
	
	this.onClick = function()
	{
		if ( thisObj.disabled ) return;
		do_showPrincipalProperties(thisObj.spId,thisObj.type);
		window.event.cancelBubble = true;

	}
}
ui_SPProperties.prototype = new UI.RenderableObject;
ui_SPProperties.prototype.constructor = ui_SPProperties;
ui_SPProperties.prototype.Render=function()
{
	var lnk = null;
	if ( !this.disabled )
	{
		lnk = document.createElement('a');
		lnk.href = "#";
		lnk.innerText = "View";
		dom_attachEventForObject(lnk, "click", this.onClick);
	}
	this.SetObjectInnerHtml("");
	if ( lnk )
		this.obj.appendChild(lnk);	
}

function ui_PostedInfo(postedTime, category)
{
	this.postedTime = postedTime;
	this.category = category;
}

ui_PostedInfo.prototype = new UI.RenderableObject;
ui_PostedInfo.prototype.constructor = ui_PostedInfo;

ui_PostedInfo.prototype.Render = function() {
	var html = "";
	if (!str_IsStringEmpty(this.category))
		html = "Posted ~0 To ~1".format(this.postedTime, this.category);
	else
		html = "Posted ~0".format(this.postedTime);
	this.SetObjectInnerHtml(html); 
}

function ui_BlogPostCategory(category)
{
	this.category = category;
}
ui_BlogPostCategory.prototype = new UI.RenderableObject;
ui_BlogPostCategory.prototype.constructor = ui_BlogPostCategory;
ui_BlogPostCategory.prototype.Render = function() 
{
	var html = ' - ';
	if (!str_IsStringEmpty(this.category ))
		html = "In "+this.category;
	this.SetObjectInnerHtml(html); 
}


function ui_BlogPostAttachments(xml)
{
	this.xml = xml;
}

ui_BlogPostAttachments.prototype = new UI.RenderableObject;
ui_BlogPostAttachments.prototype.constructor = ui_BlogPostAttachments;

ui_BlogPostAttachments.prototype.Render = function() {

	var xmlDoc = new Xml.NodeAccessor(this.xml);	
	var html = "Attachments: ";
	var renderedItems = [];
	var items = xmlDoc.SelectNodes("//"+ AttachmentItem.ItemName);
	var span = DOMObjectFactory.CreateTempElement("span");
	
	for (var i=0; i<items.length; i++) {
		
		var id = items[i].selectSingleNode(AttachmentItem.PN_ID).text;
		var contentType = items[i].selectSingleNode(AttachmentItem.PN_CONTENTTYPE).text;
		var name = items[i].selectSingleNode(AttachmentItem.PN_NAME).text;		

		var item = new ui_AttachmentItem(id, name, contentType);
		item.obj = span;
		item.Render();
		renderedItems.push(item.obj.innerHTML);		
	}
	
	if (renderedItems.length > 0)	
		html += renderedItems.join(", ");
	
	this.SetObjectInnerHtml(html); 
}

function ui_CommentHeaderLink(id, title, isauthor, date)
{
	this.id = id;
	this.base = UI.RenderableObject;	
	this.title = title;
	this.isauthor = isauthor == "true";
	this.date = date;
}

ui_CommentHeaderLink.prototype = new UI.RenderableObject;
ui_CommentHeaderLink.prototype.constructor = ui_CommentHeaderLink;

ui_CommentHeaderLink.prototype.Render = function()
{
	this.obj.className = "blogs-author";
	var html = this.GetAuthorHtml();
	html += "<b>&nbsp;wrote on&nbsp;" + this.date + "</b>";
	this.SetObjectInnerHtml(html); 
}
ui_CommentHeaderLink.prototype.GetAuthorHtml = function()
{
	var html = '';
	if (this.isauthor)
		html += "<B>[Author]</B>&nbsp;";
	var obj = DOMObjectFactory.CreateElement("span");
	var uiObj = new ui_UserBlogAuthorLink(this.id, this.title, "Internal", "");
	uiObj.SetObject(obj);
	uiObj.Render();
	html += obj.innerHTML;
	return html;
}

function ui_CommentBody(body, isauthor)
{
	this.base = UI.RenderableObject;	
	this.body = body;
	this.isauthor = isauthor == "true";
}

ui_CommentBody.prototype = new UI.RenderableObject;
ui_CommentBody.prototype.constructor = ui_CommentBody;

ui_CommentBody.prototype.Render = function()
{
	var html = '';
	if (this.isauthor)
		html += "<DIV style='color:#990000;'>"+this.body+"</DIV>";
	else
		html = this.body;
	this.SetObjectInnerHtml(html); 
}

function ui_SetFavoriteAuthor(dsName, userId, isFavorite)
{
	this.base = UI.RenderableObject;
	this.dsName = dsName;
	this.userId = userId;
	this.isFavorite = isFavorite.toLowerCase();
}
ui_SetFavoriteAuthor.prototype = new UI.RenderableObject;
ui_SetFavoriteAuthor.prototype.constructor = ui_SetFavoriteAuthor;
ui_SetFavoriteAuthor.prototype.Render=function()
{
	var script = "";

	imgPath = this.isFavorite == "true" ? "icon_check.gif" : "icon_check_grey.gif";
	script = "new httpcmd_SetFavoriteAuthor(\"" + this.dsName + "\",\"" +this.userId + "\"," + (this.isFavorite == "true" ? "false" : "true")+ "); return false; ";

	var html = "<img src='" + cmn_GetImageUrl(imgPath) + "'	onclick='"+script+"'>";

	this.SetObjectInnerHtml(html);
}

function GetIconFileName(bodyType) {	
	
	var fileName = '';
	
	 switch(bodyType.toLowerCase()){
		case '.doc':
		case '.docx':
		case '.rtf': fileName = 'doc.gif';	break;
		case '.ppt': fileName = 'ppt.gif';	break;
		case '.msg': fileName = 'msmsg.gif';break;
		case '.zip': fileName = 'zip.gif';	break;
		case '.pdf': fileName = 'pdf.gif';	break;
		//case '.txt': fileName = 'txt.gif';	break;
		case '.png': fileName = 'png.gif';	break;
		case '.jpg': fileName = 'jpg.gif';	break;
		case '.html':
		case '.htm': fileName = 'htm.gif';	break;
		case '.xlsx':
		case '.xls': fileName = 'xls.gif';	break;
		case '.gif': fileName = 'gif.gif';	break;		
		case '.mp3':
		case '.wav': fileName = 'wav.gif';	break;		
	} 
	return fileName.length > 0 ? cmn_GetImageUrl("FileIcon/"+fileName) : '';
}

 var ContentType = {
	
	Mime : {
		XML		: "text/xml",
		HTML	: "text/html",
		RTF		: "text/rtf",
		TXTPLAIN: "text/plain",
		GIF		: "image/gif",
		JPG		: "image/pjpeg",
		JPEG	: "image/jpeg",
		PNG		: "image/png",
		PDF		: "application/pdf",
		MSG		: "application/msoutlook",
		MSWORD	: "application/msword",
		MSEXCEL	: "application/vnd.ms-excel",
		ARJ		: "application/x-arj-compressed",
		LHA		: "application/x-lha-compressed",
		ZIP		: "application/x-zip-compressed",
		RAR		: "application/x-rar-compressed" },
		
	GetExtByMime	: function(type) {
		switch( type )
		{
			case this.Mime.PDF:
				return "PDF";
			case this.Mime.HTML:
				return "HTML";
			case this.Mime.MHTML:
				return "HTML";
			case this.Mime.RTF:
				return "RTF";
			case this.Mime.TXTPLAIN:
				return "TXT";
			case this.Mime.GIF:
				return "GIF";
			case this.Mime.JPG:
			case this.Mime.JPEG:
				return "JPG";
			case this.Mime.PNG:
				return "PNG";
			case this.Mime.MSWORD:
				return "DOC";
			case this.Mime.MSEXCEL:
				return "XLS";
			case this.Mime.ARJ:
			case this.Mime.LHA:
			case this.Mime.ZIP:
			case this.Mime.RAR:
				return "ZIP";
			case this.Mime.MSG:
				return "MSG";	
		}
		return "Unknown";
	}
 }		
		
 function GetIconForEventGroup(evGroup, evSubGroup) 
 {	
	var fileName = '';
	var sgInfo = GetEventSubTypeInfo(evGroup, evSubGroup);
	if (sgInfo != null)
		fileName = sgInfo.imagePath;
	return fileName.length > 0 ? cmn_GetImageUrl("EventTypesIcon/"+fileName) : '';
 }	
function GetEventSubTypeInfo(evGroup, evSubGroup)	
{
	for(var i=0; i < TPEventGroupCache.length; i++)
	{
		if (!str_IsStringEmpty(evGroup) && TPEventGroupCache[i].code != evGroup)
			continue;
		for(var j=0; j < TPEventGroupCache[i].subgroups.length; j++)
			if (TPEventGroupCache[i].subgroups[j].code == evSubGroup)
				return TPEventGroupCache[i].subgroups[j];
	}
	return null;
}
ui_MyBloggingActivityActions.Inherits(UI.RenderableObject);
function ui_MyBloggingActivityActions(msgID, containerID, msgType)
{
	this.msgID = msgID;
	this.containerID = containerID;
	this.msgType = msgType;
	
	this.Render = function()
	{
		var obj = this.obj;
		this.cntrl = UI.Control.LoadControl("UI.Controls.MyBloggingActivityActions",obj);
		this.cntrl.SetMsgID(this.msgID);
		this.cntrl.SetContainerID(this.containerID);
		this.cntrl.SetMsgType(this.msgType);
		this.cntrl.ProcessRequest();
	}
	this.Dispose = function()
	{
		this.cntrl.Dispose();
	}
}
function ui_MyBloggingActivityTools(msgId, cntId, msgType)
{
	this.msgId = msgId;
	this.cntId = cntId;
	this.msgType = msgType;
}

ui_MyBloggingActivityTools.prototype = new UI.RenderableObject;
ui_MyBloggingActivityTools.prototype.constructor = ui_MyBloggingActivityTools;

ui_MyBloggingActivityTools.prototype.Render = function() {
	var html = ""
	var deleteScript = "do_deleteMessage(\"" + this.msgId +"\",\""+ this.cntId +"\");";
	if (this.msgType != MT_COMMENT)	
	{
		var editScript = "do_EditBlogPost(~0)".format(this.msgId);
		html = UIObjects.getLinkHTML("Edit",editScript)+"-";
	}
	html += UIObjects.getLinkHTML("Delete", deleteScript);	
	this.SetObjectInnerHtml(html);
}

function ui_BlogPostReference(docid, mstype, title)
{
	this.docid = docid;
	this.mstype = mstype;
	this.title = title;
}
ui_BlogPostReference.prototype = new UI.RenderableObject;
ui_BlogPostReference.prototype.constructor = ui_MyBloggingActivityTools;
ui_BlogPostReference.prototype.Render = function() 
{	
	var html = "Reference";
	if (this.docid > 0)
	{
		var click = "do_showDocument(" + this.docid+ ",\"" + this.mstype + "\"); return cmn_cancelEvent(event);";
		click = click.replace(/"/g,"&quot;");		
		html = "<a href=\"#\" onclick=\"~0\" >Reference</a>".format(click);
	}
	this.SetObjectInnerHtml(html);
}

function ui_MyBloggingActivityTitle(postId, postTitle, msgId, blogPostSubject)
{
	this.postId = postId;	
	this.postTitle = postTitle;
	this.msgId = msgId;
	this.blogPostSubject = blogPostSubject;	
}

ui_MyBloggingActivityTitle.prototype = new UI.RenderableObject;
ui_MyBloggingActivityTitle.prototype.constructor = ui_MyBloggingActivityTitle;

ui_MyBloggingActivityTitle.prototype.Render = function() {
	var html = "";
	var script;
	if (this.postId.isEmpty()) {
		 script = "do_CompleteMessage(" + this.msgId + ");";
	} 
	else {
		html = "[comment] ";
		script = "do_CommentMessage(" + this.postId + ",null," + this.msgId + ");";
	}

	var title = this.postId.isEmpty() ? this.postTitle : this.blogPostSubject;
	
	html += UIObjects.getLinkHTML(title.trim(), script, null, null, title.trim());
	
	
	
	this.SetObjectInnerHtml(html);
}

function ui_BlogPostCommentsCount(count) {
	this.count = count;
}

ui_BlogPostCommentsCount.prototype = new UI.RenderableObject;
ui_BlogPostCommentsCount.prototype.constructor = ui_BlogPostCommentsCount;

ui_BlogPostCommentsCount.prototype.Render = function() {	
	this.SetObjectInnerHtml(this.count > 0 ? this.count : "");
}


/*****/
ui_RelatedCountItem.Inherits(UI.RenderableObject);

function ui_RelatedCountItem(title,clusterID,relatedcount,className,clusterName,pid,urlparams) {
	this.relatedcount = relatedcount;
	this.title = title;
	this.clusterID = clusterID;
	this.className = className;
	this.clusterName = clusterName;
	this.pid = pid;
	this.urlparams = urlparams;
}
ui_RelatedCountItem.prototype.Render = function() {
	var relCount = "";
	var html = "";
	try{
		relCount = new ui_ClusterLinkText(this.title, this.clusterID, this.relatedcount, this.clusterName, this.pid, this.urlparams).GetLink(this.title,"","","",false,true);
	}catch(e){relCount="";}
	
	if (!str_IsStringEmpty(relCount)){
		html += "<span class='"+this.className+"'>" + relCount + "</span>"; 
		this.SetObjectInnerHtml(html);
	}
	try 
	{
		if (str_IsStringEmpty(html)) 
		{
			html = "";
			var obj = this.obj.parentElement;
			if (obj.previousSibling && obj.previousSibling.getAttribute("sep") == "1") 
			{
				//TO DO: VK memory leak problem
				dom_RemoveNode(obj.previousSibling, true);
			}
			else if (obj.nextSibling && obj.nextSibling.getAttribute("sep") == "1") 
			{
				//TO DO: VK memory leak problem
				dom_RemoveNode(obj.nextSibling, true);
			}
		} 
	}
	catch(e) {}
}

/*****/

ui_ManageablePanelFooter.Inherits(UI.RenderableObject);

function ui_ManageablePanelFooter(isCollapsed, title, action)
{
	this.isCollapsed = isCollapsed;
	this.title = title;
	this.action = action;
}

ui_ManageablePanelFooter.prototype.Render = function()
{
	html = "";	
	if (this.isCollapsed != "true")
	{
		var linkHTML = "~0".format(UIObjects.getLinkHTML(this.title, this.action));
		html = "<span class='summary-link' style='padding: 0;'>~0</span>".format(linkHTML);		
	}	
	this.SetObjectInnerHtml(html);	
}

ui_HeadlinesMetaInfoColumn.Inherits(UI.RenderableObject);

function ui_HeadlinesMetaInfoColumn(metaData,className,isActive)
{
	this.metaData = metaData;
	this.className = className;
	this.isActive = isActive == "false" ? false : true;
}
ui_HeadlinesMetaInfoColumn.prototype.Render = function()
{
	this.SetObjectInnerHtml(this.GetHTML());
}
ui_HeadlinesMetaInfoColumn.prototype.GetHTML = function()
{
	var html = "";
	if (!str_IsStringEmpty(this.metaData))
	{
		var xmlDoc = new Xml.NodeAccessor(this.metaData);
		var nodes = xmlDoc.SelectNodes("//~0[~1='~2']".format(CompanyTagItem.ItemName, CompanyTagItem.PN_TAGNAME, "PrimaryCompany"));
		if (nodes != null && nodes.length > 0)
		{
			var leng = nodes.length < 1? nodes.length : 1;
			for( var i=0; i < leng; i++)
			{
				var nodeDoc = new Xml.NodeAccessor(nodes[i]);
				if (!str_IsStringEmpty(html))
					html += ", ";
				if (this.isActive)
					html += this.GetLinkHTML(SRCH_TN_SYMBOL, nodeDoc.GetNodeValue(CompanyTagItem.PN_ID), nodeDoc.GetNodeValue(CompanyTagItem.PN_SYMBOL), nodeDoc.GetNodeValue(CompanyTagItem.PN_NAME));
				else
					html += this.GetTextHTML(SRCH_TN_SYMBOL, nodeDoc.GetNodeValue(CompanyTagItem.PN_ID), nodeDoc.GetNodeValue(CompanyTagItem.PN_SYMBOL), nodeDoc.GetNodeValue(CompanyTagItem.PN_NAME));
			}
			html = "<span class='tc01'>~0</span>".format(html);
		}
	}
	return html;
}
ui_HeadlinesMetaInfoColumn.prototype.GetTextHTML = function(name, val, dispval, title)
{
	var domObj = DOMObjectFactory.CreateTempDOMObject("span");
	domObj.applyClass(this.className);
	domObj.setInnerText( dispval );
	domObj.setAttribute("title", title );
	return domObj.getOuterHTML();
}
ui_HeadlinesMetaInfoColumn.prototype.GetLinkHTML = function(name, val, dispval, title)
{
	var action = "do_inpDoSearchByFilter('~0','~1','~2', true); return false".format(name.replace(/\'/ig,"\\\'"), val.replace(/\'/ig,"\\\'"), dispval.replace(/\'/ig,"\\\'"));
	var domObj = DOMObjectFactory.CreateTempDOMObject("a");
	domObj.applyClass(this.className);
	domObj.setInnerText( dispval );
	domObj.setAttribute("href", "#" );
	domObj.setAttribute("onclick", action );
	domObj.setAttribute("title", title );
	return domObj.getOuterHTML();
}

ui_SynopsisMetaInfoColumn.Inherits(ui_HeadlinesMetaInfoColumn);

function ui_SynopsisMetaInfoColumn(metaData,className,isActive)
{
	this.metaData = metaData;
	this.className = className;
	this.isActive = isActive == "false" ? false : true;
}
ui_SynopsisMetaInfoColumn.prototype.Render = function()
{
	var html = this.GetHTML();
	try 
	{
		if (str_IsStringEmpty(html)) 
		{
			html = "";
			var obj = this.obj.parentElement;
			if (obj.previousSibling && obj.previousSibling.getAttribute("sep") == "1") 
			{
				//TO DO: VK memory leak problem
				dom_RemoveNode(obj.previousSibling, true);
			}
			else if (obj.nextSibling && obj.nextSibling.getAttribute("sep") == "1") 
			{
				//TO DO: VK memory leak problem
				dom_RemoveNode(obj.nextSibling, true);
			}
		} 
	}
	catch(e) {}
	this.SetObjectInnerHtml(html);
}

ui_UserBlogMetaInfoColumn.Inherits(ui_HeadlinesMetaInfoColumn);

function ui_UserBlogMetaInfoColumn(metaData)
{
	this.metaData = metaData;
}
ui_UserBlogMetaInfoColumn.prototype.Render = function()
{
	var html = this.GetHTML();
	if (!str_IsStringEmpty(html))
		html += " /";
	this.SetObjectInnerHtml(html);
}

ui_HeadLinesSourceInfoColumn.Inherits(UI.RenderableObject);
function ui_HeadLinesSourceInfoColumn(containerID, containerName, containerType, 
	sourceID, sourceName, sourceType)
{
	this.containerID = containerID;
	this.containerName = containerName;
	this.containerType = containerType;
	
	this.sourceID = sourceID;
	this.sourceName = sourceName;
	this.sourceType = sourceType;
	
	this.showContainerLink = true;
	this.containerLink = ui_CreateScriptLinkHtml(containerName, 
	     "event.cancelBubble=true;do_showContainerMessages(\"" + containerID + "\",\"" + cmn_scriptEncodeString(containerName) + "\",\"" + containerType +"\")", 
	     true, containerName);
	
	if (!str_IsStringEmpty(sourceID))
{
		this.showSourceLink = true;
		this.sourceLink = ui_CreateScriptLinkHtml(sourceName, 
	     "event.cancelBubble=true;do_showContainerMessages(\"" + sourceID + "\",\"" + cmn_scriptEncodeString(sourceName) + "\",\"" + sourceType +"\")", 
	     true, sourceName);
	}
	
	this.Render = function()
	{
		var html = "";
		if (this.showContainerLink)
			html += this.containerLink;
		if (this.showSourceLink)
			html += " / " + this.sourceLink;
		this.SetObjectInnerHtml(html);
	}
}

ui_HeadlineAndSource.Inherits(UI.RenderableObject);
function ui_HeadlineAndSource(id, title, type, link, email, containerLink, sourceLink, sourceID) {
	this.id = id;
	this.title = title;
	this.type = type;
	this.link = link;
	this.email = email;
	
	var click = "do_showDocument(~0,\"~1\", \"~2\", ~3)".format(this.id, this.type, cmn_scriptEncodeString(this.link), this.email);

	this.headlineHTML = ui_CreateScriptLinkHtml(this.title, click, this.showTooltip);
	this.sourceLink = sourceLink;
	this.containerLink = containerLink;
	this.showContainerLink = !str_IsStringEmpty(this.containerLink);
	this.showSourceLink = !str_IsStringEmpty(sourceID) && !str_IsStringEmpty(this.sourceLink);	
}

ui_HeadlineAndSource.prototype.Render = function() {
	
	html = "<ui:ttr/><table class='it' cellpadding='0' cellspacing='0' name='tableToResize' >";
	html += "<tr><td class='ellipsis'>";
	html += "<span>~0</span></td>".format(this.headlineHTML);
	html += "<td class='itFixed'><a href='#' class='cluster_relatedcount'>Related 23 items</a></td>";
	html += "<td class='ellipsis'>~0</td>".format(this.getSourceHTML());
	html += "</tr></table>";
	
	this.SetObjectInnerHtml(html);	
};

ui_HeadlineAndSource.prototype.getSourceHTML = function() {
	var html = "";
	if (this.showContainerLink)
		html += this.containerLink;
	if (this.showSourceLink)
		html += " / " + this.sourceLink;
	return html;
}

var headlinesResizeID = null;
function ui_HeadlinesOnResizeStart() {
	window.clearTimeout(headlinesResizeID);
	headlinesResizeID = window.setTimeout(ui_HeadlinesOnResize, 50);
}

function ui_HeadlinesOnResize() {
	StartTimeLog("Headlines onresize", "resize");
	var aMarkers = dom_getElementsByTagNameNS(document,"ui", "ttr");
	for (var i=0; i < aMarkers.length; i++) {
		ui_HeadlinesSetSize(aMarkers[i].nextSibling);
	}
	EndTimeLog();
}

function ui_HeadlinesSetSize(table) {
	var tableWidth = table.offsetWidth;
	var cells = table.rows[0].cells;
	var first = cells[0];
	var contentWidth = first.firstChild.offsetWidth;

	var fixedWidth = cells[1].offsetWidth;
//	var second = cells[2];
	var trailWidth = cells[2].firstChild.offsetWidth;
	
	if (tableWidth > (contentWidth + fixedWidth + trailWidth + 5)) {
		first.style.width = contentWidth + "px";
	} else {
		var width = tableWidth - fixedWidth;
		var trailPercentsWidth = Math.round(width * 0.4);
		if (trailPercentsWidth > trailWidth) {
			first.style.width = Math.round(((width - trailWidth) * 100)/tableWidth) + "%";
		} else {
			if (contentWidth < (width - trailPercentsWidth)) {
				first.style.width = contentWidth + "px";
			} else {
				first.style.width = Math.round((width * 60)/tableWidth) + "%";	
			}
		}			
	}		
}

function getAncestorByTagName(el, tagName) {
	do {  el = el.parentElement; } while (el && el.tagName != tagName) 
	return el;
}

ui_SynopsisSourceInfoColumn.Inherits(UI.RenderableObject);
function ui_SynopsisSourceInfoColumn(sourceID, idField, titleField, typeField)
{
	if (str_IsStringEmpty(sourceID))
		this.sourceLink = null;
	else
		this.sourceLink = ui_CreateScriptLinkHtml(titleField, 
	     "event.cancelBubble=true;do_showContainerMessages(\"" + idField + "\",\"" + cmn_scriptEncodeString(titleField) + "\",\"" + typeField +"\")", 
	     true, titleField  );
		
	this.Render = function()
	{
		var html = "";
		try {
			if (str_IsStringEmpty(this.sourceLink)) {
				var obj = this.obj.parentElement;
				if (obj.previousSibling && obj.previousSibling.getAttribute("sep") == "1") {
					//TO DO: VK memory leak problem
					dom_RemoveNode(obj.previousSibling, true);
				} else
				if (obj.nextSibling && obj.nextSibling.getAttribute("sep") == "1") {
					//TO DO: VK memory leak problem
					dom_RemoveNode(obj.nextSibling, true);
				}
			} 
			else
				html = "Source: " + this.sourceLink;
		}
		catch(e) {}
		this.SetObjectInnerHtml(html);
	}
}

ui_OneDayEventsTime.Inherits(UI.RenderableObject);
function ui_OneDayEventsTime(occurrence, startTime)
{
	this.occurrence = occurrence;
	this.startTime = startTime;
}
ui_OneDayEventsTime.prototype.Render = function()
{
	if (this.occurrence == EventOccurrence.TS)
		this.SetObjectInnerHtml(this.startTime);
}

ui_SearchResultEventsTime.Inherits(UI.RenderableObject);
function ui_SearchResultEventsTime(occurrence, startTime)
{
	this.occurrence = occurrence;
	this.startTime = startTime;
}
ui_SearchResultEventsTime.prototype.Render = function()
{
	var html = "";
	html = new EventTimeFormatter(this.occurrence, null, this.startTime, null).getOccurrence() || this.startTime;
	this.SetObjectInnerHtml(html+"&nbsp;");
}

function ui_EmailItDeleteLink( dsName, id, displayValue )
{
	this.dsName = dsName;
	this.id = id;
	this.displayValue = displayValue;
}
ui_EmailItDeleteLink.prototype = new UI.RenderableObject;
ui_EmailItDeleteLink.prototype.constructor = ui_EmailItDeleteLink;
ui_EmailItDeleteLink.prototype.Render = function()
{
	var span = DOMObjectFactory.CreateElement(UI.HtmlTag.Span);	
	span.innerText = this.displayValue;
	this.SetObjectInnerHtml("");
	this.obj.appendChild(span);	
	dom_attachEventForObject(span, "click", new Function("EmailIt.deletePopup('" +this.dsName+"','" + this.id + "')"));
};

function ui_UserBlogAuthorLink( id, title, type, cssclass )
{
	this.id = id;
	this.title = title;
	this.type = type;
	this.cssclass = cssclass;
}
ui_UserBlogAuthorLink.prototype = new UI.RenderableObject;
ui_UserBlogAuthorLink.prototype.constructor = ui_UserBlogAuthorLink;
ui_UserBlogAuthorLink.prototype.Render = function()
{
	var domObj;
	if (this.type == "Internal")
	{		
		domObj = DOMObjectFactory.CreateTempDOMObject("a");
		domObj.setAttribute("href", "#" );
		domObj.setAttribute("onclick", "do_showUserBlogAuthorMessages(\""+this.id+"\",\"" + cmn_scriptEncodeString(this.title) + "\"); return false;" ); 
	}
	else
		domObj = DOMObjectFactory.CreateTempDOMObject("span");
		
	domObj.setInnerText( this.title );
	domObj.setAttribute("title", this.title );
	domObj.setAttribute("class", this.cssclass );
	this.SetObjectInnerHtml(domObj.getOuterHTML());
};

function EventTimeFormatter(occurrence, startDate, startTime, startDateFormatted) {
	this.occurrence = occurrence;
	this.startDate = new Date(startDate);
	this.startTime = startTime;
	this.startDateFormatted = startDateFormatted;
}

EventTimeFormatter.prototype.getOccurrence = function() {
	var result = null;	
	switch (this.occurrence) {
		case EventOccurrence.BMO:
			result = "BMO";
			break;
		case EventOccurrence.AMC:
			result = "AMC";
			break;
		case EventOccurrence.NTS:
			result = "NTS";
			break;
	}
	return result;	
}

EventTimeFormatter.prototype.getTimeFormatted = function() {

	var start = floorDate(this.startDate);
	var today = floorDate(new Date());
	return (start.toString() == today.toString() ? this.getOccurrence() || this.startTime : this.startDateFormatted);		
}
 
 
function ui_DeletePage(id, canDel)
{
	this.base = UI.RenderableObject;
	this.pageId = id;
	this.disabled = !( typeof(canDel) == "string" && canDel != null && canDel.toLowerCase() == 'true' );
	
	var thisObj = this;	
	
	this.onClick = function()
	{
		if ( thisObj.disabled ) return;
		do_deletePage(thisObj.pageId);
	}
}
ui_DeletePage.prototype = new UI.RenderableObject;
ui_DeletePage.prototype.constructor = ui_DeletePage;
ui_DeletePage.prototype.Render=function()
{
	if ( this.disabled ) return;
	var obj = document.createElement('a');
	obj.href = "#";
	obj.innerText = "x";
	dom_attachEventForObject(obj, "click", this.onClick);
	this.SetObjectInnerHtml("");
	this.obj.appendChild(obj);	
}

function ui_MetaTagItem(title, searchfunction, tagname, val, dispval, tooltip)
{
	this.base = UI.RenderableObject;
	this.title = title;
	this.searchfunction = searchfunction;
	this.tagname = tagname;
	this.val = val;
	this.dispval = dispval;
	this.tooltip = tooltip;
}
ui_MetaTagItem.prototype = new UI.RenderableObject;
ui_MetaTagItem.prototype.constructor = ui_MetaTagItem;
ui_MetaTagItem.prototype.Render=function()
{
	var obj = document.createElement('nobr');
	if (!str_IsStringEmpty(this.searchfunction))
	{
		obj = document.createElement('a');
		obj.href = "#";
		// TO DO: Viacheslav Kopichev (Memory leak problem)
		dom_attachEventForObject(obj, "click", new Function("~0(\"~1\",\"~2\",\"~3\")".format(this.searchfunction,this.tagname,cmn_scriptEncodeString(this.val),cmn_scriptEncodeString(this.dispval))));
	}
	obj.title = this.tooltip;
	obj.innerText = this.dispval;
	this.SetObjectInnerHtml("");
	this.obj.appendChild(obj);	
	if (this.title.length > 45)
	{
		obj.style.width = "295";
		obj.className = "txtover display-inline";
	}
}

ui_NewItem.Inherits(UI.RenderableObject);
function ui_NewItem(unread)
{
	this.unread = unread;
}
ui_NewItem.prototype.Render=function()
{
	var el = this.obj.parentElement;
	while (el && !(el.tagName == "TR" && el.className.indexOf("ih02") != -1)) {
		el = el.parentElement;
	}
	
	if (el) {
		if (this.unread.toLowerCase() == 'true') {	
			
			if (el.className.indexOf("newItm") == -1 ) 
				el.className += " newItm";
				
		} else {
				el.className.replace("newItm", "");
		}	
	}
}



ui_HeadlinesSelectedItem.Inherits(UI.RenderableObject);
function ui_HeadlinesSelectedItem(selected)
{
	this.selected = selected;
}

ui_HeadlinesSelectedItem.prototype.Render=function()
{
	var el = this.obj.parentElement;
	while (el && !(el.tagName == "TR" && (el.className.indexOf("ih02")!=-1 || el.className.indexOf("is02")!=-1))) 
		el = el.parentElement;
	
	if (el) 
	{
		var classNameToSet = el.className.indexOf("ih02")!=-1 ? "ih02_ms" : "is02_ms";
		if (this.selected.toLowerCase() == 'true') 
		{							
			if (el.className.indexOf("_ms") == -1 )
				el.className += " "+classNameToSet;
				
		} 
		else 
		{
				el.className.replace(" "+classNameToSet, "");
		}	
	}
}

ui_HeadlinesSelectedItemCheckbox.Inherits(UI.RenderableObject);
function ui_HeadlinesSelectedItemCheckbox(selected, msg_id, cluster_id)
{
	this.selected = selected;
	this.msg_id = msg_id;
	this.cluster_id = cluster_id;
	this.initialized = false;	
}

ui_HeadlinesSelectedItemCheckbox.prototype.Render=function()
{	
	var input = null;
	if(!this.initialized)
	{
		input = document.createElement("input");
		input.setAttribute("id", this.obj.id+"_cb");
		input.setAttribute("type", "checkbox");
		input.setAttribute("onclick", "ui_HeadlinesSelectedItemCheckbox_OnClick(this,"+this.msg_id+");");
		
		this.initialized = true;
	}
	else
		input = this.obj.childNodes[0];
	
	input.removeAttribute("checked", false);	
	var selItems = data_GetSelectedMessagesForEmailing();
	if(selItems && selItems.getCount() > 0)
		for(var i=0; i<selItems.getCount(); i++)
			if(this.msg_id==selItems.GetByIndex(i).GetNodeValue(MessageItem.PN_ID))
			{
				input.setAttribute("checked", true);	
				break;
			}
	this.SetObjectInnerHtml(input.outerHTML);
}

function ui_HeadlinesSelectedItemCheckbox_OnClick(input, msg_id, evt)
{
	if (window.event)
		window.event.cancelBubble = true;		
		
	// APL: In Trends mode DS is always "Subscriptions.Latest"
	var dsName = "Subscriptions.Latest";
	if(nav_currentNavInfo.GetPageID() != PID_TRENDS)
		dsName = SiteLayout.ContentViewSwitch.GetCurrentHeadlinesState() ? "Subscriptions.Latest" : "Subscriptions.LatestS";	
	data_MarkItemSelected(dsName, msg_id, input.checked, false, false, false, true);
}

function ui_UIHeadlinesDateTimeItem(elDateTime, elTimeOnly)
{
	this.displayName = elDateTime != elTimeOnly ? elTimeOnly : "";
}
ui_UIHeadlinesDateTimeItem.prototype = new UI.RenderableObject;
ui_UIHeadlinesDateTimeItem.prototype.constructor = ui_UIHeadlinesDateTimeItem;
ui_UIHeadlinesDateTimeItem.prototype.Render=function()
{
	this.SetObjectInnerHtml(this.displayName);
}

function ui_EntAdvDispName(displayName,isOwner)
{
	this.isOwner = isOwner == null || eval(isOwner) != true ? false : true;
	this.displayName = displayName;
}
ui_EntAdvDispName.prototype = new UI.RenderableObject;
ui_EntAdvDispName.prototype.constructor = ui_EntAdvDispName;
ui_EntAdvDispName.prototype.Render=function()
{
	this.SetObjectInnerHtml(this.displayName);
}

function ui_TagsLinkRendere(tagname, clienttagname, tagvalue, disptagname, disptagvalue, isfortagging, size)
{
	this.base = UI.RenderableObject;
	this.tagname = tagname;
	this.clienttagname = clienttagname;
	this.tagvalue = tagvalue;
	this.disptagname = disptagname;
	this.disptagvalue = disptagvalue;
	this.isfortagging = isfortagging.toLowerCase() == "true";
	this.size = size;
}
ui_TagsLinkRendere.prototype = new UI.RenderableObject;
ui_TagsLinkRendere.prototype.constructor = ui_TagsLinkRendere;
ui_TagsLinkRendere.prototype.Render=function()
{
	var tttagname = this.disptagname;
	var onclick = "";
	var title = "";
	var encodeddispvalue = cmn_scriptEncodeString(this.disptagvalue);
	var encodedvalue = cmn_scriptEncodeString(this.tagvalue);
	if (this.isfortagging != true)
	{
		switch(this.tagname) 
		{
			case "Company":
				tttagname = "secondary " + tttagname;
				onclick = "TouchPointSettings.setShowPrimarySymbols('0');";
				break;
			case "PrimaryCompany":
				tttagname = "primary " + tttagname;
				onclick = "TouchPointSettings.setShowPrimarySymbols('-1');";
				break;
		}
		title = "Search by ~0: ~1".format(tttagname, this.disptagvalue);
		onclick += "do_inpDoSearchByFilter(\"~0\", \"~1\", \"~2\", true);return false;".format(this.clienttagname, encodedvalue, encodeddispvalue.toUpperCase());
	}
	else
	{
		title = "~0: ~1".format(tttagname, this.disptagvalue);
		onclick += "srch_inpAddToInputValueEx(\"~0\", \"~1\", \"~2\");return false;".format(this.disptagname, encodeddispvalue);
	}
	
	var domObj = DOMObjectFactory.CreateTempDOMObject("a");
	domObj.setInnerText( this.disptagvalue );
	domObj.setAttribute("href", "#");
	domObj.setAttribute("title", title);
	domObj.setAttribute("onclick", onclick);
	if (this.size != null)
		domObj.setAttribute("class", "it0"+this.size);
	this.SetObjectInnerHtml(domObj.getOuterHTML());
}

function ui_CalendarHeader(id, name, daily)
{
	this.base = UI.RenderableObject;
	this.name = name;
	this.id = id;
	this.daily = daily == "true";
}
ui_CalendarHeader.prototype = new UI.RenderableObject;
ui_CalendarHeader.prototype.constructor = ui_CalendarHeader;
ui_CalendarHeader.prototype.Render=function()
{
	var html = "<table><tr>";
	if (!str_IsStringEmpty(this.name) && this.name != EventOccurrence.TS && this.daily)
	{
		var tmpl = "<td width=122px class='grc1' style='padding-left:7px'>~0</td><td>~1</td>" 
		html += tmpl.format(EventOccurrence.GetShortName(this.name), EventOccurrence.GetLongName(this.name))
	}
	else
	{
		var dateTxt = null;
		if ([EventOccurrence.TS, EventOccurrence.BMO, EventOccurrence.AMC, EventOccurrence.NTS ].indexOf(this.name) == -1 && !str_IsStringEmpty(this.name))
			dateTxt = this.name;
		else 
		{
			var date = new Date(0,0,0,this.id,0,0);
			dateTxt = date.ToString(this.GetFormat());
		}
			
		var tmpl = "<td class='grc1' style='padding-left:7px'>~0</td>" 
		html += tmpl.format(dateTxt);
	}
	html += "</tr></table>";
	this.obj.style.height = "10px";
	this.SetObjectInnerHtml(html);
}
ui_CalendarHeader.prototype.GetFormat=function()
{
	if (this.daily)
	{
		if (str_IsStringEmpty(GeneralPreferences.TimeFormatExpression))
			return "hh:mm tt";
		else
			return GeneralPreferences.TimeFormatExpression;
	}
	else
	{
		if (str_IsStringEmpty(GeneralPreferences.DateFormatExpression))
			return "MM/dd/yyyy";
		else
			return GeneralPreferences.DateFormatExpression;
	}
}

ui_RemoveAssignment.Inherits(UI.RenderableObject);
function ui_RemoveAssignment(link, isSystem)
{
	this.link = link;
	this.isSystem = eval(isSystem) == true ? true : false;
	
	this.Render = function()
	{
		var html = "";
		if (!this.isSystem && this.link)
			html += this.link;
		this.SetObjectInnerHtml(html);
	}
}

ui_HTMLDecoder.Inherits(UI.RenderableObject);
function ui_HTMLDecoder(html)
{
	this.html = html;
}
ui_HTMLDecoder.prototype.Render=function()
{
	this.SetObjectInnerHtml(this.html);
}

ui_LookingForwardColumn.Inherits(UI.RenderableObject);
function ui_LookingForwardColumn(id)
{
	this.id = id;
	
	this.SplitString = function(searchWord,prompt,searchFromFirst)
	{
		var esprompt = (RegExp.escape(prompt)).replace(/\"/gi, "\\\"").replace(/\n/gi, "\\n")
		return searchWord.split(new RegExp("(?="+(searchFromFirst?" ":"")+esprompt+")","ig"));
	}
	this.ReplaceSubstrings = function(array,prompt,onlyFirst)
	{
		var thtml = "";
		for (var i = 0; i < array.length; i++)
		{
			var pos = array[i].toLowerCase().indexOf(prompt);
			if ( pos > -1 && pos < 2 && (!onlyFirst || onlyFirst && i == 0) )
				thtml += cmn_htmlEncode(array[i].substr(0,pos)) + "<strong>"+cmn_htmlEncode(array[i].substr(pos,prompt.length))+"</strong>" + cmn_htmlEncode(array[i].substr(pos+prompt.length));
			else
				thtml += cmn_htmlEncode(array[i]);
		}
		return thtml;
	}
	this.Render = function()
	{
		var prompt = lf_GetLastPrompt();
		if (prompt == null) return;
		if (prompt == "Direct Finance");
		prompt = prompt.toLowerCase();
		var type = lf_GetLastType();
		var item = lf_GetItemByID(this.id);
		if (!item) return;
		var name = null;
		var info = null;
		var value = null;
		var node = null;
		var xmlCustomData = lf_GetCustomDataXml(); // custom data
		var IsInName = true; // search result in Name
		var ignore = false;
		var OnlyFirstWord = true; // search substring in the first word of phrase
		var SearchFromFirstLetter = true; // search substring from first letter in the word
		var SearchInOrder = false; // search in name, if not result, search in info
		var nameWidth = "width:70px;";
		var firstStep = lf_GetResultOnFirstStep();
		switch(type)
		{
			case SRCH_TN_SYMBOL:
				value = name = item.GetNodeValue(ResolverSymbolItem.PN_SYMBOL);
				var country = item.GetNodeValue(ResolverSymbolItem.PN_COUNTRY);
				var nsc = item.GetNodeValue(ResolverSymbolItem.PN_NEEDSETCOUNTRY);
				if (!str_IsStringEmpty(country) && (lf_GetCount() > 1 || (!str_IsStringEmpty(nsc) && nsc.toLowerCase() == "true")))
					value += "=" + country
				info = item.GetNodeValue(ResolverSymbolItem.PN_NAME);
				if (xmlCustomData)
				{
					node = xmlCustomData.selectSingleNode("//IsSearchBySymbol");
					if (node != null && node.text == "false")
					{
						IsInName = IsInName && (firstStep == -1 || firstStep <= item.GetIndex());
						ignore = true;
					}
					if (IsInName)
					{
						var delimiters = [" ",".","="];
						var symlen = prompt.length;
						for(var l = 0; l < delimiters.length; l++)
						{
							var tsymlen = prompt.indexOf(delimiters[l]);
							if (tsymlen != -1 && tsymlen < symlen)
								symlen = tsymlen;
						}
						prompt = prompt.substr(0,symlen);
					}
				}				
				break;
			case SRCH_TN_INDUSTRY:
				OnlyFirstWord = false;
				SearchFromFirstLetter = false;
				IsInName = false;
				value = item.GetNodeValue(ResolverIndustryItem.PN_SHORTNAME);
				info = item.GetNodeValue(ResolverIndustryItem.PN_NAME);
				name = item.GetNodeValue(ResolverIndustryItem.PN_ID);
				break;
			case SRCH_TN_PORTFOLIO:
				value = name = item.GetNodeValue(CoverageItem.PN_NAME);					
				break;
			case SRCH_TN_REGION:
			case SRCH_TN_COUNTRY:
			case SRCH_TN_LANGUAGE:
				//IsInName = false;
				OnlyFirstWord = false;
				SearchFromFirstLetter = false;
				//SearchInOrder = true;
				value = info = item.GetNodeValue(ResolverGeographyItem.PN_NAME);					
				name = item.GetNodeValue(ResolverGeographyItem.PN_ID);
				break;				
			case SRCH_TN_CALENDAR:
			case SRCH_TN_BLOG:
			case SRCH_TN_FOLDER:
			case SRCH_TN_FEED:
				SearchFromFirstLetter = false;
				OnlyFirstWord = false;
				value = name = item.GetNodeValue(ContainerItem.PN_TITLE);
				break;
			case SRCH_TN_PROVIDER:
				value = name = item.GetNodeValue(LookingForwardItem.PN_ID);
				break;
			case SRCH_TN_BROKER:
			case SRCH_TN_TOPIC:
			case SRCH_TN_CUSTOMTOPIC:
				nameWidth = "width:100px;";
				OnlyFirstWord = false;
				SearchFromFirstLetter = false;
				value = info = item.GetNodeValue(LookingForwardItem.PN_NAME);
				name = item.GetNodeValue(LookingForwardItem.PN_ID);
				break;
			case SRCH_TN_SAVEDSEARCH:
				value = name = item.GetNodeValue(SearchItem.PN_TITLE);
				break;
			case SRCH_TN_FEEDCATEGORY:
				OnlyFirstWord = false;
				SearchFromFirstLetter = false;
				value = name = item.GetNodeValue(LookingForwardItem.PN_NAME);
				break;
			case SRCH_TN_BLOGCATEGORY:
				value = name = item.GetNodeValue(CategoryItem.PN_CATEGORYNAME);
				break;
			case SRCH_TN_PERIOD:
				nameWidth = "width:100px;";
				OnlyFirstWord = false;
				SearchFromFirstLetter = false;
				SearchInOrder = true;
				value = name = item.GetNodeValue(LookingForwardItem.PN_ID);
				info = item.GetNodeValue(LookingForwardItem.PN_NAME);
				break;
		}
		if (value == null)
			value = "";
		if (name == null)
			name = "";
		var html = "";
		if (str_IsStringEmpty(info))
			nameWidth = "";
		if (!ignore)
			IsInName = IsInName && (firstStep == -1 || firstStep > item.GetIndex());
		var searchWord = IsInName ? name : info; 
		var array = this.SplitString(searchWord,prompt,SearchFromFirstLetter);
		var thtml = this.ReplaceSubstrings(array,prompt,OnlyFirstWord);
		var tooltip = "";
		var encoded_name = cmn_htmlEncode(name);
		var encoded_info = cmn_htmlEncode(info);
		
		this.id = this.id.replace("\"","\\\"");
		var script = "lf_Replace(\"" + cmn_scriptEncodeString(value) + "\",\"" + this.id + "\");";
		lf_AddItemsScript(this.id,script);
		if (!str_IsStringEmpty(name))
		{
			script = cmn_htmlEncode(script);
			if (str_IsStringEmpty(info))
				tooltip = "title=\""+encoded_name+"\"";
			html += "<span style=\"display:-moz-inline-box;\"><a href=\"#\" style=\"" + nameWidth+ "\" onclick=\""+script+"\" "+tooltip+">";
			html += IsInName ? thtml : encoded_name;
			html += "</a></span>";
		}
		if (!str_IsStringEmpty(info))
		{
			if (IsInName && SearchInOrder && thtml == cmn_htmlEncode(searchWord) && thtml != encoded_info)
			{
				IsInName = false;
				array = this.SplitString(info,prompt,SearchFromFirstLetter);
				thtml = this.ReplaceSubstrings(array,prompt,OnlyFirstWord);
			}		
			tooltip = "title=\""+encoded_info+"\"";
			html += "<span "+tooltip+">";
			html += IsInName ? encoded_info : thtml;
			html += "</span>";
		}
		this.SetObjectInnerHtml(html);
	}
}
//-----------------------UI.CustomMetaData----------------------
var __UICUSTOMMETADATA__XSLTROWTEMPLATE = 
	["<tr>",
		"<td valign=\"top\" class=\"mtd_itm\"><span><xsl:value-of select=\"~0\" /></span></td>",
		"<td>",
			"<xsl:choose>",
				"<xsl:when test=\"position() = last() and not(position() = 1) \">",
					"<xsl:attribute name=\"class\"> mtd_info_last </xsl:attribute>",
				"</xsl:when> ",
				"<xsl:when test=\"position() = 1 and not(position() = last())\">",
					"<xsl:attribute name=\"class\"> mtd_info_first mtd_info </xsl:attribute>",
				"</xsl:when> ",
				"<xsl:when test=\"position() = 1 and position() = last()\">",
					"<xsl:attribute name=\"class\"> mtd_info_first </xsl:attribute>",
				"</xsl:when> ",
				"<xsl:otherwise>",
					"<xsl:attribute name=\"class\"> mtd_info </xsl:attribute>",
				"</xsl:otherwise>",
			"</xsl:choose>",
			"<xsl:variable name=\"v_Prm\" select=\"./~2\" />",
			"<xsl:apply-templates select=\"//~1[~2=$v_Prm]\" />&#160;",
		"</td>",
	"</tr>"].join('');
							 
var __UICUSTOMMETADATA__XSLTTEMPLATE = 
	["<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" >",
	 "<xsl:output method=\"html\" />",
	 "<xsl:template match=\"/\" >",
	 	"<div class=\"mtd_cust_row\">",
	 		"<table cellpadding=\"0\" cellspacing=\"0\" class=\"mtd_table ~5\">",
	 			"<tr><td><img src='~2' class='mtd_sep_itm' height='1px'/></td><td/></tr>",
	 			"<xsl:for-each select=\"//~1[not(~6 = preceding-sibling::~1/~6)]\">",
	 				"~0",
	 			"</xsl:for-each>",
	 		"</table>",
	 	"</div>