dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.Toolbar");
dojo.require("dijit.form.Button");
dojo.require("dijit.ProgressBar");
dojo.require("dijit.Menu");

/**
 * @author DREDroot
 *
 */
dojo.declare("dojom.Viewer", null,
{

	controller : null,
	logger : null,
	FClass : null,
	GClass : null,
	PClass : null,
	TClass : null,
	log : null,
	
	constructor: function ()
	{
		this.log = LOG.addClass("Viewer");
		var obj = this;
		
		try{
			
			this.controller = new dojom.Controller();
			this.FClass = new dojom.classes.FloaterClass();
			this.GClass = new dojom.classes.GridClass(this.controller);		
			this.PClass = new dojom.classes.ParametersClass();
			this.TClass = new dojom.classes.TabClass("mainTabContainer");												
			

			LOG.setMsgConsole(this.FClass.createToaster());
			
			var logConsole = new Object();	
			logConsole.setContent = function(text){
				obj.controller.saveLogUIError(text);
			}
			
			LOG.setLogConsole(logConsole);
			
			dojo.connect(this.TClass.mainTabContainer,"selectChild",function(tabChild){
				try{
					setTimeout(dojo.hitch(obj, function(){	
						obj.log.debug('constructor /selectChild/. tabChild:'+tabChild);
						if(tabChild.tabId == -1)
							return;
								
						if(tabChild.parameters == null)
						{
							tabChild.parameters = {};
							tabChild.parameters['keywords'] = null;
							tabChild.parameters['category'] = null;										
							tabChild.parameters['page'] = null;										
							tabChild.parameters['entity'] = null;
							tabChild.parameters['sortOption'] = null;
							tabChild.parameters['byAuthor'] = null;												
						}
						
						obj.PClass.setParameters(tabChild.parameters);
					}), 1000);
				}catch(ex){obj.log.error('constructor /selectChild/.'+JSON.stringify(ex))}
			});	
						
			dojo.connect(this.GClass,'rowDataOpen',function(inRowIndex,gridId){
				try{
					
					if(gridId !=-1)
						obj.openEntityInWindow(obj.GClass.newSearches_grids[gridId].model.data[inRowIndex][0]);				
					else 				
						obj.openEntityInWindow(obj.GClass.mySearches_grid.model.data[inRowIndex][0]);
				}catch(ex){obj.log.error('constructor /rowDataOpen/.'+JSON.stringify(ex))}
			});	
			
			dojo.connect(this.GClass,'rowDataShow',function(inRowIndex,gridId){
				try{
					var tabChild = obj.TClass.mainTabContainer.selectedChildWidget;
					if(gridId !=-1)
						obj.showEntity(obj.GClass.newSearches_grids[gridId].model.data[inRowIndex][0],tabChild);				
					else 				
						obj.showEntity(obj.GClass.mySearches_grid.model.data[inRowIndex][0],tabChild);
				}catch(ex){obj.log.error('constructor /rowDataOpen/.'+JSON.stringify(ex))}
			});	
			
			dojo.connect(this.TClass,'changeTab',function(tabChild,params){
				setTimeout(dojo.hitch(obj, function(){				
					if(	params['keywords']!=null 
						|| params['category']!=null 
						|| params['page']!=null 
						|| params['entity']!=null 
						|| params['tabPageIndex']!=null 
						)
						obj.PClass.setParameters(tabChild.parameters);
						
					if(params['gridData']!=null && params['page'] == null)
					{					
						var hitsContent = document.createElement('div');
						if(params['execTime'] != null)
							hitsContent.appendChild(function(){
								var span = document.createElement('span');
								span.setAttribute('style','font-size:1.0em');
								if(parseInt(params['numEntities']) > 0 && params["numEntities"] !=null)
									span.innerHTML = 'matches found: <b>'+params["numEntities"]+'</b>'+'  ('+params["execTime"]+' seconds).';
								else
									span.innerHTML = '<font style="font-size:1.0em;color: #cc0000">no matches found for:</font> <b>'+params['keywords']+'</d>';									
								return span;
							}());
						if(params['spelling'])
							hitsContent.appendChild(function(){
								var span = document.createElement('span');
								span.setAttribute('style','font-size:1.0em;color: #cc0000');
								span.innerHTML = '&nbsp;&nbsp;&nbsp;Did you mean: ';
								span.appendChild(function(){
									var a = document.createElement('a');
									a.setAttribute('href','##');
									a.onclick = function(){
										obj.makeSearch({
											'keywords':params['spelling'],
											'newtab':false
										});
									}
									a.innerHTML = params['spelling'];
									return a;
								}());
								return span;
							}());
						else if((params["numEntities"] ==null || parseInt(params['numEntities']) <= 0)  && params['category'] != 0)
						{
							hitsContent.appendChild(function(){
								var span = document.createElement('span');
								span.setAttribute('style','font-size:1.0em;color: #cc0000');
								span.innerHTML = '&nbsp;&nbsp;&nbsp;Try search in other category';								
								return span;
							}());
						}
						var node = document.getElementById('hitsContent');
						if(node.childDomNode != null)
							node.replaceChild(hitsContent,node.childDomNode);
						else
							node.appendChild(hitsContent);
						node.childDomNode = hitsContent;						
					}
				}), 1000);
			});
			this.controller.loadCategories(function(readStore){
				obj.log.debug('loaded categories');
				try{
					var selectTopCatigory = dijit.byId("selectTopCatigory");       	
					selectTopCatigory.store = new dojo.data.ItemFileReadStore({data: readStore});
					selectTopCatigory.setValue(0);
					obj.checkParameters();			
				}catch(ex){obj.log.error('conctructor /loadCategories/.'+JSON.stringify(ex))}
			});
			
			dijit.byId('TodayNewsTab').controlButton.innerDiv.className += ' tabToday';

			
		}catch(ex){obj.log.error('conctructor.'+JSON.stringify(ex))}
		
		//obj.checkParameters();
	},
	
	checkParameters: function()
	{
		var obj = this;
		
		try{
			var params = this.PClass.getParameters();
		
			//if(this.PClass.getCookie('login'))
			//	this.PClass.setParameters({login:this.PClass.getCookie('login')});						
			
			if(params['entity'])
			{						
				var entityId = parseInt(params['entity']);			
				obj.openEntityInWindow(entityId)
			}
			
			if(params['keywords']&&params['category'])
			{
				this.makeSearch(params);
				if(params['page'])
				{
					setTimeout(dojo.hitch(obj, function(){
						obj.loadNextGridPage(params['page']);
					}), 1000);
				}								
			}
		}catch(ex){obj.log.error('checkParameters /getParameters()/.'+JSON.stringify(ex))}	
						
		try{
			//dijit.byId('signInContent1').setContent('(Already have a page? <a href="##" onclick="Login(1)">Sign in</a> to see your stuff.)');
			this.login('','');
		}catch(ex){obj.log.error('checkParameters'+JSON.stringify(ex))};
	},
		
	makeSearch: function(params)
	{
		var obj = this;
		try{			
			this.log.debug('makeSearch.'+JSON.stringify(params));
			
			var tabChild = obj.TClass.mainTabContainer.selectedChildWidget;				
			if(params['sortOption'] != null && tabChild.parameters !=null && tabChild.parameters['sortOption'] !=null)
			{
				var re =new RegExp("(\\w+),(\\d+)");
				if(re.exec(params['sortOption'])[1] == re.exec(tabChild.parameters['sortOption'])[1])
				{
					var a = re.exec(tabChild.parameters['sortOption'])[2] == 0 ? '1' : '0';
					params['sortOption'] = params['sortOption'].replace(re,"$1,"+a);
				}					
			}
			obj.FClass.createEntityWindow().hide();
			
			if(params['keywords'] != null)
				dijit.byId('input_keyword').setValue(params['keywords']);
			else 
			{
				var widget = dijit.byId('input_keyword');
				if(!widget.isValid())
				{					
					this.log.debug('MakeSearch. Invalid keywords');
					return;
				}
				params['keywords'] = widget.getValue();
			}
				
			if(params['category'] != null)
				dijit.byId('selectTopCatigory').setValue(params['category']);
			else 
			{
				var widget = dijit.byId('selectTopCatigory');
				if(!widget.isValid())
				{					
					this.log.debug('MakeSearch. Invalid category');
					return;
				}
				params['category'] = widget.getValue();
			}			
			
			var progressBar = new dijit.ProgressBar({indeterminate:true,style:'width:50%;overflow:hidden;'},document.createElement('div'));
			var node = document.getElementById('hitsContent');
			if(node.childDomNode != null)
				node.replaceChild(progressBar.domNode,node.childDomNode);
			else
				node.appendChild(progressBar.domNode);
			node.childDomNode = progressBar.domNode;
			
			
			if(params['newtab']==false)	
			{
				this.refreshCurrentTab(params);				
			}		
			else
			{
				if(!this.createNewSearchTab(params))
					dijit.byId("hitsContent").setContent();
			}
		}catch(ex){this.log.error('makeSearch'+JSON.stringify(ex))}
	},	
	
	onFloatResize: function(tab)
	{
		var obj = this;
		try{
			if(tab == null) 
				return;
				
			if(tab.grid) tab.grid.domNode.style.height = (parseInt(obj.TClass.mainTabContainer.domNode.style.height) - 105) + 'px';
			if(tab.sentity) tab.sentity.domNode.style.height = (parseInt(obj.TClass.mainTabContainer.domNode.style.height) - 79) + 'px';
		}catch(ex){obj.log.error('onFloatResize/'+tab+'/.'+JSON.stringify(ex))}
	},
	
	createNewSearchTab: function(params)
	{		
		var obj = this;		
		try{
			var tabId = this.TClass.getNextSearchTabId();		
			obj.log.debug('createNewSearchTab. tabId='+tabId);
			
			if(tabId == null)
			{
				obj.log.msg('Can not create new search`s tab, max num of search`s tabs - '+this.TClass.tabIds.length,'warning');
				return false;
			}
			
			params['tabId']=tabId;
			
			/*CREATE CONTENT*/				
			var grid = this.GClass.createNewSearchGrid(document.createElement('div'),tabId);						
			
			/*CREATE TAB*/			
			var tabChild = obj.TClass.createNewTab({
				'id'	: 'searchTab_'+tabId,
				'tabId' : tabId,
				'parameters':params,
				'grid'	: grid,
				'cssClass': (params['byAuthor'] ==1 ? 'tabAuthor' :'tabSearch')
			});
						
			/*GET DATA*/
			if(params['keywords'] !=null && params['category'] !=null)
				this.controller.getSearchRows(params,
					function(_data){
						try{
							obj.log.debug('createNewSearchTab /GET DATA/. tabChild:'+tabChild+'. Load data.');							
							
							var toolbar = document.createElement("div");	
							if (dojo.isOpera)
								toolbar.setAttribute("style","width:99%;");
							else 
								toolbar.setAttribute("style","width:100%;");
							toolbar.className="tundra dijitToolbar";
														
							var menu = new dijit.Menu({},document.createElement("div"));
							var item1 = new dijit.MenuItem({label:'Price'},document.createElement("div"));
							dojo.connect(item1.domNode,'onclick',function(){
								params['sortOption']= '[[price,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item1);
							
							var item2 = new dijit.MenuItem({label:'Date'},document.createElement("div"));
							dojo.connect(item2.domNode,'onclick',function(){
								params['sortOption']= '[[created,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item2);
							
							var item3 = new dijit.MenuItem({label:'Store'},document.createElement("div"));
							dojo.connect(item3.domNode,'onclick',function(){
								params['sortOption']= '[[store,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item3);
							
							var dropDownButton = new dijit.form.DropDownButton({label: "sorting", dropDown: menu });
							var div = document.createElement("div");
							
							if (dojo.isIE)
							{
								div.style.cssText = 'width:99%; height:28px; text-align:right;';
								
							}
							else
								div.setAttribute("style","width:99%; text-align:right;");
							div.appendChild(dropDownButton.domNode);
							toolbar.appendChild(div);
														
							obj.TClass.changeTab(tabChild,{
								'numEntities': _data['numEntities'],
								'keywords': params['keywords'],
								'category': params['category'],
								'execTime': _data['execTime'],
								'spelling': _data['spelling'],
								'gridData': _data['data'],
								'toolbarContent':toolbar,
								'pagesNum':_data['numPages']
							});	
						}catch(ex){obj.log.error('createNewSearchTab /GET DATA/.'+JSON.stringify(ex))}		
						obj.onFloatResize(tabChild);								
				});
			
			/*Events*/
			dojo.connect(obj.TClass.mainTabContainer,"resize",function(){
				try{
					obj.onFloatResize(tabChild)
				}catch(ex){obj.log.error('createNewSearchTab /onResize/.'+JSON.stringify(ex))}
			});							
			dojo.connect(tabChild.pages,'onPageClick',function(num){
				try{
					obj.loadNextGridPage(num,params);
				}catch(ex){obj.log.error('createNewSearchTab /onPageClick/.'+JSON.stringify(ex))}
			});
			
		}catch(ex){obj.log.error('createNewSearchTab.'+JSON.stringify(ex))}		
		return tabChild;
	},
	
	refreshCurrentTab: function(params)
	{
		var obj = this;
		try{
			var tabChild = this.TClass.mainTabContainer.selectedChildWidget;
			params['tabId']=tabChild.tabId;
			
			obj.log.debug('refreshCurrentTab.'+tabChild);
			
			if(tabChild.id == "TodayNewsTab" || tabChild.tabId < 0)
			{
				this.createNewSearchTab(params);		
			}
			else 
			{						
				this.controller.getSearchRows(params,
					function(_data){
						try{
							var toolbar = document.createElement("div");	
							if (dojo.isOpera)
								toolbar.setAttribute("style","width:99%;");
							else 
								toolbar.setAttribute("style","width:100%;");
							toolbar.className="tundra dijitToolbar";
														
							var menu = new dijit.Menu({},document.createElement("div"));
							var item1 = new dijit.MenuItem({label:'Price'},document.createElement("div"));
							dojo.connect(item1.domNode,'onclick',function(){
								params['sortOption']= '[[price,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item1);
							
							var item2 = new dijit.MenuItem({label:'Date'},document.createElement("div"));
							dojo.connect(item2.domNode,'onclick',function(){
								params['sortOption']= '[[created,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item2);
							
							var item3 = new dijit.MenuItem({label:'Store'},document.createElement("div"));
							dojo.connect(item3.domNode,'onclick',function(){
								params['sortOption']= '[[store,0]]';
								params['newtab']= false;
								obj.makeSearch(params);
							});
							menu.addChild(item3);
							
							var dropDownButton = new dijit.form.DropDownButton({label: "sorting", dropDown: menu });
							var div = document.createElement("div");
							
							if (dojo.isIE)
							{
								div.style.cssText = 'width:99%; height:28px; text-align:right;';
								
							}
							else
								div.setAttribute("style","width:99%; text-align:right;");
							div.appendChild(dropDownButton.domNode);
							toolbar.appendChild(div);

							obj.TClass.changeTab(tabChild,{
								'numEntities': _data['numEntities'],
								'execTime': _data['execTime'],
								'spelling': _data['spelling'],
								'keywords': params['keywords'],
								'category': params['category'],
								'sortOption': params['sortOption'],
								'byAuthor': params['byAuthor'],
								'page': null,
								'entity': null,
								'gridData': _data['data'],
								'pagesNum': _data['numPages'],
								'toolbarContent':toolbar,
								'tabPageIndex':0,
								'cssClass': (params['byAuthor'] == 1 ? 'tabAuthor' :'tabSearch')
							});
						}catch(ex){obj.log.error('refreshCurrentTab /controller.getSearchRows()/.'+JSON.stringify(ex))}							
					}
				);		
			}
		}catch(ex){obj.log.error('refreshCurrentTab .'+JSON.stringify(ex));return;};	
	},
	
	createMySearches: function()
	{
		var obj = this;		
		try{
			if(dijit.byId('my_searches_tab'))
			{
				//obj.TClass.mainTabContainer.selectChild(dijit.byId('my_searches_tab'));
				return dijit.byId('my_searches_tab');
			}
			obj.log.debug('createMySearches.');
			
			/*CREATE CONTENT*/		
			var grid = this.GClass.createMySearchGrid();						
			
			var toolbarContent = new dijit.layout.ContentPane({id: 'toolbar_mysearch',style:"overflow-x: hidden;"},document.createElement('div'));			
			var toolbar = document.createElement("div");	
			if (dojo.isOpera)
				toolbar.setAttribute("style","width:99%;");
			else 
				toolbar.setAttribute("style","width:100%;");
			toolbar.className="tundra dijitToolbar";	
			var div = document.createElement("div");
			if (dojo.isIE)
				div.style.cssText = 'width:99%; height:28px; text-align:right;';
			else
				div.setAttribute("style","height:20px;width:99%; text-align:right;");
			toolbar.appendChild(div);
			toolbarContent.domNode.appendChild(toolbar);
			
			var button_content = new dijit.layout.ContentPane({id: 'remove_sel_rows_mysearch'},document.createElement('div'));
			var button = document.createElement("table");	
			var button = new dijit.form.Button({label:'Remove selected rows'},document.createElement("div"));	
			dojo.connect(button.domNode,'onclick',function(){
				var rows = obj.GClass.removeSelectedRows(-1);
				if(obj.PClass.isLogin(false)) obj.controller.deleteFromMySearches(rows,function(){});
			})
			button_content.domNode.appendChild(
				document.createElement("table").appendChild(
					document.createElement("tr").appendChild(
						document.createElement("td").appendChild(button.domNode)
					)
				) 
			);
			
			/*CREATE TAB*/
			var tabChild = obj.TClass.createNewTab({
				'id': 'my_searches_tab',
				'tabId':-1,
				'insertIndex':1,
				'title': 'My Searches('+grid.model.data.length+')',
				'grid': grid,
				'toolbar': toolbarContent,
				'pages': button_content,
				'cssClass': 'tabMySearches'
			});
			obj.onFloatResize(tabChild);
			
			/*Events*/
			dojo.connect(obj.TClass.mainTabContainer,"resize",function(){
				try{
					obj.onFloatResize(tabChild)
				}catch(ex){obj.log.error('createNewSearchTab /onResize/.'+JSON.stringify(ex))}
			});				
			dojo.connect(grid.model,"allChange",function(){				
				try{
					obj.TClass.changeTab(tabChild,{'title':'My Searchs('+grid.model.data.length+')'});
				}catch(ex){obj.log.error('createMySearches /grid.model.allChange/.'+JSON.stringify(ex))}
			});					
			
		}catch(ex){'createMySearches.'+JSON.stringify(ex)}
		
		return tabChild;	
	},	
		
	loadNextGridPage: function(num,params)
	{		
		var obj = this;
		try{
			var tabChild = this.TClass.mainTabContainer.selectedChildWidget;
			
			obj.log.debug('loadNextGridPage. tabChild: '+tabChild+', num: '+num);
			
			this.controller.getSearchRowsNextPage(num,params,tabChild.tabId,
				function(_data){
						try{
							obj.TClass.changeTab(tabChild,{
								'gridData': _data['data'],
								'page': num
							});
						}catch(ex){obj.log.error('loadNextGridPage /getSearchRowsNextPage()/.'+JSON.stringify(ex))}
				}
			);
		}catch(ex){obj.log.error('loadNextGridPage /getSearchRowsNextPage/.'+JSON.stringify(ex))};
	},	
	
	openEntityInWindow: function(entityId,floater,scroll)
	{		
		var obj = this;
		try{
			obj.log.debug('openEntityInWindow. entityId: '+entityId+',floater:'+floater+',scroll:'+scroll);
			
			var tabChild = this.TClass.mainTabContainer.selectedChildWidget;
			var category = 0;
			if(tabChild != null && tabChild.parameters != null && tabChild.parameters['category'] != null)
				category = tabChild.parameters['category'];
			
			
			if(entityId == null)
				return;
			
			if(floater == null)
			{
				floater = obj.FClass.createEntityWindow();
				if(floater.onWindowHide == null)
				{
					floater.onWindowHide = function(){
						obj.PClass.setParameters({'entity':null});
					}
					dojo.connect(floater,'hide',floater.onWindowHide);
				}
			}
			
			/*Creare Entity*/
			var entityHTML = document.createElement("div");				
			var entity = this.controller.getEntity(entityId,function(){
				try{
					setTimeout(dojo.hitch(this, function(){
						obj.openEntityInWindow(entityId,floater,scroll);
					}), 1000);					
				}catch(ex){obj.log.error('openEntity /openEntity/.'+JSON.stringify(ex))}				
			});				
			
			if (entity == null || entity['author_stors'] == null)
			{
				if(entity != null)
					obj.controller.getAuthor(entity['author_id'],function(data){					
						try{
							entity['author_stors'] = data['stores'];
							setTimeout(dojo.hitch(this, function(){
								obj.openEntityInWindow(entityId,floater,scroll);
							}), 1000);
						}catch(ex){obj.log.error('openEntityInWindow /getAuthorInfo/.'+JSON.stringify(ex))}
					});	  						
			  	
			  	entityHTML.appendChild(new dojom.data.Entity().getLoaderNode());
		   	}
			else
			{			 
				/*Model image*/
				entityHTML.appendChild(entity.getImageNode());
				
				/*Model info*/
				entityHTML.appendChild(function(){
					var div = document.createElement('div');
					div.setAttribute('style',' margin: 0.2em 0.2em 0.2em 308px; width: auto;');
						
					/*Model name*/				
					div.appendChild(entity.getNameNode());												
					
					/*Model info details*/
					div.appendChild(function(){
		   		    	var ul = entity.getDetailsNode();
		   		    	
						if(entity['author'] != null && entity['author_stors'] != null)
						{		
							ul.childs['author'].replaceChild(function(){
								var a = document.createElement('a');
								a.setAttribute('href','##');
								a.onclick = function(){
									obj.makeSearch({
										'keywords':entity['author'],
										'byAuthor':1,
										'newtab':true
									});
								}
								a.innerHTML = entity['author'];
								return a;
							}(),ul.childs['author'].lastChild);
									
							ul.childs['author_info'].innerHTML = "Author`s publishing stores: ";
							ul.childs['author_info'].appendChild(function(){
								var author_info = document.createElement('ul');																
								for(var i=0; i<entity['author_stors'].length;i++)
									author_info.appendChild(function(){
										var li = document.createElement('li');																
										for(var j in entity['author_stors'][i])
											li.innerHTML += '<span>'+j+'('+entity['author_stors'][i][j]+')</span>';
										return li;	
									}());											
																																																	
								return author_info;
							}());																														
						}						
		   		    	
						if(entity['keywords'] != null)
						{	
							ul.childs['keywords'].replaceChild(function(){
								if(entity['keywords_split']==null || entity['keywords_split'].nodeName == null)
								{	
									var tmp = [];
									try{
										tmp = entity['keywords'].split(/[ ,;]/);
									}catch(ex){obj.log.error('openEntityInWindow /entity[\'keywords\'].split/.'+JSON.stringify(ex))}
																		
									var span = document.createElement('span');		
									for(var i=0; i<tmp.length; i++)
									{
										span.appendChild(function(){
											var a = document.createElement('a');
											a.keywords = tmp[i];
											a.setAttribute('href','##');
											a.onclick = function(){
												obj.makeSearch({
													'keywords':a.keywords,
													'category':category,
													'newtab':true
												});
											}
											a.innerHTML = tmp[i];
											return a;
										}());
										span.appendChild(document.createTextNode(' '));
									}										
									entity['keywords_split'] = span;
								}								
								return entity['keywords_split'];
							}(),ul.childs['keywords'].lastChild);								
						}					
		   		    
						if(entity['comments'] != null)	
						{		
							ul.childs['comments'].replaceChild(function(){
								var a = document.createElement('a');
								a.setAttribute('href','##');
								a.onclick = function(){									
										obj.openEntityInWindow(entityId,null,{comments:true});	
								}
								a.innerHTML = 'Comments(<span>'+entity['comments'].length+'</span>)';
								return a;
							}(),ul.childs['comments'].lastChild);							
						}		   		   	 			   		    	
		   		    	return ul;
		   		    }());				   		    		   		    		   		    
					return div;
				}());
				
				entityHTML.appendChild(function(){
					//write 'Share code here'
					var _spanShare = document.createElement('span');
					_spanShare.setAttribute('style','vertical-align:middle;float:right;');
					var _innerStr_1 = '';					
					_spanShare.appendChild(function(){
						var a = document.createElement('a');
						a.setAttribute('href','http://www.addthis.com/bookmark.php');
						a.setAttribute('target','_blank');
						a.onclick = function(){									
							addthis_url = location.href;
							addthis_title = 	entity['name'];
							return addthis_click(this);
						}
						_innerStr_1 = '<img src="http://s9.addthis.com/button1-share.gif" width="125" height="16" border="0" alt="Bookmark and Share" /> <script type="text/javascript">var addthis_pub = "3dsn2008";</script><script type="text/javascript" src="http://s9.addthis.com/js/widget.php?v=10"></script>'; 
						a.innerHTML = _innerStr_1;		
						return a;
					}())			
					return _spanShare;							
				}());
				
				/*Model description*/
				if(entity['description'] != null)
					entityHTML.appendChild(entity.getDescriptionNode());
				
				/*Model rate*/
				entityHTML.appendChild(document.createElement('br'));
				if(entity['yourate'] == null)
				{
					entityHTML.appendChild(function(){
						var div = document.createElement('div');
						div.appendChild(function(){
							var span = document.createElement('span');
							span.innerHTML = '<b>Set You rate:</b>';
							return span;
						}());
						var span_1 = document.createElement('span');
						span_1.innerHTML='&nbsp;&nbsp;';
							
						div.appendChild(span_1);
						
						for(var i=0; i<11; i++)
						{
							var span_2 = document.createElement('span');
							span_2.innerHTML='&nbsp;&nbsp;';
							div.appendChild(function(){
								var span = document.createElement('span');
								var a = document.createElement('a');
								a.setAttribute('href',"##");
								a.i = i;
								a.onclick = function(){
									obj.setModelRate(entityId,a.i);
								}
								a.innerHTML = a.i;
								span.appendChild(a);
								return span;
							}());
							div.appendChild(span_2);
						}					
						return div;
					}());
				}
				else
					entityHTML.appendChild(function(){
						var div = document.createElement('div');
						div.setAttribute('style','font-size:1.0em;color: grey');
						div.innerHTML = 'Thank You for your rate';
						return div;
					}())
					
				/*Model comments*/				
				entityHTML.appendChild(document.createElement('br'));
				var span = document.createElement('span')
				span.setAttribute('id','comments');
				entityHTML.appendChild(span);
				if(entity['comments'] !=null && entity['comments'].length >0)
				{
					entityHTML.appendChild(document.createElement('br'));
					entityHTML.appendChild(document.createElement('b')).innerHTML = 'Comments:';
					entityHTML.appendChild(entity.getCommentsNode());
				}
								
				entityHTML.appendChild(function(){
					var div = document.createElement('div');
					div.setAttribute('style','width:100%;text-align:center;');
					
					div.appendChild(function(){						
						var textarea = document.createElement('textarea');
						textarea.setAttribute('style','width:99%;');
						textarea.setAttribute('cols','40');
						textarea.setAttribute('rows','3');
						
						
						
						textarea.setAttribute('id','comment_textarea_'+entityId);						
						return textarea;
					}());							
					return div;
				}());	
				
				entityHTML.appendChild(function(){
					var div = document.createElement('div');
					div.setAttribute('style','width:100%;text-align:center;');
					
					div.appendChild(function(){
						var button = new dijit.form.Button({label:'Add comment'},document.createElement('div'));
						button.domNode.onclick = function(){
							obj.addCommentForEntity(entityId);						
						}
						return button.domNode;
					}());							
					return div;
				}());		
																	
				
				/*Model control panel*/	
				entityHTML.appendChild(document.createElement('br'));			
				if(obj.TClass.mainTabContainer.selectedChildWidget.tabId != -1)
				{
					entityHTML.appendChild(function(){
						var button = new dijit.form.Button({label:'Add to My Searches'},document.createElement('div'));
						button.domNode.onclick = function(){
							obj.addToMySearches(entityId);						
						}
						return button.domNode;
					}());
				}
				
				entityHTML.appendChild(function(){
					var button = new dijit.form.Button({label:'Report about content'},document.createElement('div'));
					button.domNode.onclick = function(){
						obj.createFeedbackForm(entityId);						
					}
					return button.domNode;
				}());
			}
			
					
			floater.setNewContent(entityHTML);
			if(scroll != null && scroll['comments']==true)
			{
				try{
					var thepoint = document.getElementById('comments').offsetTop;
					floater.containerNode.lastChild.scrollTop = thepoint;
				}catch(ex){}
			}											
			setTimeout(dojo.hitch(this, function(){						
						obj.PClass.setParameters({'entity':entityId});
			}), 1000);				
								
		}catch(ex){obj.log.error('openEntityInWindow /entityId:'+entityId+',floater:'+floater+'/.'+ex)}		
	},
	
	
	showEntity: function(entityId,tabChild)
	{
		var obj = this;
		try{
			obj.log.debug('showEntity. entityId: '+entityId+', tabChild: '+tabChild);
			if(tabChild == null)
				tabChild = this.TClass.mainTabContainer.selectedChildWidget;			
			
			if(entityId == null)
				entityId = tabChild.parameters['entity'];
			
			if(entityId == null)
				return;
			
			/*Creare Entity*/
			var entityHTML = document.createElement("div");	
			var entity = this.controller.getEntity(entityId,function(){
				try{
					setTimeout(dojo.hitch(this, function(){
						obj.showEntity(entityId,tabChild);
					}), 1000);					
				}catch(ex){obj.log.error('showEntity /showEntity/.'+JSON.stringify(ex))}				
			});	
			
			
			if (entity == null)
			{			  				  	
			  	entityHTML.appendChild(new dojom.data.Entity().getLoaderNode());
			}
			else
			{	
				/*Model image*/
				entityHTML.appendChild(entity.getImageNode());
				
				/*Model info*/
				entityHTML.appendChild(function(){
					var div = document.createElement('div');
					div.setAttribute('style',' margin: 0.2em 0.2em 0.2em 308px; width: auto;');
						
					/*Model name*/				
					div.appendChild(entity.getNameNode());												
					
					/*Model info details*/
					div.appendChild(function(){
		   		    	var ul = entity.getDetailsNode();
		   		    	
						if(entity['author'] != null)
						{		
							ul.childs['author'].replaceChild(function(){
								var a = document.createElement('a');
								a.setAttribute('href','##');
								a.onclick = function(){
									obj.openEntityInWindow(entityId);
								}
								a.innerHTML = entity['author'];
								return a;
							}(),ul.childs['author'].lastChild);																																												
						}						
		   		    	
						if(entity['keywords'] != null)
						{	
							ul.childs['keywords'].replaceChild(function(){
								if(entity['keywords_split']==null || entity['keywords_split'].nodeName == null)
								{	
									var tmp = [];
									try{
										tmp = entity['keywords'].split(/[ ,;]/);
									}catch(ex){obj.log.error('openEntityInWindow /entity[\'keywords\'].split/.'+JSON.stringify(ex))}
																		
									var span = document.createElement('span');		
									for(var i=0; i<tmp.length; i++)
									{
										span.appendChild(function(){
											var a = document.createElement('a');
											a.keywords = tmp[i];
											a.setAttribute('href','##');
											a.onclick = function(){
												obj.makeSearch({
													'keywords':a.keywords,
													'category':tabChild.parameters['category'],
													'newtab':true
												});
											}
											a.innerHTML = tmp[i];
											return a;
										}());
										span.appendChild(document.createTextNode(' '));
									}											
									entity['keywords_split'] = span;
								}								
								return entity['keywords_split'];
							}(),ul.childs['keywords'].lastChild);								
						}					
		   		    
						if(entity['comments'] != null)	
						{		
							ul.childs['comments'].replaceChild(function(){
								var a = document.createElement('a');
								a.setAttribute('href','##');
								a.onclick = function(){
									obj.openEntityInWindow(entityId,null,{comments:true});									
								}
								a.innerHTML = 'Comments(<span>'+entity['comments'].length+'</span>)';
								return a;
							}(),ul.childs['comments'].lastChild);							
						}		   		   	 			   		    	
		   		    	return ul;
		   		    }());				   		    		   		    		   		    
					return div;
				}());
				
				/*Model description*/
				if(entity['description'] != null)
					entityHTML.appendChild(function(){
						var div = entity.getDescriptionNode();
						div.replaceChild(function(){
							var span = document.createElement('span');
							if(entity['shotdescription'] == null)
							{	
								entity['shotdescription'] = '';
								try{			
									entity['shotdescription'] = entity['description'].split('.')[0];
								}catch(ex){obj.log.error('showEntity /entity[\'description\'].split/.'+ex)}																
							}	
							span.innerHTML = entity['shotdescription'];
							return span;
						}(),div.lastChild);
						return div;	
					}());							
			}
			
			/*Model control panel*/
			var sepanelContent = document.createElement('div');			
			
			sepanelContent.appendChild(function(){
				var button = new dijit.form.Button({label:'Add to My Searches'},document.createElement('div'));
				button.domNode.onclick = function(){
					obj.addToMySearches(entityId);						
				}
				return button.domNode;
			}())
			
			sepanelContent.appendChild(function(){
				var button = new dijit.form.Button({label:'Details'},document.createElement('div'));
				button.domNode.onclick = function(){
					obj.openEntityInWindow(entityId);						
				}
				return button.domNode;
			}())
			sepanelContent.appendChild(function(){
				//write 'Share code here'
					var _spanShare = document.createElement('span');
					_spanShare.setAttribute('style','vertical-align:middle;');
					var _innerStr_1 = '';					
					_spanShare.appendChild(function(){
						var a = document.createElement('a');
						a.setAttribute('href','http://www.addthis.com/bookmark.php');
						a.setAttribute('target','_blank');
						a.onclick = function(){									
							addthis_url = location.href + "&entity="+entityId;
							addthis_title = 	entity['name'];
							return addthis_click(this);
						}
						_innerStr_1 = '<img src="http://s9.addthis.com/button1-share.gif" width="125" height="16" border="0" alt="Bookmark and Share" /> <script type="text/javascript">var addthis_pub = "3dsn2008";</script><script type="text/javascript" src="http://s9.addthis.com/js/widget.php?v=10"></script>'; 
						a.innerHTML = _innerStr_1;		
						return a;
					}())			
					return _spanShare;						
			}())
			
			this.TClass.changeTab(tabChild,{
				'sentityContent':entityHTML,
				'sepanelContent':sepanelContent
			});
		}catch(ex){obj.log.error('showEntity /entityId:'+entityId+',tabChild:'+tabChild+'/.'+ex)}		
	},
	
	addToMySearches: function(entityId)
	{
		var obj = this;
		try{
			if(entityId == null)
				entityId = obj.TClass.mainTabContainer.selectedChildWidget.parameters['entity'];
	
			obj.FClass.createEntityWindow().hide();
			obj.createMySearches();	
			obj.GClass.addToMySearches({'entityId':entityId});				
		}catch(ex){this.log.error('addToMySearches.'+ex)}
	},	
	
	
	setModelRate : function(id,rate)
	{
		var obj = this;
		try{
			obj.log.debug('conctructor /setModelRate/. id: '+id+'rate: '+rate);
			if(obj.PClass.isLogin(true))
				obj.controller.setModelRate(id,rate,function(data){					
					try{
						obj.controller.getEntity(id)['yourate'] = true;
						obj.openEntityInWindow(id)
					}catch(ex){obj.log.error('conctructor /setModelRate/.'+JSON.stringify(ex))}
				});
			setTimeout(dojo.hitch(obj, function(){
				obj.PClass.setParameters();
			}), 1000);
		}catch(ex){obj.log.error('setModelRate.'+ex)}
	},
	
	addCommentForEntity: function(entityId)
	{
		var obj = this;
		obj.log.debug('addCommentForEntity. entityId: '+entityId);
		try{
			var str = document.getElementById('comment_textarea_'+entityId).value;		
		
			if(str != '')
			{
				if(obj.PClass.isLogin(true))
					this.controller.addCommentForEntity(entityId,str,function(data){
						try{			
							obj.controller.pEntities[entityId]['comments'].push(data['comment']);
							obj.openEntityInWindow(entityId,null,{comments:true});
						}catch(ex){obj.log.error('addCommentForEntity /after addCommentForEntity/.'+JSON.stringify(ex))}
						
					});		
			}
		}catch(ex){obj.log.error('addCommentForEntity /getElementById/'+JSON.stringify(ex))}
	},										
	
	createFeedbackForm: function(id)
	{
		var obj = this;			
		try{
			obj.log.debug('createFeedbackForm. byId:'+id);
			if(obj.PClass.isLogin(true))
			{		
				if(id !=null)
					obj.FClass.createEntityWindow().hide();
				var floater = obj.FClass.createFeedbackFloater(function(params){
					try{
						obj.controller.postFeedback(params['message'],id,function(data){	
							try{
								obj.log.msg('Send successful');
							}catch(ex){'createFeedbackForm /controller.postFeedback()/.'+JSON.stringify(ex)}
						});							
					}catch(ex){obj.log.error('createFeedbackForm /FClass.createFeedbackFloater()/.'+JSON.stringify(ex))}			
				});
				if(id !=null)
					var evnt = dojo.connect(floater.floater,'hide',function(){					
							obj.FClass.createEntityWindow().show();
							dojo.disconnect(evnt);
					});
			}	
			setTimeout(dojo.hitch(obj, function(){
				obj.PClass.setParameters();
			}), 1000);
		}catch(ex){obj.log.error('createFeedbackForm'+JSON.stringify(ex))}
	},
	
	createRegForm: function()
	{
		var obj = this;	
		try{
			return this.FClass.createRegistrationFloater(function(params){
						var _tmp = this;
						try{
							obj.controller.registration(params,function(data){
								try{
									if(!obj.PClass.parameters['login'])
										obj.login(params['login'],params['pass']);
									_tmp.hide();
									obj.log.msg('Registration successful');
								}catch(ex){obj.log.error('createRegForm /controller.registration()/.'+JSON.stringify(ex))}
							});
						}catch(ex){obj.log.error('createRegForm /createRegistrationFloater()/.'+JSON.stringify(ex))}
						
					});		
		}catch(ex){obj.log.error('createRegForm.'+JSON.stringify(ex))}
	},
	
	createSignInFloater: function()
	{					
		var obj = this;
		try{
			this.FClass.createSignInFloater(function(params){
				try{
					obj.login(params['login'],params['pass']);
				}catch(ex){obj.log.error('createSignInFloater /createSignInFloater()/.'+JSON.stringify(ex))}
			},obj.createRegForm());		
		}catch(ex){obj.log.error('createSignInFloater.'+JSON.stringify(ex))}
	},
	
	login: function(login,pass)
	{
		var obj = this;
		obj.log.debug('login: '+login);
		try{
			this.controller.login(login,pass,function(data){
				try{		
					if(login=='')
						login = data['login'];
					if(login != null && login != '')
					{
						obj.PClass.setParameters({login: login});
						
						var node = document.getElementById('signInContent1');
						node.innerHTML = login;
						node.style.display ='block';
						
						document.getElementById('signInContent2').style.display = 'none';						
						document.getElementById('signInContent3').style.display = 'block';
						
						//obj.createMySearches();
						obj.loadMySearchRows();
					}
				}catch(ex){obj.log.error('login /controller.login()/.'+JSON.stringify(ex))}
			});
		}catch(ex){obj.log.error('login.'+JSON.stringify(ex))}
	},
	
	logout: function()
	{	
		var obj = this;
		obj.log.debug('logout');
		try{
			//this.seveGeometryOfFloaters();
			//this.PClass.deleteCookie('login','/','');
			this.PClass.setParameters({login:null});
			this.GClass.mySearchRows_data = null;
			
			if(dijit.byId('my_searches_tab'))
				obj.TClass.mainTabContainer.closeChild(dijit.byId('my_searches_tab'));
			
			var node = document.getElementById('signInContent1');
			node.innerHTML = '';
			node.style.display='none';
			
			document.getElementById('signInContent2').style.display='block';						
			document.getElementById('signInContent3').style.display='none';
			this.controller.logout();
		}catch(ex){obj.log.error('logout.'+JSON.stringify(ex))}
	},		
		
	loadMySearchRows: function()
	{
		var obj = this;
		obj.log.debug('loadMySearchRows');
		try{
			this.controller.getMySearchRows(function(_data){
				try{
					obj.GClass.mySearchRows_data =  _data['data'];
					
					if (obj.GClass.mySearches_grid != null)
						obj.GClass.mySearches_grid.setData(_data['data']);
				}catch(ex){obj.log.error('loadMySearchRows /controller.getMySearchRows()/.'+JSON.stringify(ex))}
			});
		}catch(ex){obj.log.error('loadMySearchRows.'+JSON.stringify(ex))}
	}
});
