var ComboboxRenderer=function(store){return function(input){var keyString=new String(input);if(keyString==undefined||keyString=='')return null;var text='';var keys=keyString.split(',');for(var i=0;i<keys.length;i++)
{var item=store.query('id',keys[i]).items[0];if(item!=undefined){text+=(text!=''?', ':'')+item.data['name'];}}
return text;}};var LoadingLayer={show:function(msg){if(!msg)msg='Loading data...';Ext.get('loading-msg').update(msg);Ext.get('loading').show();},hide:function(){Ext.get('loading').hide();}};Ext.ns('Widget');Widget.SearchSelectBox=function(conf){this.grid=null;if(conf.grid){this.grid=conf.grid;delete conf.grid;}
var config={beforeBlur:Ext.emptyFn,forceSelection:false,triggerAction:'all',allowBlank:true,hideOnSelect:true,editable:false,selectOnFocus:true,width:200,listeners:{render:function(field){field.clearValue();},select:function(field,record,idx){this.grid.filter(field);},blur:function(field){this.grid.filter(field);},specialkey:function(field,e){field.setValue(null);this.gird.filter(field);}}};Ext.apply(config,conf||{});Widget.SearchSelectBox.superclass.constructor.call(this,config);this.visibleByTransformDom(conf.transform);};Ext.extend(Widget.SearchSelectBox,Ext.ux.form.LovCombo,{visibleByTransformDom:function(domId){if($("."+domId).hasClass('hide')){this.hide();}},applyEmptyText:function(){if(this.rendered&&this.emptyText&&this.getRawValue().length<1){this.setRawValue(this.emptyText);this.el.addClass(this.emptyClass);}},preFocus:function(){var el=this.el;if(this.emptyText){}
if(this.selectOnFocus){(function(){el.dom.select();}).defer(this.inEditor&&Ext.isIE?50:0);}},onSelect:function(record,index){if(this.fireEvent('beforeselect',this,record,index)!==false){if(!record.get(this.checkField)){this.clearValue();}}
Widget.SearchSelectBox.superclass.onSelect.apply(this,arguments);}});Ext.ns('Widget');Widget.ContentBasePanel=function(conf){var config={applyTo:'center-grid-list',clicksToEdit:0,autoWidth:true,autoHeight:true,margins:'0 0 0 0',cmargins:'0 0 0 0'};Ext.apply(config,conf||{});Widget.ContentBasePanel.superclass.constructor.call(this,config);this.doResizeLayout();Ext.EventManager.onWindowResize(this.doResizeLayout,this);};Ext.extend(Widget.ContentBasePanel,Ext.grid.EditorGridPanel,{doResizeLayout:function(){if(!$("#contents-info").is(":visible"))return;var height=$(window).height();var newHeight=height-90;$(".contents-container").height(newHeight);var width=this.getView().mainBody.getSize().width+210;$(".contents").attr("style","min-width:"+width+"px;");}});Ext.ns('Widget');Widget.LabelsHeader=Ext.extend(Ext.BoxComponent,{tpl:new Ext.Template('<a href="#">'+gettext('Labels')+'</a>','<div class="btn">','<a href="#" class="btn_add" onclick="Ext.getCmp(\'labels-panel\').newLabel();return false;"></a>','<a href="/settings/labels/" class="btn_setting"></a>','</div>'),autoEl:{tag:'div',cls:'title'},onRender:function(){Widget.LabelsHeader.superclass.onRender.apply(this,arguments);this.tpl.insertFirst(this.el);}});Widget.LabelsSearchHeader=function(conf){var config={};Ext.apply(config,conf||{});this.searchField=config.searchField;Widget.LabelsSearchHeader.superclass.constructor.call(this,config);};Ext.extend(Widget.LabelsSearchHeader,Ext.BoxComponent,{autoEl:{tag:'div'},onRender:function(){Widget.LabelsSearchHeader.superclass.onRender.apply(this,arguments);this.searchField.render(this.el);}});Widget.LabelsGridView=function(config){Widget.LabelsGridView.superclass.constructor.call(this,config);};Ext.extend(Widget.LabelsGridView,Ext.grid.GridView,{cellSelector:'',rowSelector:'li.label-item',initTemplates:function(){var ts=this.templates||{};if(!ts.master){ts.master=new Ext.Template('<div class="label_list">','<ul>{body}</ul>','</div>');}
if(!ts.body){ts.body=new Ext.Template('{rows}');}
if(!ts.row){ts.row=new Ext.Template('{cells}');}
if(!ts.cell){ts.cell=new Ext.Template('<li class="label-item"><a href="#" style="width:176px;">{value}</a></li>');}
for(var k in ts){var t=ts[k];if(t&&typeof t.compile=='function'&&!t.compiled){t.disableformats=true;t.compile();}}
this.templates=ts;},ensureVisible:function(){},getResolvedXY:function(resolved){if(!resolved){return null;}
var c=resolved.cell,r=resolved.row;return[this.el.getX(),Ext.fly(r).getY()]},syncFocusEl:function(row,col,hscroll){},scrollToTop:function(){},focusCell:function(row,col,hscroll){},initElements:function(){var E=Ext.Element;var el=this.grid.getGridEl().dom.firstChild;var cs=el.childNodes;this.el=new E(el);this.mainBody=new E(cs[0]);},layout:function(){if(!this.mainBody){return;}
var g=this.grid;var c=g.getGridEl();var csize=c.getSize(true);var vw=csize.width;if(vw<20||csize.height<20)return;},renderHeaders:function(){},renderUI:function(){var body=this.templates.body.apply({rows:'&nbsp;'});var html=this.templates.master.apply({body:body});var g=this.grid;g.getGridEl().dom.innerHTML=html;this.initElements();},refresh:function(headersToo){this.fireEvent('beforerefresh',this);this.grid.stopEditing(true);var result=this.renderBody();this.mainBody.update(result);this.processRows(0,true);this.layout();this.applyEmptyText();this.fireEvent('refresh',this);},getEditorParent:function(){return this.mainBody.dom;},processRows:function(startRow,skipStripe){if(!this.ds||this.ds.getCount()<1){return;}
var rows=this.getRows();skipStripe=skipStripe||!this.grid.stripeRows;startRow=startRow||0;Ext.each(rows,function(row,idx){row.rowIndex=idx;row.className=row.className.replace(this.rowClsRe,' ');if(!skipStripe&&(idx+1)%2===0){row.className+=' x-grid3-row-alt';}});Ext.fly(rows[rows.length-1]).addClass(this.lastRowCls);},findHeaderIndex:function(el){return false;},findCellIndex:function(el,requiredCls){return 0;},getCell:function(row,col){var cell=this.getRow(row);return cell;}});Widget.LabelPagingToolbar=Ext.extend(Ext.Toolbar,{pageSize:10,displayMsg:'{0} more',paramNames:{start:'start',limit:'limit'},initComponent:function(){this.addEvents('change','beforechange');Widget.LabelPagingToolbar.superclass.initComponent.call(this);this.cursor=this.pageSize;this.bind(this.store);},onRender:function(ct,position){Widget.LabelPagingToolbar.superclass.onRender.call(this,ct,position);this.moreButton=Ext.get(this.addDom({tag:'a',cls:'more',html:this.getDisplayMsg()}).el);this.moreButton.on('click',this.clickMoreButton,this);},bind:function(store){store=Ext.StoreMgr.lookup(store);store.on("beforeload",this.beforeLoad,this);store.on("load",this.onLoad,this);store.on("loadexception",this.onLoadError,this);},unbind:function(store){store=Ext.StoreMgr.lookup(store);store.un("beforeLoad",this.beforeLoad,this);store.un("load",this.onLoad,this);store.un("loadexception",this.onLoadError,this);this.store=undefined;},beforeLoad:function(){},onLoad:function(store,r,o){if(!this.rendered){this.dsLoaded=[store,r,o];return;}
this.cursor=store.baseParams['limit']+this.pageSize;this.updateDisplayMsg();},onLoadError:function(){},doLoad:function(start,end){var o={};if(this.fireEvent('beforechange',this,o)!==false){this.store.baseParams['start']=start;this.store.baseParams['limit']=end;this.store.load();}},updateDisplayMsg:function(){if(this.moreButton){if(this.cursor>=this.store.getTotalCount()){this.moreButton.hide();}
else if(!this.moreButton.isVisible()){this.moreButton.show();}
this.moreButton.update(this.getDisplayMsg());}},getDisplayMsg:function(){var total=this.store.getTotalCount();var moreCount=total-this.cursor;var msg=String.format(this.displayMsg,moreCount);return msg;},clickMoreButton:function(){this.doLoad(0,this.cursor);},onDestroy:function(){if(this.store){this.unbind(this.store);}
Widget.LabelPagingToolbar.superclass.onDestroy.call(this);}});Widget.LabelsPanel=function(conf){this.pageSize=10;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/folder/label/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:['id','name']})});this.store.proxy.conn.disableCaching=false;this.store.baseParams={option:'search',limit:this.pageSize};this.searchField=new Ext.ux.form.SearchField({width:198,emptyText:''});this.searchField.callbackObj=this;var config={id:'labels-panel',style:'width: 100%',autoHeight:true,store:this.store,view:new Widget.LabelsGridView(),hideHeaders:true,cm:new Ext.grid.ColumnModel({columns:[{id:'name',dataIndex:'name',width:210,editor:new Ext.form.TextField({allowBlank:false,listeners:{blur:this.cancelEditing.createDelegate(this)}})}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true,moveEditorOnEnter:false}),bbar:new Widget.LabelPagingToolbar({store:this.store}),listeners:{rowclick:function(grid,rowIndex,e){var record=grid.getStore().getAt(rowIndex);this.targetPanel.filterByLabel(record);},afteredit:function(e){if(!e.value){e.record.reject();}
var conn=new Ext.data.Connection();conn.request({url:'/folder/label/edit/',params:{id:e.record.id,field:e.field,value:e.value},success:function(resp,opt){var result=Ext.util.JSON.decode(resp.responseText);var label=result.label;e.record.id=label.id;e.record.commit();},failure:function(resp,opt){e.record.reject();}});}}};Ext.apply(config,conf||{});this.tbar=new Widget.LabelsHeader();Widget.LabelsPanel.superclass.constructor.call(this,config);this.store.load();};Ext.extend(Widget.LabelsPanel,Ext.grid.EditorGridPanel,{onRender:function(){Widget.LabelsPanel.superclass.onRender.apply(this,arguments);this.searchFieldHeader=new Widget.LabelsSearchHeader({renderTo:this.tbar,searchField:this.searchField});},load:function(){this.store.load();},newLabel:function(){this.stopEditing();var Record=Ext.data.Record.create(['id','name']);var defaultFields={id:0,name:''};this.store.insert(0,new Record(defaultFields,0));this.startEditing(0,0);},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},reset:function(){this.selModel.clearSelections();},cancelEditing:function(field){if(!field.getRawValue()){this.stopEditing();this.store.getAt(0).reject();this.store.load();}}});Ext.ns('Widget');Widget.GridStatusView=Ext.extend(Ext.BoxComponent,{id:'gridStatusView',tpl:new Ext.Template('<div class="result-info">','<img src="'+MEDIA_URL+'/ext/resources/images/adview/common/icon_resultinfo.gif" />','{msg}<a href="#" class="btn_clear" onclick="Ext.getCmp(\'gridStatusView\').clearSearchFilter();return false;"></a>','</div>'),msgEng:'Showing Search Results for <strong>{0}</strong>',autoEl:{tag:'div'},initComponent:function(){this.bind(this.store);},bind:function(store){store=Ext.StoreMgr.lookup(store);store.on("datachanged",this.onDataChanged,this);},unbind:function(store){store=Ext.StoreMgr.lookup(store);store.un("datachanged",this.onDataChanged,this);this.store=undefined;},onDataChanged:function(store){var isShow=false;for(var key in store.baseParams){if(key=='keyword'&&store.baseParams[key])
{isShow=true;}else if(key.match("^filter_")=="filter_"){if(store.baseParams[key]){isShow=true;}}}
if(isShow){this.showMessage(store);}
else{this.removeMessage(store);}},onDestroy:function(){if(this.store){this.unbind(this.store);}
Widget.GridStatusView.superclass.onDestroy.call(this);},removeMessage:function(store){this.el.update("");},showMessage:function(store){this.el.update("");this.tpl.insertFirst(this.el,{msg:this.getMessage(store)});},getMessage:function(store){var msg="";for(var key in store.baseParams){if(key=='keyword'){if(store.baseParams['keyword']!=''){msg+="search: "+store.baseParams[key]+" ";}}else if(key.match("^filter_")=="filter_"){if(store.baseParams[key]!=''){var keyName=key.substr(key.indexOf("filter_")+7);msg+=keyName+":"+store.baseParams['value_'+key]+" ";}}}
return String.format(this.msgEng,msg);},clearSearchFilter:function(){this.parentContainer.clearSearchFilters();}});Ext.ns('Widget');Widget.DataNavigator=function(config){this.tpl=new Ext.XTemplate('<ul class="{this.ulCls}" >','<tpl for=".">','<li class="item"><a href="#">{title}</a></li>','</tpl>','</ul>',{ulCls:config.navCls});Widget.DataNavigator.superclass.constructor.call(this,config);this.on('containerclick',function(thisView,e){return false;});this.isDefaultSelected=true;this.bindStore(true);this.load();};Ext.extend(Widget.DataNavigator,Ext.DataView,{onRender:function(){Widget.DataNavigator.superclass.onRender.apply(this,arguments);if(this.enableDnD){this.dz=new this.dropZone(this,{ddGroup:this.ddGroupName});}},singleSelect:true,itemSelector:'li.item',load:function(){this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();var canLoad=false;if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},bindStore:function(initial){if(!initial){this.store.un('load',this.onLoadStore,this);}
else{this.store.on('load',this.onLoadStore,this);}},onLoadStore:function(){if(this.isDefaultSelected){if(this.selectedId){var index=this.store.indexOfId(parseInt(this.selectedId));this.select(index,true,false);}}
this.isDefaultSelected=false;},onDestroy:function(){this.bindStore(null);Widget.DataNavigator.superclass.onDestroy.call(this);}});var CountryStore=function(){var config={proxy:new Ext.data.HttpProxy({url:'/countries/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:[{name:'id'},{name:'name'}]})};CountryStore.superclass.constructor.call(this,config);};Ext.extend(CountryStore,Ext.data.Store);var CountryComboBox=function(conf){var config={name:'country',beforeBlur:Ext.emptyFn,valueField:'id',displayField:'name',triggerAction:'all',width:210,listWidth:240,minChars:2,hideTrigger:false,editable:true,emptyText:'Type first charcters the country name',typeAhead:false,pageSize:50};Ext.apply(config,conf||{});CountryComboBox.superclass.constructor.call(this,config);};Ext.extend(CountryComboBox,Ext.ux.form.LovCombo,{onSelect:function(record,index){if(this.fireEvent('beforeselect',this,record,index)!==false){if(!record.get(this.checkField)){this.clearValue();}}
CountryComboBox.superclass.onSelect.apply(this,arguments);}});var LanguageStore=function(conf){var config={proxy:new Ext.data.HttpProxy({url:'/folder/language/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:[{name:'id'},{name:'name'}]})};Ext.apply(config,conf||{});LanguageStore.superclass.constructor.call(this,config);};Ext.extend(LanguageStore,Ext.data.Store);var LanguageComboBox=function(conf){var config={name:'language',beforeBlur:Ext.emptyFn,valueField:'id',displayField:'name',triggerAction:'all',forceSelection:false,selectOnFocus:false,editable:false,hideOnSelect:false};Ext.apply(config,conf||{});LanguageComboBox.superclass.constructor.call(this,config);};Ext.extend(LanguageComboBox,Ext.ux.form.LovCombo,{onSelect:function(record,index){if(this.fireEvent('beforeselect',this,record,index)!==false){if(!record.get(this.checkField)){this.clearValue();}}
FolderCategoryComboBox.superclass.onSelect.apply(this,arguments);}});var FolderLabelStore=function(conf){var config={proxy:new Ext.data.HttpProxy({url:'/folder/label/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:[{name:'id'},{name:'name'}]})};Ext.apply(config,conf||{});FolderLabelStore.superclass.constructor.call(this,config);};Ext.extend(FolderLabelStore,Ext.data.Store);var FolderLabelComboBox=function(conf){var config={name:'labels',beforeBlur:Ext.emptyFn,grow:true,listWidth:180,valueField:'id',displayField:'name',triggerAction:'all',forceSelection:false,selectOnFocus:false,editable:false,hideOnSelect:false};Ext.apply(config,conf||{});FolderLabelComboBox.superclass.constructor.call(this,config);};Ext.extend(FolderLabelComboBox,Ext.ux.form.LovCombo,{});var FolderClusterDropZone=function(view,config){this.view=view;FolderClusterDropZone.superclass.constructor.call(this,view.getEl(),config);};Ext.extend(FolderClusterDropZone,Ext.dd.DropZone,{onContainerOver:function(dd,e,data){var result=dd.grid!==this.grid?this.dropAllowed:this.dropNotAllowed;if(result==this.dropAllowed){var targetSel=this.view.itemSelector;var t=e.getTarget(targetSel);if(!t||this.view.indexOf(t)<0){result=this.dropNotAllowed;}}
return result;},onContainerDrop:function(dd,e,data){if(dd.grid!==this.view){var targetSel=this.view.itemSelector;var t=e.getTarget(targetSel);if(!t||this.view.indexOf(t)<0)return false;var view=this.view;var record=view.getRecord(t);if(!record)return false;var folderId=record.data.id;var clusterIds="";var originalIds="";Ext.each(data.selections,function(r){if(r.data.cid){clusterIds+=(clusterIds!=''?', ':'')+r.data.cid;}
else if(r.data.oid){originalIds+=(originalIds!=''?', ':'')+r.data.oid;}});Ext.Ajax.request({url:'/foldercluster/move/',params:{folderId:folderId,clusterIds:clusterIds,originalIds:originalIds},success:function(resp,opt){Ext.each(data.selections,function(r){dd.grid.store.remove(r);});},failure:function(resp,opt){Ext.Msg.alert("Error unable to move clusters");}});return true;}
else{return false;}},containerScroll:true});var SiteCoverageRecordFields=[{name:'site_id',type:'int'},'site_name','site_logo_url','region_code','region_name','region_logo_url','insert_total_cnt','insert_daily_cnt','insert_average_cnt','deadlink_total_cnt','deadlink_daily_cnt','deadlink_average_cnt','index_total_cnt','index_daily_cnt','index_average_cnt'];var SiteCoverageGridPanel=function(conf){this.pageSize=300;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/sitecoverage/list/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'site_id',totalProperty:'total',fields:SiteCoverageRecordFields}),sortInfo:{field:'site_id',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize}
var config={margins:"0 5 0 5",frame:false,viewConfig:{forceFit:false},cls:'contents',autoWidth:true,autoHeight:true,store:this.store,cm:new Ext.grid.ColumnModel({columns:[{header:"",dataIndex:"site_name",menuDisabled:true,width:230,renderer:function(value,metadata,record){var logo_url=record.get('site_logo_url');if(logo_url){return'<img src="'+logo_url+'" /> '+value;}
return value;}},{header:"",dataIndex:"region_name",menuDisabled:true,width:230,renderer:function(value,metadata,record){var logo_url=record.get('region_logo_url');if(logo_url){return'<img src="'+logo_url+'" /> '+value;}
return value;}},{header:gettext("Daily Avg"),dataIndex:"insert_average_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'},{header:gettext("Total"),dataIndex:"insert_total_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'},{header:gettext("Daily Avg"),dataIndex:"deadlink_average_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'},{header:gettext("Total"),dataIndex:"deadlink_total_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'},{header:gettext("Daily Avg"),dataIndex:"index_average_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'},{header:gettext("Total"),dataIndex:"index_total_cnt",width:120,align:"right",menuDisabled:true,summaryType:'sum'}],defaults:{menuDisabled:true,sortable:false}}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,align:'left',displayInfo:true,emptyMsg:'No Data found'}),plugins:[new Ext.ux.plugins.GroupHeaderGrid({rows:[[{header:gettext('Site'),colspan:1,align:'center',css:'info'},{header:gettext('Region'),colspan:1,align:'center',css:'info'},{header:gettext('Videos Crawled'),colspan:2,align:'center',css:'info'},{header:gettext('Videos Deadlinked'),colspan:2,align:'center',css:'data'},{header:gettext('Videos Indexed'),colspan:2,align:'center',css:'data'}]],hierarchicalColMenu:true}),new Ext.ux.grid.HybridSummary()]};Ext.apply(config,conf||{});SiteCoverageGridPanel.superclass.constructor.call(this,config);this.load();this.doResizeLayout();Ext.EventManager.onWindowResize(this.doResizeLayout,this);};Ext.extend(SiteCoverageGridPanel,Ext.grid.GridPanel,{doResizeLayout:function(){var height=$(window).height();var newHeight=height-90;$(".contents-container").height(newHeight);var width=this.getView().mainBody.getSize().width+210;$(".contents").attr("style","min-width:"+width+"px;");},load:function(){this.store.load();}});var SiteCoverageLayout=function(){var siteCoverageGridPanel;return{init:function(){siteCoverageGridPanel=new SiteCoverageGridPanel({id:'site-coverage-grid',renderTo:'container'});}}}();Ext.ns('Content');Content.ProgramSimpleList=Ext.extend(Ext.DataView,{onRender:function(){Content.ProgramSimpleList.apply(this,arguments);this.dz=new FolderClusterDropZone(this,{ddGroup:'folderDDGroup'});},store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/programs/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:['id','title']})}),tpl:new Ext.XTemplate('<ul class="program-list" style="height:300px;">','<tpl for=".">','<li class="item"><a href="#">{title}</a></li>','</tpl>','</ul>'),listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);if(this.gridPanel){this.gridPanel.loadByProgramId(record.id);$("span#program_title").html(record.data.title);}}},singleSelect:true,itemSelector:'li.item',load:function(){this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();var canLoad=false;if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}}});Ext.ns('Content');Content.ProgramRecordFields=[{name:'id',type:'int'},'title','title_eng','title_jp','program_code',{name:'type',type:'int'},{name:'release_date',type:'date',dateFormat:'Y-m-d'},'category','language','labels','countries','genres','ratings','director','actor','copyright','cluster_count'];Content.ProgramPanel=function(){this.pageSize=40;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/programs/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:Content.ProgramRecordFields}),sortInfo:{field:'release_date',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize};this.categoryStore=new FolderCategoryStore();this.labelStore=new FolderLabelStore();this.categoryStore.load();this.labelStore.load();Content.ProgramPanel.superclass.constructor.call(this,{cls:'grid-program',clicksToEdit:0,store:this.store,cm:new Ext.grid.ColumnModel({columns:[{id:'program_code',header:gettext('Program Code'),dataIndex:'program_code',sortable:true,width:90,hideable:false,editor:new Ext.form.TextField({allowBlank:true})},{id:'title',header:gettext('Title'),dataIndex:'title',sortable:true,width:300,editor:new Ext.form.TextField({allowBlank:false,validator:function(val){if(!val.trim())return false;return true;}})},{id:'title_eng',header:gettext('Title (English)'),dataIndex:'title_eng',sortable:true,hidden:true,width:300,editor:new Ext.form.TextField({allowBlank:false})},{id:'title_jp',header:gettext('Title (Japan)'),dataIndex:'title_jp',width:300,sortable:true,hidden:true,editor:new Ext.form.TextField({allowBlank:false})},{id:'release_date',header:gettext('Release Date'),dataIndex:'release_date',sortable:true,type:'date',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d'),editor:new Ext.form.DateField({format:'Y-m-d'})},{id:'cluster_count',header:gettext('Fingerprints'),sortable:true,width:90,dataIndex:'cluster_count'},{id:'category',header:gettext('Category'),dataIndex:'category',sortable:true,renderer:ComboboxRenderer(this.categoryStore),width:80,editor:new FolderCategoryComboBox({store:this.categoryStore})},{id:'labels',header:gettext('Labels'),dataIndex:'labels',sortable:true,width:80,renderer:ComboboxRenderer(this.labelStore),editor:new FolderLabelComboBox({store:this.labelStore})},{id:'country',header:gettext('Country'),dataIndex:'countries',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'language',header:gettext('Language'),dataIndex:'languages',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'genre',header:gettext('Genre'),dataIndex:'genres',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'rating',header:gettext('Rating'),dataIndex:'ratings',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'director',header:gettext('Director'),dataIndex:'director',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'actor',header:gettext('Actors/Acteresses'),dataIndex:'actor',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})},{id:'copyright',header:gettext('Copyright Holder'),dataIndex:'copyright',sortable:true,width:80,editor:new Ext.form.TextField({allowBlank:true})}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true,moveEditorOnEnter:false,listeners:{rowdeselect:this.rowdeselect.createDelegate(this)}}),listeners:{cellcontextmenu:function(grid,rowIndex,cellIndex,e){this.startEditing(rowIndex,cellIndex);e.stopEvent();},rowdblclick:function(grid,rowIndex,e){var record=grid.getStore().getAt(rowIndex);if(record.get('id')){var pid=record.get('id');LoadingLayer.show();document.location="/content/p/"+pid+"/f/";}},afteredit:function(e){var conn=new Ext.data.Connection();conn.request({url:'/folder/edit/',params:{action:'update',id:e.record.id,field:e.field,value:e.value},success:function(resp,opt){var result=Ext.util.JSON.decode(resp.responseText);var id=result.id;e.record.id=id;e.record.commit();},failure:function(resp,opt){e.record.reject();}});}},bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,align:'left',displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Program found')})});this.getView().getRowClass=function(record,index,rowParams,store){var type=record.get('type');if(type==2){return"default-folder";}
return"";}};Ext.extend(Content.ProgramPanel,Widget.ContentBasePanel,{onCellDblClick:function(g,row,col){},afterRender:function(){Content.ProgramPanel.superclass.afterRender.apply(this,arguments);this.getBottomToolbar().add('-');this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_add.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Add Program'),handler:this.addProgram.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_delete.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Remove Program'),handler:this.removeProgram.createDelegate(this)});},load:function(){this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filterByLabel:function(labelRecord){if(labelRecord.data.id>0){this.store.baseParams['filter_labels']=labelRecord.data.id;this.store.baseParams['value_filter_labels']=labelRecord.data.name;}
else{delete this.store.baseParams['filter_labels'];delete this.store.baseParams['value_filter_labels'];}
this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();var canLoad=false;if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},addProgram:function(){this.stopEditing();var Record=Ext.data.Record.create(Content.ProgramRecordFields);var defaultFields={id:0};this.store.insert(0,new Record(defaultFields,0));this.startEditing(0,0);this.getSelectionModel().selectFirstRow();},removeProgram:function(){var thisPanel=this;var sm=this.getSelectionModel();var sel=sm.getSelected();if(sm.hasSelection()){if(sel.data.id==0){this.store.reload();return;}
if(sel.data.type==2){Ext.Msg.alert(gettext("Warning"),gettext("Default folder can't be removed."));return;}
if(sel.data.cluster_count>0){Ext.Msg.alert(gettext("Warning"),gettext("The program with cluster can't be deleted <br /> If you wish to delete,move cluster to another program"));return;}
Ext.Msg.show({title:'Remove Program',buttons:Ext.MessageBox.YESNOCANCEL,msg:'Remove "'+sel.data.title+'"?',fn:function(btn){if(btn=='yes'){Ext.Ajax.request({url:'/folder/remove/',params:{id:sel.id},success:function(resp,opt){thisPanel.store.remove(sel);},failure:function(resp,opt){Ext.Msg.alert("Error unable to remove program");},scope:this});}}});}},rowdeselect:function(thisSm,rowIndex,record){if(rowIndex==0&&record.id==0){record.reject();this.store.reload();}}});Ext.ns('Content.Program');Content.Program.Layout=function(){var programPanelStatusView;var programPanel;var searchField;var categoryComboBox;var languageComboBox;var countryComboBox;var genreComboBox;var ratingCombobox;var copyrightComboBox;var countryStore;var labelsPanel;return{init:function(){var that=this;programPanel=new Content.ProgramPanel();programPanelStatusView=new Widget.GridStatusView({renderTo:'grid-status-view',parentContainer:that,store:programPanel.store});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:gettext('Search'),listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=programPanel;categoryComboBox=new Widget.SearchSelectBox({id:'categories-selectbox',name:'category',emptyText:gettext('Category'),transform:'categories-selectbox',grid:programPanel});languageComboBox=new Widget.SearchSelectBox({id:'languages-selectbox',name:'language',emptyText:gettext('Language'),transform:'languages-selectbox',grid:programPanel});countryStore=new CountryStore();countryComboBox=new Widget.SearchSelectBox({id:'country-selectbox',name:'country',emptyText:gettext('Country'),transform:'country-selectbox',grid:programPanel});genreComboBox=new Widget.SearchSelectBox({id:'genre-selectbox',name:'genre',emptyText:gettext('Genre'),transform:'genre-selectbox',grid:programPanel});ratingCombobox=new Widget.SearchSelectBox({id:'rating-selectbox',name:'rating',emptyText:gettext('Rating'),transform:'rating-selectbox',grid:programPanel});copyrightComboBox=new Widget.SearchSelectBox({id:'copyright-selectbox',name:'copyright',emptyText:gettext('Copyright Holder'),transform:'copyright-selectbox',grid:programPanel});labelsPanel=new Widget.LabelsPanel({renderTo:'labels-area',targetPanel:programPanel});labelsPanel.load();countryStore.load();programPanel.load();},clearSearchFilters:function(){delete programPanel.store.baseParams.keyword;for(var key in programPanel.store.baseParams){if(key.match("^filter_")=="filter_"){delete programPanel.store.baseParams[key];}}
programPanel.load();searchField.reset();categoryComboBox.reset();languageComboBox.reset();countryComboBox.reset();genreComboBox.reset();ratingCombobox.reset();copyrightComboBox.reset();labelsPanel.reset();}};}();Ext.ns('Content');Content.FingerprintRecordFields=[{name:'oid',type:'int'},'asset_code','title','title_eng','title_jp',{name:'created_at',type:'date',dateFormat:'Y-m-d'},{name:'release_date',type:'date',dateFormat:'Y-m-d'},'length','season','ep','seed_url_count','status','status_message','thumb_url'];Content.FingerprintPanel=function(programId){this.programId=programId;this.pageSize=40;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/originals/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'oid',totalProperty:'total',fields:Content.FingerprintRecordFields}),sortInfo:{field:'created_at',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize};Content.FingerprintPanel.superclass.constructor.call(this,{cls:'grid-original-thumb',stripeRows:true,store:this.store,enableDragDrop:true,ddGroup:'folderDDGroup',ddText:gettext('{0} selected fingerprints'),cm:new Ext.grid.ColumnModel({columns:[{id:'thumb',header:'',dataIndex:'thumb_url',sortable:false,fixed:true,menuDisabled:true,resizable:false,width:67,renderer:function(val){return'<img src="'+val+'" onerror="this.src=\''+MEDIA_URL+'/ext/resources/images/adview/common/blank_thumbnail.gif\';"/>';}},{id:'title',header:gettext('Title'),dataIndex:'title',sortable:true,width:300,editor:new Ext.form.TextField({allowBlank:false,validator:function(val){if(!val.trim())return false;return true;}})},{id:'title_eng',header:gettext('Title (English)'),dataIndex:'title_eng',sortable:true,width:300,hidden:true,editor:new Ext.form.TextField({allowBlank:false})},{id:'title_jp',header:gettext('Title (Japanses)'),dataIndex:'title_jp',sortable:true,width:300,hidden:true,editor:new Ext.form.TextField({allowBlank:false})},{id:'created_at',header:gettext('Date Created'),dataIndex:'created_at',sortable:true,type:'date',align:'center',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d')},{id:'release_date',header:gettext('Release Date'),dataIndex:'release_date',sortable:true,type:'date',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d'),editor:new Ext.form.DateField({format:'Y-m-d'})},{id:'oid',header:'OID',dataIndex:'oid',align:'center'},{id:'length',header:gettext('Length'),sortable:true,align:'right',dataIndex:'length'},{id:'seed_url_count',header:gettext('Seed URLs'),sortable:true,align:'right',dataIndex:'seed_url_count'},{id:'asset_code',header:gettext('Asset Code'),dataIndex:'asset_code',sortable:true,editor:new Ext.form.TextField({allowBlank:true}),width:120},{id:'season',header:gettext('Season Number'),sortable:true,dataIndex:'season',editor:new Ext.form.TextField({allowBlank:true})},{id:'ep',header:gettext('Episode Number'),sortable:true,dataIndex:'ep',editor:new Ext.form.TextField({allowBlank:true})},{id:'status',header:gettext('Status'),sortable:true,dataIndex:'status_message',fixed:true,width:148,renderer:function(val){if(val.error==true)
{return'<div class="status '+val.message+'" >&nbsp;</div><a href="#" class="error" ext:qtip="'+val.error_message+'" >&nbsp;</a>';}
return'<div class="status '+val.message+'" >&nbsp;</div>'}}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:false,moveEditorOnEnter:false}),listeners:{cellcontextmenu:function(grid,rowIndex,cellIndex,e){this.startEditing(rowIndex,cellIndex);e.stopEvent();},rowdblclick:function(thisGrid,rowIndex,e){var record=thisGrid.getStore().getAt(rowIndex);if(record.get('oid')){var pid=this.programId;var fid=record.get('oid');LoadingLayer.show();document.location="/content/p/"+pid+"/f/"+fid+"/s/";}},afteredit:function(e){var conn=new Ext.data.Connection();conn.request({url:'/original/video/edit/',params:{action:'update',id:e.record.id,field:e.field,value:e.value},success:function(resp,opt){e.record.commit();},failure:function(resp,opt){e.record.reject();}});}},bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,align:'left',displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Data found')})});};Ext.extend(Content.FingerprintPanel,Widget.ContentBasePanel,{onCellDblClick:function(g,row,col){},afterRender:function(){Content.FingerprintPanel.superclass.afterRender.apply(this,arguments);this.getBottomToolbar().add('-');this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_delete.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Remove Fingerprint'),handler:this.removeOriginal.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/document-excel.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Export excel'),handler:this.exportExcel.createDelegate(this)});},load:function(){this.store.load();},loadByProgramId:function(programId){this.programId=programId;this.store.baseParams.folder_id=programId;this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();var canLoad=false;if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},cancelEditing:function(field){if(!field.getRawValue()){this.stopEditing();this.store.load();}},removeOriginal:function(){var thisPanel=this;var fid=this.programId;var sm=this.getSelectionModel();var sel=sm.getSelections();var oids=new Array();for(var i=0;i<sel.length;i++){oids[i]=sel[i].data.oid;}
if(sm.hasSelection()){Ext.Msg.show({title:gettext("Remove Fingerprint"),msg:gettext('Are you really going to delete selected fingerprints?'),buttons:Ext.MessageBox.YESNOCANCEL,fn:function(btn){if(btn=='yes'){Ext.Ajax.request({url:'/original/video/remove/',params:{fid:fid,oids:oids},success:function(resp,opt){thisPanel.load();},failure:function(resp,opt){Ext.Msg.alert("Error unable to remove cluster.");},scope:this});}}});}},exportExcel:function(){if(!this.programId)return;LoadingLayer.show();var $iframe=$("#hidden_iframe");$iframe.attr("src","/folder/excel/?folder_id="+this.programId);LoadingLayer.hide();}});Ext.ns('Content.Fingerprint');Content.Fingerprint.Layout=function(){var fingerprintPanelStatusView;var fingerprintPanel;var searchField;var statusField;var programSearchField;var categoryComboBox;var languageComboBox;var countryComboBox;var genreComboBox;var ratingCombobox;var copyrightComboBox;var programList;return{init:function(programId){var that=this;fingerprintPanel=new Content.FingerprintPanel(programId);fingerprintPanelStatusView=new Widget.GridStatusView({renderTo:'grid-status-view',parentContainer:that,store:fingerprintPanel.store});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:gettext('Search'),listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=fingerprintPanel;var programPanel=null;statusField=new Widget.SearchSelectBox({emptyText:gettext('Status'),grid:fingerprintPanel,name:'status',transform:'status-selectbox'});programList=new Widget.DataNavigator({store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/programs/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:['id','title']})}),renderTo:'program-list-area',targetPanel:fingerprintPanel,navCls:'program-list',selectedId:programId,enableDnD:true,ddGroupName:'folderDDGroup',dropZone:FolderClusterDropZone,listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);if(this.targetPanel){this.targetPanel.loadByProgramId(record.id);$("div.title span").html(record.data.title);}}}});programSearchField=new Ext.ux.form.SearchField({width:190,applyTo:'program-searchkeyword',contentEl:'program-searchkeyword',emptyText:gettext('Search Programs'),listeners:{render:function(thisField){$("#program-searchfield").show();}}});programSearchField.callbackObj=programList
categoryComboBox=new Widget.SearchSelectBox({id:'categories-selectbox',width:190,name:'category',emptyText:gettext('Category'),transform:'categories-selectbox',grid:programList});languageComboBox=new Widget.SearchSelectBox({id:'languages-selectbox',name:'language',width:190,emptyText:gettext('Language'),transform:'languages-selectbox',grid:programList});countryComboBox=new Widget.SearchSelectBox({id:'country-selectbox',name:'country',width:190,emptyText:gettext('Country'),transform:'country-selectbox',grid:programList});genreComboBox=new Widget.SearchSelectBox({id:'genre-selectbox',name:'genre',width:190,emptyText:gettext('Genre'),transform:'genre-selectbox',grid:programList})
ratingCombobox=new Widget.SearchSelectBox({id:'rating-selectbox',name:'rating',width:190,emptyText:gettext('Rating'),transform:'rating-selectbox',grid:programList});copyrightComboBox=new Widget.SearchSelectBox({id:'copyright-selectbox',name:'copyright',width:190,emptyText:gettext('Copyright Holder'),transform:'copyright-selectbox',grid:programList});fingerprintPanel.loadByProgramId(programId);$("div.programs").addClass("closed");$("div.programsfilter a.btn").click(function(){var $programs=$("div.programs");if($programs.hasClass("closed")){$programs.removeClass("closed");}
else{$programs.addClass("closed");}});},clearSearchFilters:function(){if(fingerprintPanel.store.baseParams.keyword){delete fingerprintPanel.store.baseParams.keyword;}
if(fingerprintPanel.store.baseParams.filter_status){delete fingerprintPanel.store.baseParams.filter_status;}
fingerprintPanel.load();searchField.reset();statusField.reset();}}}();Ext.ns('Content');Content.SeedURLRecordFields=[{name:'id',type:'int'},{name:'title'},{name:'url'},{name:'vid'},{name:'status',type:'int'},{name:'status_message'},{name:'title'},{name:'length'},{name:'site_id'},{name:'user_id'},{name:'user_password'},{name:'created'}];Content.SeedURLPanel=function(fingerprintId){this.fingerprintId=fingerprintId;this.pageSize=40;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/seedurl/list/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:Content.SeedURLRecordFields}),sortInfo:{field:'created',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize,fingerprintId:this.fingerprintId};Content.SeedURLPanel.superclass.constructor.call(this,{loadMask:{msg:'Loading...'},viewConfig:{deferEmptyText:true,emptyText:gettext('No Seed URLs')},sm:new Ext.grid.RowSelectionModel({singleSelect:true,moveEditorOnEnter:false}),cm:new Ext.grid.ColumnModel({columns:[{header:gettext('Title'),dataIndex:'title',width:250,sortable:true},{header:gettext('Status'),dataIndex:'status_message',width:148,fixed:true,sortable:true,renderer:function(val){if(!val)return'';if(val.error==true)
{return'<div class="status '+val.message+'" >&nbsp;</div><a href="#" class="error" ext:qtip="'+val.error_message+'">&nbsp;</a>';}
return'<div class="status '+val.message+'" >&nbsp;</div>'}},{header:'URL',dataIndex:'url',width:350,minWidth:120,menuDisabled:true,hideable:false,renderer:function(val){return'<div ext:qtip="'+val+'">'+val+'</div>';},editor:new Ext.form.TextField({listeners:{blur:this.cancelEditing.createDelegate(this)}})},{header:gettext('Date'),dataIndex:'created',width:60,align:'center',sortable:true},{header:gettext('Length'),dataIndex:'length',width:60,align:'center',sortable:true},{header:gettext('Id'),dataIndex:'user_id',editor:new Ext.form.TextField(),renderer:function(val){if(!val)return'';return'<div ext:qtip="'+val+'">'+val+'</div>';},menuDisabled:true},{header:gettext('Password'),dataIndex:'user_password',editor:new Ext.form.TextField(),menuDisabled:true},{header:'vid',dataIndex:'vid',sortable:true,renderer:function(val){if(!val)return'';if(val==0)return"-";return val;},menuDisabled:true}]}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Seed URLs found')}),listeners:{cellcontextmenu:function(grid,rowIndex,cellIndex,e){this.startEditing(rowIndex,cellIndex);e.stopEvent();},beforeedit:function(e){if(e.record.get('status')>=100){Ext.Msg.alert("Warning",gettext("Completed Seed URL or the ones in process can't be deleted."));this.stopEditing();return false;}
return true;},afteredit:function(e){var that=this;var conn=new Ext.data.Connection();conn.request({url:'/seedurl/edit/',params:{action:'update',id:e.record.id,oid:that.fingerprintId,fid:that.fingerprintId,field:e.field,value:e.value},success:function(resp,opt){var result=Ext.util.JSON.decode(resp.responseText);var id=result.id;var status_message=result.status_message;e.record.status_message=status_message;e.record.id=id;e.record.data.id=id;e.record.commit();},failure:function(resp,opt){e.record.reject();}});}}});};Ext.extend(Content.SeedURLPanel,Widget.ContentBasePanel,{onCellDblClick:function(g,row,col){},afterRender:function(){Content.SeedURLPanel.superclass.afterRender.apply(this,arguments);this.getBottomToolbar().add('-');this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_add.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Add SeedURL'),handler:this.addSeedURL.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_delete.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Remove SeedURL'),handler:this.removeSeedURL.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/document-excel.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Export excel'),handler:this.exportExcel.createDelegate(this)});},load:function(){this.store.load();},loadByFingerprintId:function(fid){this.fingerprintId=fid;this.store.baseParams.fingerprint_id=fid;this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},addSeedURL:function(){this.stopEditing();var Record=Ext.data.Record.create(Content.SeedURLRecordFields);this.store.insert(0,new Record({id:0,url:'http://'},0));this.startEditing(0,2);this.getSelectionModel().selectFirstRow();},removeSeedURL:function(){var thisPanel=this;var sm=this.getSelectionModel();var sel=sm.getSelected();if(sm.hasSelection()){if(sel.data.status>=100){Ext.Msg.alert("Warning",gettext("Completed Seed URL or the ones in process can't be deleted."));return;}
Ext.Msg.show({title:'Remove seed url',buttons:Ext.MessageBox.YESNOCANCEL,msg:'Remove "'+sel.data.url+'"? ',fn:function(btn){if(btn=='yes'){Ext.Ajax.request({url:'/seedurl/remove/',params:{id:sel.data.id},success:function(resp,opt){var result=Ext.util.JSON.decode(resp.responseText);if(result.success){thisPanel.store.remove(sel);}
else{Ext.Msg.alert("",result.msg);}},failure:function(resp,opt){Ext.Msg.alert("error","Error unable to remove seed url");},scope:this});}}});}},cancelEditing:function(field){if(!field.getRawValue()||field.getRawValue()=='http://'){this.stopEditing();this.store.load();}},exportExcel:function(){if(!this.fingerprintId)return;LoadingLayer.show();var $iframe=$("#hidden_iframe");$iframe.attr("src","/seedurl/export/?oid="+this.fingerprintId);LoadingLayer.hide();}});Ext.ns('Content.SeedURL');Content.SeedURL.Layout=function(){var seedURLPanel;var seedURLPanelStatusView;var searchField;var statusField;var fpNavigator;return{init:function(programId,fingerprintId){var that=this;seedURLPanel=new Content.SeedURLPanel(fingerprintId);seedURLPanelStatusView=new Widget.GridStatusView({renderTo:'grid-status-view',parentContainer:that,store:seedURLPanel.store});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:'Search',listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=seedURLPanel;statusField=new Widget.SearchSelectBox({emptyText:'Status',name:'status',grid:seedURLPanel,transform:'status-selectbox'});fpNavigator=new Widget.DataNavigator({store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/originals/json/?folder_id='+programId}),reader:new Ext.data.JsonReader({root:'list',id:'oid',totalProperty:'total',fields:['oid','title']})}),renderTo:'navigator-list-area',targetPanel:seedURLPanel,navCls:'program-list',selectedId:fingerprintId,listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);if(this.targetPanel){this.targetPanel.loadByFingerprintId(record.id);$("div.title span").html(record.data.title);}}}});var fpSearchField=new Ext.ux.form.SearchField({width:190,applyTo:'fp-searchkeyword',contentEl:'fp-searchkeyword',emptyText:'Search Fingerprints',listeners:{render:function(thisField){$("#fp-searchfield").show();}}});fpSearchField.callbackObj=fpNavigator;seedURLPanel.loadByFingerprintId(fingerprintId);},clearSearchFilters:function(){if(seedURLPanel.store.baseParams.keyword){delete seedURLPanel.store.baseParams.keyword;}
if(seedURLPanel.store.baseParams.filter_status){delete seedURLPanel.store.baseParams.filter_status;}
searchField.reset();statusField.reset();seedURLPanel.load();}}}();var VideoRecordFields=[{name:'vid',type:'int'},{name:'title'},{name:'date',type:'date',dateFormat:'Y-m-d'},{name:'view_count'},{name:'share_count'},{name:'cmt_count'},{name:'embed_html'},{name:'site_name'},{name:'is_seedurl'},{name:'alive',type:'int'}];var VideoListPanel=function(){this.pageSize=20;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/video/list/'}),reader:new Ext.data.JsonReader({root:'list',id:'vid',totalProperty:'total',fields:VideoRecordFields}),sortInfo:{field:'date',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize}
VideoListPanel.superclass.constructor.call(this,{id:'video_list_panel',applyTo:'video_list',store:this.store,layout:'fit',autoWidth:true,autoHeight:true,viewConfig:{forceFit:true},cm:new Ext.grid.ColumnModel({columns:[new Ext.grid.RowNumberer(),{id:'site',header:'Site',dataIndex:'site_name',align:'center',width:90,sortable:true},{id:'title',header:'Title',dataIndex:'title',width:290,sortable:true},{id:'date',header:'Date',dataIndex:'date',type:'date',width:90,renderer:Ext.util.Format.dateRenderer('Y-m-d'),sortable:true},{id:'view_count',header:'View',dataIndex:'view_count',width:60,sortable:true},{id:'share_count',header:'Shared',dataIndex:'share_count',width:60,sortable:true},{id:'cmt_count',header:'Comments',dataIndex:'cmt_count',width:60,sortable:true},{id:'alive',header:'Alive',dataIndex:'alive',width:60,align:'center',renderer:function(val){return val==1?'Y':'N';},sortable:true},{id:'is_seedurl',header:'Seed url',dataIndex:'is_seedurl',width:60,align:'center',renderer:function(val){return val==1?'Y':'N';},sortable:true}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:'No Videos'})});this.getSelectionModel().on('rowselect',this.rowSelect,this);this.getView().getRowClass=function(record,index,rowParams,store){var alive=record.get('alive');if(alive!=1){return"row-deadlink";}
return"";};};Ext.extend(VideoListPanel,Ext.grid.GridPanel,{rowSelect:function(selModel,rowIndex,record){var records=this.getSelectionModel().getSelections();if(records.length==1){var vid=record.get('vid');var embed_html=record.get('embed_html');if(vid&&embed_html){$("#video_player_container").load("/video/player/embed/"+vid+"/");}}},load:function(){this.store.load();},loadByDVid:function(dvid){this.store.baseParams.dvid=dvid;this.store.load();}});var VideoPlayerPanel=function(conf){var config={id:'video-player-panel',region:"east",layout:"fit",loadMash:{msg:"Loading..."},margins:"0 5 0 5",width:420,minWidth:420,height:620,frame:false,split:true,collapsible:false,viewConfig:{forceFit:true},autoScroll:true};Ext.apply(config,conf||{});VideoPlayerPanel.superclass.constructor.call(this,config);};Ext.extend(VideoPlayerPanel,Ext.Panel,{loadByVideoId:function(dvid){if(dvid==this.dvid)return;this.dvid=dvid;var params={dvid:this.dvid};if(this.rendered){this.load({url:'/video/player/',params:params,scripts:true});}}});Ext.ns("Analytics");Analytics.ChartFilter=function(p,i,t,ids){this.MAX_FILTER_SIZE=7;this.SEPARATOR="|";this.path=p;this.id=i;this.viewType='view_count';this.type=t;this.idList=ids;this.from=undefined;this.to=undefined;this.getSettingsUrl=function(){var url="/analytics/chart/settings/"+this.path+"/"+this.id+"/"+this.type+"/"+this.idList+"/"+this.viewType+"/";return url;};var self=this;this.updateDataTable=function(start,end){if(this.tid){Ext.Ajax.abort(this.tid);}
var handleSuccess=function(o){this.tid=null;if(o.responseText!==undefined){Ext.get('datatable-area').update(o.responseText);}}
var handleFailure=function(o){this.tid=null;}
if(start){self.from=start;}
if(end){self.to=end;}
this.tid=Ext.Ajax.request({url:'/analytics/data_table/'+self.path+'/'+self.id+'/'+
self.type+'/'+encodeURIComponent(self.idList)+'/'+
self.from+'/'+self.to+'/'+self.viewType+'/',method:'GET',success:handleSuccess,failure:handleFailure,scope:this});};this.loadChartItemList=function(){$.ajax({url:'/analytics/chart/item/list/'+self.type+"/"+encodeURIComponent(self.idList)+"/",dataType:'html',success:function(res){$("#cart-item-list").html(res);}});}
this.changeViewType=function(viewType){self.viewType=viewType;reloadSettings(this.getSettingsUrl());};$("#data-filter-form input:radio[name=datafilter_type]").click(function(){var $this=$(this);if($this.val()=='region'){$("#datafilter-area-site").hide();$("#datafilter-area-region").show();}
else{$("#datafilter-area-site").show();$("#datafilter-area-region").hide();}});$("#data-filter-form div.btn img").click(function(){var $form=$("#data-filter-form");var $type=$form.find("input:radio[name=datafilter_type]:checked");self.type=$type.val();if(self.type=='region'){var $list=$form.find("input:checkbox[name=region_id]:checked");}
else if(self.type=='site'){var $list=$form.find("input:checkbox[name=site_id]:checked");}
var list=new Array();$list.each(function(index){if(index<=self.MAX_FILTER_SIZE){var value=$(this).val();list.push(value);}
else{alert('Max 7 filters');}});if(list.length!=0){self.idList=list.join('|');$("#data-filter").hide();self.loadChartItemList();reloadSettings(self.getSettingsUrl());self.updateDataTable();}
return false;});};Ext.ns("Analytics");Analytics.SiteChartFilter=function(p,i){this.MAX_FILTER_SIZE=7;this.SEPARATOR="|";this.path=p;this.id=i;this.viewType='view_count';this.from=undefined;this.to=undefined;this.getSettingsUrl=function(){var url="/analytics/chart/settings/site/"+this.path+"/"+this.id+"/"+this.viewType+"/";return url;};var self=this;this.changeViewType=function(viewType){self.viewType=viewType;reloadSettings(this.getSettingsUrl());};};Ext.ns('Analytics');Analytics.TimetrackList=function(conf){var config={applyTo:'timetrack-items',listeners:{selectionchange:function(thisView,selections){if(selections&&selections.length<1){return;}
var selection=selections[0];var record=this.getRecord(selection);this.timetrackCt.loadVideoByDvid(record.data.dvid,record.data.sid);this.timetrackCt.originalView.clearSelections();},containerclick:function(thisView,e){return false;}}};Ext.apply(config,conf||{});var that=this;this.tpl=new Ext.XTemplate('<ul>','<tpl for=".">','<li class="timetrack-item" ><div>','{[this.timetrack(values)]}','</div></li>','</tpl>','</ul>',{timetrack:function(item){var basicStartRatio=0;var basicEndRatio=0;var json=that.store.reader.jsonData;if(json.basicTimetrack){basicStartRatio=json.basicTimetrack.startratio;basicEndRatio=json.basicTimetrack.endratio;}
return String.format('<div {0}><span class="bg_relevant" style="left:{1}%;width:{2}%;"></span>'+'<span class="timedata" style="left:{3}%;width:{4}%;"></span></div>',item.basic==true?'class="most_relevant"':'',basicStartRatio,basicEndRatio,item.timetrack.startratio,item.timetrack.endratio);}});Analytics.TimetrackList.superclass.constructor.call(this,config);};Ext.extend(Analytics.TimetrackList,Ext.DataView,{singleSelect:true,itemSelector:'li.timetrack-item',selectedClass:'selected',load:function(){this.store.load();}});Ext.ns('Analytics');Analytics.TimetrackRecordFields=[{name:'id'},{name:'sid_type'},{name:'sid',type:'int'},{name:'dvid',type:'int'},{name:'timetrack'},{name:'title'},{name:'length'},{name:'video_count'},{name:'view_count'},{name:'share_count'},{name:'cmt_count'},{name:'total'},{name:'date'}];Analytics.TimetrackContainer=function(config){Ext.apply(this,config);this.sid=null;this.dvid=null;this.pageSize=20;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/foldercluster/timetrack/list/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:Analytics.TimetrackRecordFields}),sortInfo:{field:'timetrack',direction:'ASC'},remoteSort:true});this.originalView=new Ext.DataView({applyTo:'original-view',store:new Ext.data.SimpleStore({'id':0,fields:Analytics.TimetrackRecordFields}),tpl:new Ext.XTemplate('<tpl for=".">','<div class="select-item">','<div class="timetrack-item">','{[this.timetrack(values)]}','</div>','<div class="original-title">{title}</div>','</div>','<div class="export-excel"><a href="#" onclick="exportExcel();return false;">'+gettext('Export excel')+'</a></div>','</tpl>',{timetrack:function(item){if(typeof item.timetrack=='undefined')return'';return String.format('<div><span class="bg_relevant" style="left:{0}%;width:{1}%;"></span>'+'<span class="timedata" style="left:{2}%;width:{3}%;"></span></div>',item.timetrack.startratio,item.timetrack.endratio,item.timetrack.startratio,item.timetrack.endratio);}}),timetrackCt:this,singleSelect:true,itemSelector:'div.select-item',selectedClass:'selected',listeners:{selectionchange:function(thisView,selections){if(selections&&selections.length<1){return;}
var selection=selections[0];var record=this.getRecord(selection);this.timetrackCt.loadVideoByDvid(record.data.dvid,record.data.sid);this.timetrackCt.timetrackList.clearSelections();},containerclick:function(thisView,e){return false;}}});this.timetrackList=new Analytics.TimetrackList({store:this.store,timetrackCt:this});this.timetrackPaging=new Ext.PagingToolbar({store:this.store,renderTo:'timetrack-paging'});this.store.baseParams={limit:this.pageSize};this.store.baseParams.clusterId=this.clusterId;this.bindStore(true);this.store.load();};Ext.extend(Analytics.TimetrackContainer,Ext.util.Observable,{loadByClusterId:function(clusterId){if(clusterId!=this.clusterId){this.clusterId=clusterId;this.store.baseParams.clusterId=this.clusterId;this.store.load();}},loadVideoByDvid:function(dvid,sid){if(this.dvid!=dvid||this.sid!=sid){this.videoPanel.loadByVideoId(dvid,sid);this.dvid=dvid;this.sid=sid;}},bindStore:function(initial){if(!initial){this.store.un('load',this.onLoadStore,this);}
else{this.store.on('load',this.onLoadStore,this);}},reload:function(){this.store.baseParams.start=0;this.store.load();},onLoadStore:function(){this.onLoadOriginalStore();var store=this.store;var total_all=store.reader.jsonData['total_all'];this.dvid=null;if(store.getTotalCount()<=0){if(total_all=='0'){this.videoPanel.loadByVideoId(-1,this.sid);}
else{this.videoPanel.loadByVideoId(-2,this.sid);}
this.timetrackPaging.hide();}
else{if(store.lastOptions.params&&store.lastOptions.params.start>0){this.timetrackList.select(0);}
else{this.originalView.select(0);}
this.timetrackPaging.show();}},onLoadOriginalStore:function(){var original=this.store.reader.jsonData.original;var Record=Ext.data.Record.create(Analytics.TimetrackRecordFields);var record=new Record(original,0);var data=new Ext.util.MixedCollection();data.add(0,record);this.originalView.store.data=data;this.originalView.refresh();if(this.sid!==original.sid){this.originalView.clearSelections();this.timetrackList.clearSelections();}},onDestroy:function(){this.bindStore(null);TimetrackContainer.superclass.onDestroy.call(this);}});Ext.ns('Analytics');Analytics.TopTabView=function(conf){var tpl=new Ext.XTemplate('<div class="tab-navi">','<tpl for=".">','<a class="tab-item" href="#">{name}</a>','</tpl>','</ul>');var config={renderTo:'tab-navi-area',tpl:tpl,selectedClass:'selected',itemSelector:'a.tab-item',singleSelect:true,listeners:{click:function(thisDataView,index,node,e){var record=this.store.getAt(index);var $contents=$("#contents-"+record.data.id);if(record.data.id!='info'){var url=record.data.url;if(this.params){var param=eval("this.params.obj."+this.params.attr);url=String.format(url,param);}
$.ajax({url:url,dataType:'html',success:function(data){$contents.html(data);$("div.contents-area").not($contents).hide();$contents.show();}});}
else{$("div.contents-area").not($contents).hide();$contents.show();}}}};Ext.apply(config,conf||{});Analytics.TopTabView.superclass.constructor.call(this,config);this.select(0);};Ext.extend(Analytics.TopTabView,Ext.DataView,{});Ext.ns('Analytics');Analytics.ProgramRecordFields=[{name:'id',type:'int'},{name:'name'},'title_eng','title_jp','program_code',{name:'type',type:'int'},{name:'release_date',type:'date',dateFormat:'Y-m-d'},{name:'category'},{name:'countries'},{name:'languages'},{name:'labels'},{name:'cluster_count'},{name:'video_count'},{name:'view_count'},{name:'share_count'},{name:'cmt_count'}];Analytics.ProgramPanel=function(){this.pageSize=40;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/folder/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:Analytics.ProgramRecordFields}),sortInfo:{field:'release_date',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize};this.categoryStore=new FolderCategoryStore();this.labelStore=new FolderLabelStore();this.categoryStore.load();this.labelStore.load();Analytics.ProgramPanel.superclass.constructor.call(this,{cls:'grid-program',clicksToEdit:0,store:this.store,cm:new Ext.grid.ColumnModel({columns:[{id:'program_code',header:gettext('Program Code'),dataIndex:'program_code',sortable:true,width:90,hideable:true,hidden:true,editor:new Ext.form.TextField({allowBlank:true})},{id:'name',header:gettext('Title'),dataIndex:'name',sortable:true,width:300,hideable:false,editor:new Ext.form.TextField({allowBlank:false,validator:function(val){if(!val.trim())return false;return true;}})},{id:'title_eng',header:gettext('Title (English)'),dataIndex:'title_eng',sortable:true,hidden:true,width:300,editor:new Ext.form.TextField({allowBlank:false})},{id:'title_jp',header:gettext('Title (Japan)'),dataIndex:'title_jp',width:300,sortable:true,hidden:true,editor:new Ext.form.TextField({allowBlank:false})},{id:'release_date',header:gettext('Release Date'),dataIndex:'release_date',sortable:true,type:'date',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d'),editor:new Ext.form.DateField({format:'Y-m-d'})},{id:'cluster_count',header:gettext('Clusters'),sortable:true,dataIndex:'cluster_count',width:90,summaryType:'sum'},{id:'video_count',header:gettext('Videos'),sortable:true,dataIndex:'video_count',width:90,summaryType:'sum'},{id:'view_count',header:gettext('Views'),sortable:true,dataIndex:'view_count',width:90,summaryType:'sum'},{id:'share_count',header:gettext('Shared'),sortable:true,dataIndex:'share_count',width:90,summaryType:'sum'},{id:'cmt_count',header:gettext('Comments'),sortable:true,dataIndex:'cmt_count',width:90,summaryType:'sum'},{id:'category',header:gettext('Category'),dataIndex:'category',sortable:true,width:90,renderer:ComboboxRenderer(this.categoryStore),editor:new FolderCategoryComboBox({store:this.categoryStore})},{id:'labels',header:gettext('Labels'),dataIndex:'labels',sortable:true,width:90,renderer:ComboboxRenderer(this.labelStore),editor:new FolderLabelComboBox({store:this.labelStore})},{id:'country',header:gettext('Country'),dataIndex:'countries',sortable:true,width:90,editor:new Ext.form.TextField({allowBlank:true})},{id:'language',header:gettext('Language'),dataIndex:'languages',sortable:true,width:90,editor:new Ext.form.TextField({allowBlank:true})}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true,moveEditorOnEnter:false,listeners:{rowdeselect:this.rowdeselect.createDelegate(this)}}),listeners:{cellcontextmenu:function(grid,rowIndex,cellIndex,e){this.startEditing(rowIndex,cellIndex);e.stopEvent();},rowdblclick:function(grid,rowIndex,e){var record=grid.getStore().getAt(rowIndex);if(record.get('id')){var pid=record.get('id');LoadingLayer.show();document.location="/analytics/p/"+pid+"/c/";}},afteredit:function(e){var conn=new Ext.data.Connection();conn.request({url:'/folder/edit/',params:{action:'update',id:e.record.id,field:e.field,value:e.value},success:function(resp,opt){var result=Ext.util.JSON.decode(resp.responseText);var id=result.id;e.record.id=id;e.record.commit();},failure:function(resp,opt){e.record.reject();}});}},bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,align:'left',displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Program found')}),plugins:[new Ext.ux.plugins.GroupHeaderGrid({rows:[[{id:"info",header:gettext("Info"),align:"center",colspan:5},{id:"statistics",header:gettext("Statistics"),align:"center",colspan:5},{id:"metadata",header:gettext("Metadata"),align:"center",colspan:4}]]}),new Ext.ux.grid.HybridSummary()]});this.getView().getRowClass=function(record,index,rowParams,store){var type=record.get('type');if(type==2){return"default-folder";}
return"";}};Ext.extend(Analytics.ProgramPanel,Widget.ContentBasePanel,{onCellDblClick:function(g,row,col){},afterRender:function(){Analytics.ProgramPanel.superclass.afterRender.apply(this,arguments);this.getBottomToolbar().add('-');this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_add.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Add Program'),handler:this.addProgram.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_delete.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Remove Program'),handler:this.removeProgram.createDelegate(this)});},load:function(){this.store.load();},reload:function(){this.store.reload();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filterByLabel:function(labelRecord){if(labelRecord.data.id>0){this.store.baseParams['filter_labels']=labelRecord.data.id;this.store.baseParams['value_filter_labels']=labelRecord.data.name;}
else{delete this.store.baseParams['filter_labels'];delete this.store.baseParams['value_filter_labels'];}
this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();var canLoad=false;if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},addProgram:function(){this.stopEditing();var Record=Ext.data.Record.create(Content.ProgramRecordFields);var defaultFields={id:0};this.store.insert(0,new Record(defaultFields,0));this.startEditing(0,1);this.getSelectionModel().selectFirstRow();},removeProgram:function(){var thisPanel=this;var sm=this.getSelectionModel();var sel=sm.getSelected();if(sm.hasSelection()){if(sel.data.id==0){this.store.reload();return;}
if(sel.data.type==2){Ext.Msg.alert(gettext("Warning"),gettext("Default folder can't be removed."));return;}
if(sel.data.cluster_count>0){Ext.Msg.alert(gettext("Warning"),gettext("The program with cluster can't be deleted <br /> If you wish to delete,move cluster to another program"));return;}
Ext.Msg.show({title:gettext('Remove Program'),buttons:Ext.MessageBox.YESNOCANCEL,msg:'Remove "'+sel.data.title+'"?',fn:function(btn){if(btn=='yes'){Ext.Ajax.request({url:'/folder/remove/',params:{id:sel.id},success:function(resp,opt){thisPanel.store.remove(sel);},failure:function(resp,opt){Ext.Msg.alert("Error unable to remove program");},scope:this});}}});}},rowdeselect:function(thisSm,rowIndex,record){if(rowIndex==0&&record.id==0){record.reject();this.store.reload();}}});Ext.ns('Analytics.Program');Analytics.Program.Layout=function(){var programPanelStatusView;var programPanel;var searchField;var categoryComboBox;var languageComboBox;var countryComboBox;var genreComboBox;var ratingCombobox;var copyrightComboBox;var countryStore;var labelsPanel;var topTabView;return{init:function(params){var groupId=params.groupId;var enableReport=params.enableReport;var that=this;programPanel=new Analytics.ProgramPanel();programPanel.groupId=groupId;programPanelStatusView=new Widget.GridStatusView({renderTo:'grid-status-view',parentContainer:that,store:programPanel.store});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:gettext('Search'),listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=programPanel;categoryComboBox=new Widget.SearchSelectBox({id:'categories-selectbox',name:'category',grid:programPanel,emptyText:gettext('Category'),transform:'categories-selectbox'});languageComboBox=new Widget.SearchSelectBox({id:'languages-selectbox',name:'language',grid:programPanel,emptyText:gettext('Language'),transform:'languages-selectbox'});countryStore=new CountryStore();countryComboBox=new Widget.SearchSelectBox({id:'country-selectbox',name:'country',emptyText:gettext('Country'),transform:'country-selectbox',grid:programPanel});genreComboBox=new Widget.SearchSelectBox({id:'genre-selectbox',name:'genre',grid:programPanel,emptyText:gettext('Genre'),transform:'genre-selectbox'});ratingCombobox=new Widget.SearchSelectBox({id:'rating-selectbox',name:'rating',grid:programPanel,emptyText:gettext('Rating'),transform:'rating-selectbox'});copyrightComboBox=new Widget.SearchSelectBox({id:'copyright-selectbox',name:'copyright',grid:programPanel,emptyText:gettext('Copyright Holder'),transform:'copyright-selectbox'});labelsPanel=new Widget.LabelsPanel({renderTo:'labels-area',targetPanel:programPanel});var tabViewItems=[['info',gettext('Information')],['stats',gettext('Statistics'),'/analytics/stats/group/my/'],['intelli',gettext('Intelligence'),'/analytics/intelli/group/my/']];if(enableReport=='True'){tabViewItems[tabViewItems.length]=['report',gettext('Report'),'/analytics/report/group/{0}/']}
topTabView=new Analytics.TopTabView({params:{obj:programPanel,attr:'groupId'},store:new Ext.data.SimpleStore({fields:['id','name','url'],data:tabViewItems,autoLoad:false})});labelsPanel.load();countryStore.load();programPanel.load();},clearSearchFilters:function(){delete programPanel.store.baseParams.keyword;for(var key in programPanel.store.baseParams){if(key.match("^filter_")=="filter_"){delete programPanel.store.baseParams[key];}}
programPanel.load();searchField.reset();categoryComboBox.reset();languageComboBox.reset();countryComboBox.reset();genreComboBox.reset();ratingCombobox.reset();copyrightComboBox.reset();labelsPanel.reset();},reloadStores:function(){programPanel.reload();}};}();Ext.ns('Analytics');Analytics.ClusterRecordFields=[{name:'id',type:'int'},'cid','asset_code','title','title_eng','title_jp',{name:'release_date',type:'date',dateFormat:'Y-m-d'},{name:'season_number',type:'int'},{name:'episode_number',type:'int'},{name:'country'},{name:'language'},{name:'sid_type'},{name:'sid',type:'int'},{name:'full_sid'},{name:'length'},{name:'total'},{name:'date',type:'date',dateFormat:'Y-m-d'},{name:'video_count'},{name:'view_count'},{name:'share_count'},{name:'cmt_count'},'thumb_url'];Analytics.ClusterPanel=function(programId){this.programId=programId;this.pageSize=40;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/foldercluster/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:Analytics.ClusterRecordFields}),sortInfo:{field:'date',direction:'DESC'},remoteSort:true});this.store.baseParams={limit:this.pageSize};this.countryStore=new CountryStore();this.langStore=new LanguageStore();Analytics.ClusterPanel.superclass.constructor.call(this,{cls:'grid-original-thumb',store:this.store,enableDragDrop:true,ddGroup:'folderDDGroup',ddText:gettext('{0} selected clusters'),cm:new Ext.grid.ColumnModel({columns:[{id:'thumb',header:'',dataIndex:'thumb_url',sortable:false,fixed:true,menuDisabled:true,resizable:false,width:67,renderer:function(val){return'<img src="'+val+'" onerror="this.src=\''+MEDIA_URL+'/ext/resources/images/adview/common/blank_thumbnail.gif\';"/>';}},{id:'asset_code',header:gettext('Asset Code'),dataIndex:'asset_code',sortable:true,width:120,hidden:true,editor:new Ext.form.TextField({allowBlank:true})},{id:'title',header:gettext('Title'),dataIndex:'title',sortable:true,width:300,editor:new Ext.form.TextField({allowBlank:false,validator:function(val){if(!val.trim())return false;return true;}})},{id:'title_eng',header:gettext('Title (English)'),dataIndex:'title_eng',sortable:true,width:300,hidden:true,editor:new Ext.form.TextField({allowBlank:false})},{id:'title_jp',header:gettext('Title (Japanese)'),dataIndex:'title_jp',sortable:true,hidden:true,width:300,editor:new Ext.form.TextField({allowBlank:false})},{id:'date',header:gettext('Date Created'),dataIndex:'date',sortable:true,type:'date',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d')},{id:'length',header:gettext('Length'),sortable:true,align:'center',width:90,dataIndex:'length'},{id:'total',header:gettext('Segments'),sortable:true,width:90,dataIndex:'total'},{id:'video_count',header:gettext('Videos'),sortable:true,dataIndex:'video_count',width:90,summaryType:'sum'},{id:'view_count',header:gettext('Views'),sortable:true,dataIndex:'view_count',width:90,summaryType:'sum'},{id:'share_count',header:gettext('Shared'),sortable:true,dataIndex:'share_count',width:90,summaryType:'sum'},{id:'cmt_count',header:gettext('Comments'),sortable:true,dataIndex:'cmt_count',width:90,summaryType:'sum'},{id:'sid',header:'SID',dataIndex:'full_sid',align:'center',width:90,sortable:false},{id:'release_date',header:gettext('Release Date'),dataIndex:'release_date',width:80,sortable:true,type:'date',renderer:Ext.util.Format.dateRenderer('Y-m-d'),editor:new Ext.form.DateField({format:'Y-m-d'})},{id:'season_number',header:gettext('Season Number'),dataIndex:'season_number',sortable:true,width:90,editor:new Ext.form.TextField()},{id:'episode_number',header:gettext('Episode Number'),dataIndex:'episode_number',sortable:true,width:90,editor:new Ext.form.TextField()}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:false,moveEditorOnEnter:false}),listeners:{cellcontextmenu:function(grid,rowIndex,cellIndex,e){this.startEditing(rowIndex,cellIndex);e.stopEvent();},rowdblclick:function(thisGrid,rowIndex,e){var record=thisGrid.getStore().getAt(rowIndex);if(record.get('id')){var pid=this.programId;var cid=record.get('id');LoadingLayer.show();document.location="/analytics/p/"+pid+"/c/"+cid+"/s/";}},afteredit:function(e){var conn=new Ext.data.Connection();conn.request({url:'/foldercluster/edit/',params:{action:'update',id:e.record.id,field:e.field,value:e.value},success:function(resp,opt){e.record.commit();},failure:function(resp,pot){e.record.reject();}});}},bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,align:'left',displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Program found')}),plugins:[new Ext.ux.plugins.GroupHeaderGrid({rows:[[{id:"info",header:gettext("Info"),align:"center",colspan:8},{id:"statistics",header:gettext("Statistics"),align:"center",colspan:4},{id:"metadata",header:gettext("Metadata"),align:"center",colspan:4}]]}),new Ext.ux.grid.HybridSummary()]});};Ext.extend(Analytics.ClusterPanel,Widget.ContentBasePanel,{onCellDblClick:function(g,row,col){},afterRender:function(){Analytics.ClusterPanel.superclass.afterRender.apply(this,arguments);this.getBottomToolbar().add('-');this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/table_delete.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Remove Cluster'),handler:this.removeOriginal.createDelegate(this)});this.getBottomToolbar().add({icon:MEDIA_URL+'/ext/resources/images/adview/document-excel.png',cls:'x-btn-text-icon',xtype:'tbbutton',text:gettext('Export excel'),handler:this.exportExcel.createDelegate(this)});},load:function(){this.store.load();},reload:function(){this.store.reload();},loadByProgramId:function(programId){this.programId=programId;this.store.baseParams.folderId=programId;this.store.load();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},filter:function(field){var filterParamName='filter_'+field.getName();if(this.store.baseParams[filterParamName]){if(this.store.baseParams[filterParamName]!=field.getValue())canLoad=true;}
else if(field.getValue()){canLoad=true;}
if(canLoad){this.store.baseParams[filterParamName]=field.getValue();this.store.baseParams['value_'+filterParamName]=field.getRawValue();this.store.load();}},cancelEditing:function(field){if(!field.getRawValue()){this.stopEditing();this.store.load();}},removeOriginal:function(){var thisPanel=this;var sm=this.getSelectionModel();var sel=sm.getSelections();var fid=this.programId;var cids=new Array();for(var i=0;i<sel.length;i++){cids[i]=sel[i].data.cid;}
if(sm.hasSelection()){Ext.Msg.show({title:gettext("Remove Cluster"),buttons:Ext.MessageBox.YESNOCANCEL,msg:gettext('Are you really going to delete selected clusters?'),fn:function(btn){if(btn=='yes'){Ext.Ajax.request({url:'/foldercluster/remove/',params:{fid:fid,cids:cids},success:function(resp,opt){thisPanel.load();},failure:function(resp,opt){Ext.Msg.alert("Error unable to remove cluster.");},scope:this});}}});}},exportExcel:function(){if(!this.programId)return;LoadingLayer.show();var $iframe=$("#hidden_iframe");$iframe.attr("src","/folder/excel/?folder_id="+this.programId);LoadingLayer.hide();}});Ext.ns('Analytics.Cluster');Analytics.Cluster.Layout=function(){var clusterPanelStatusView;var clusterPanel;var searchField;var programSearchField;var categoryComboBox;var languageComboBox;var countryComboBox;var genreComboBox;var ratingCombobox;var copyrightComboBox;var programList;var topTabView;return{init:function(params){var programId=params.programId;var enableReport=params.enableReport;var that=this;clusterPanel=new Analytics.ClusterPanel(programId);clusterPanelStatusView=new Widget.GridStatusView({renderTo:'grid-status-view',parentContainer:that,store:clusterPanel.store});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:gettext('Search'),listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=clusterPanel;programList=new Widget.DataNavigator({store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/content/programs/json/?limit=500'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:['id','title']})}),renderTo:'program-list-area',targetPanel:clusterPanel,selectedId:programId,navCls:'program-list',enableDnD:true,ddGroupName:'folderDDGroup',dropZone:FolderClusterDropZone,listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);if(this.targetPanel){this.targetPanel.loadByProgramId(record.id);$("div.title span").html(record.data.title);}}}});programSearchField=new Ext.ux.form.SearchField({width:190,applyTo:'program-searchkeyword',contentEl:'program-searchkeyword',emptyText:gettext('Search Programs'),listeners:{render:function(thisField){$("#program-searchfield").show();}}});programSearchField.callbackObj=programList
categoryComboBox=new Widget.SearchSelectBox({id:'categories-selectbox',width:190,name:'category',emptyText:gettext('Category'),transform:'categories-selectbox',grid:programList});languageComboBox=new Widget.SearchSelectBox({id:'languages-selectbox',name:'language',width:190,emptyText:gettext('Language'),transform:'languages-selectbox',grid:programList});countryComboBox=new Widget.SearchSelectBox({id:'country-selectbox',name:'country',width:190,emptyText:gettext('Country'),transform:'country-selectbox',grid:programList});genreComboBox=new Widget.SearchSelectBox({id:'genre-selectbox',name:'genre',width:190,emptyText:gettext('Genre'),transform:'genre-selectbox',grid:programList})
ratingCombobox=new Widget.SearchSelectBox({id:'rating-selectbox',name:'rating',width:190,emptyText:gettext('Rating'),transform:'rating-selectbox',grid:programList});copyrightComboBox=new Widget.SearchSelectBox({id:'copyright-selectbox',name:'copyright',width:190,emptyText:gettext('Copyright Holder'),transform:'copyright-selectbox',grid:programList});clusterPanel.loadByProgramId(programId);var tabViewItems=[['info',gettext('Information')],['stats',gettext('Statistics'),'/analytics/stats/folder/{0}/'],['intelli',gettext('Intelligence'),'/analytics/intelli/folder/{0}/']];if(enableReport=='True'){tabViewItems[tabViewItems.length]=['report',gettext('Report'),'/analytics/report/folder/{0}/'];}
topTabView=new Analytics.TopTabView({params:{obj:clusterPanel,attr:'programId'},store:new Ext.data.SimpleStore({fields:['id','name','url'],data:tabViewItems,autoLoad:false})});$("div.programs").addClass("closed");$("div.programsfilter a.btn").click(function(){var $programs=$("div.programs");if($programs.hasClass("closed")){$programs.removeClass("closed");}
else{$programs.addClass("closed");}});},clearSearchFilters:function(){if(clusterPanel.store.baseParams.keyword){delete clusterPanel.store.baseParams.keyword;}
clusterPanel.load();searchField.reset();},reloadStores:function(){clusterPanel.reload();}}}();Ext.ns('Analytics.Segment');Analytics.Segment.Layout=function(){var videoPanel;var searchField;var topTabView;var clNavigator;var timetrackContainer;return{init:function(programId,clusterId){videoPanel=new Analytics.VideoPanel();timetrackContainer=new Analytics.TimetrackContainer({clusterId:clusterId,videoPanel:videoPanel});searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:'Search',listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=videoPanel;clNavigator=new Widget.DataNavigator({store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/foldercluster/?folderId='+programId}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:['id','title']})}),renderTo:'navigator-list-area',navCls:'program-list',selectedId:clusterId,listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);timetrackContainer.loadByClusterId(record.id);$("div.title span").html(record.data.title);}}});clSearchField=new Ext.ux.form.SearchField({width:190,applyTo:'cl-searchkeyword',contentEl:'cl-searchkeyword',emptyText:'Search Clusters',listeners:{render:function(thisField){$("#cl-searchfield").show();}}});clSearchField.callbackObj=clNavigator;topTabView=new Analytics.TopTabView({params:{obj:timetrackContainer,attr:'clusterId'},store:new Ext.data.SimpleStore({fields:['id','name','url'],data:[['info',gettext('Information')],['stats',gettext('Statistics'),'/analytics/stats/cluster/{0}/'],['intelli',gettext('Intelligence'),'/analytics/intelli/cluster/{0}/']],autoLoad:false})});},reloadStores:function(){timetrackContainer.reload();},getTimetrackContainer:function(){return timetrackContainer;}}}();Ext.ns('Analytics');Analytics.VideoRecordFields=[{name:'vid',type:'int'},{name:'title'},{name:'date',type:'date',dateFormat:'Y-m-d'},{name:'view_count'},{name:'share_count'},{name:'cmt_count'},{name:'embed_html'},{name:'site_name'},{name:'site_logo'},{name:'region_name'},{name:'region_logo'},{name:'is_seedurl'},{name:'alive',type:'int'},{name:'player_count',type:'int'}];Analytics.VideoGridView=function(config){Analytics.VideoGridView.superclass.constructor.call(this,config);};Ext.extend(Analytics.VideoGridView,Ext.grid.GridView,{emptyTextIfSelectedDataFilter:'<span class="x-grid-empty">'+
gettext('No videos for your selected data filter.')+'&nbsp;&nbsp;<a href="#" onclick="$(\'div.set-datafilter a\').click();return false;">'+
gettext('Set Data Filter?')+'</a></span>',emptyText:gettext('No videos'),applyEmptyText:function(){var $msgbox=$("#grid-msgbox");if(this.grid.videoId===null||this.grid.videoId===-2){$msgbox.html(gettext("Not all videos displayed. Set data filter?"));$msgbox.show();this.mainBody.update('<div class="x-grid-empty">'+this.emptyTextIfSelectedDataFilter+'</div>');return;}
if(this.grid.videoId===-1){$msgbox.hide();this.mainBody.update('<div class="x-grid-empty">'+this.emptyText+'</div>');}
var store=this.grid.store;var all_video_total=store.reader.jsonData['all_video_total'];var emptyText=this.emptyText;if(parseInt(all_video_total,10)==store.getTotalCount()){$msgbox.html('');$msgbox.hide();}
else{emptyText=this.emptyTextIfSelectedDataFilter;$msgbox.html(gettext("Not all videos displayed. Set data filter?"));$msgbox.show();}
if(!this.hasRows()){this.mainBody.update('<div class="x-grid-empty">'+emptyText+'</div>');}}});Analytics.VideoPanel=function(){this.sid=null;this.videoId=null;this.pageSize=20;this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/video/list/'}),reader:new Ext.data.JsonReader({root:'list',id:'vid',totalProperty:'total',fields:Analytics.VideoRecordFields}),sortInfo:{field:'date',direction:'DESC'},remoteSort:true});this.store.baseParams={sid:this.sid,limit:this.pageSize}
Analytics.VideoPanel.superclass.constructor.call(this,{store:this.store,autoHeight:true,viewConfig:{enableRowBody:true,showPreviewRowIndex:false,deferEmptyText:true},loadMask:{msg:'Loading...'},cm:new Ext.grid.ColumnModel({columns:[{id:'region',header:gettext('Region'),dataIndex:'region_name',align:'center',width:80,sortable:false,renderer:function(value,metadata,record){var region_url=record.get("region_logo");if(region_url){return'<img src="'+region_url+'" /> '+value;}
return value;}},{id:'site',header:gettext('Site'),dataIndex:'site_name',align:'center',width:110,sortable:true,renderer:function(value,metadata,record){var site_logo=record.get('site_logo');if(site_logo){return'<img src="'+site_logo+'" /> '+value;}
return value;}},{id:'title',header:gettext('Title'),dataIndex:'title',width:300,sortable:true},{id:'date',header:gettext('Date'),dataIndex:'date',type:'date',width:80,renderer:Ext.util.Format.dateRenderer('Y-m-d'),sortable:true},{id:'view_count',header:gettext('View'),dataIndex:'view_count',width:90,sortable:true,summaryType:'sum',renderer:function(value,metadata,record){if(typeof(record.get)!="undefined"){var player_count=record.get("player_count",0);if(player_count>0){return value+" ("+player_count+") ";}}
return value;}},{id:'share_count',header:gettext('Shared'),dataIndex:'share_count',width:90,sortable:true,summaryType:'sum'},{id:'cmt_count',header:gettext('Comments'),dataIndex:'cmt_count',width:90,sortable:true,summaryType:'sum'},{id:'alive',header:gettext('Alive'),dataIndex:'alive',width:90,align:'center',renderer:function(val){return val==1?'Y':'N';},sortable:true},{id:'is_seedurl',header:gettext('Seed url'),dataIndex:'is_seedurl',width:90,align:'center',renderer:function(val){return val==1?'Y':'N';},sortable:true},{id:'vid',header:gettext('VID'),dataIndex:'vid',width:90}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Videos')}),plugins:[new Ext.ux.grid.HybridSummary()],listeners:{cellclick:function(thisGrid,rowIndex,columnIndex,e){var view=thisGrid.getView();if(view.showPreviewRowIndex===rowIndex){view.showPreviewRowIndex=false;}
else{view.showPreviewRowIndex=rowIndex;}
view.refresh();}}});this.getView().getRowClass=function(record,rowIndex,rowParams,store){var result="";var alive=record.get('alive');if(alive!=1){result="row-deadlink";}
var vid=record.get('vid');if(rowIndex===this.showPreviewRowIndex){rowParams.body='<div class="row-preview"><div id="video_player_container_'+vid+'" class="video_player_container"></div></div>';$.ajax({url:'/video/player/embed/'+vid+'/',dataType:'html',success:function(result){$("#video_player_container_"+vid).html(result);}});return result+' x-grid3-row-expanded';}
else{rowParams.body='<div class="row-preview"><div id="video_player_container_'+vid+'"></div></div>';}
return result+' x-grid3-row-collapsed';};};Ext.extend(Analytics.VideoPanel,Widget.ContentBasePanel,{showVideoInfo:function(){var view=this.getView();view.showPreview=true;view.refresh();},loadByVideoId:function(videoId,sid){this.getView().showPreviewRowIndex=false;this.videoId=videoId;this.sid=sid;this.store.baseParams.dvid=videoId;this.store.baseParams.sid=sid;this.store.load();},reload:function(){this.getView().showPreviewRowIndex=false;this.store.reload();},search:function(searchField){this.store.baseParams.keyword=searchField.getValue();this.store.load();},clearSearch:function(){this.store.baseParams.keyword=null;this.store.load();},doResizeLayout:function(){if(!$("#contents-info").is(":visible"))return;var height=$(window).height();var newHeight=height-90;$(".contents-container").height(newHeight);var width=this.getView().mainBody.getSize().width+415;$(".contents").attr("style","min-width:"+width+"px;");},getView:function(){if(!this.view){this.view=new Analytics.VideoGridView(this.viewConfig);}
return this.view;}});Ext.ns('Analytics.Video');Analytics.Video.Layout=function(){var videoPanel;var searchField;var topTabView;var sgNavigator;return{init:function(programId,clusterId,dvid){videoPanel=new Analytics.VideoPanel(dvid);searchField=new Ext.ux.form.SearchField({width:200,applyTo:'searchkeyword',contentEl:'searchkeyword',emptyText:'Search',listeners:{render:function(thisField){$("#searchfield").show();}}});searchField.callbackObj=videoPanel;sgNavigator=new Widget.DataNavigator({store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/foldercluster/videos/?clusterId='+clusterId+'&filter_only_dvid=1'}),reader:new Ext.data.JsonReader({root:'list',id:'dvid',totalProperty:'total',fields:['dvid','title']})}),renderTo:'navigator-list-area',targetPanel:videoPanel,navCls:'program-list',listeners:{click:function(dataView,index,node,e){var record=this.store.getAt(index);if(this.targetPanel){this.targetPanel.loadByVideoId(record.data.dvid);$("div.title span").html(record.data.title);}}}});sgSearchField=new Ext.ux.form.SearchField({width:190,applyTo:'sg-searchkeyword',contentEl:'sg-searchkeyword',emptyText:'Search Segments',listeners:{render:function(thisField){$("#sg-searchfield").show();}}});sgSearchField.callbackObj=sgNavigator;videoPanel.loadByVideoId(dvid);},reloadStores:function(){videoPanel.reload();}}}();var DataFilterPanel=function(){DataFilterPanel.superclass.constructor.call(this,{id:'data-filter-panel',region:'north',autoHeight:false,autoScroll:false,autoShow:false,height:0,margins:'0 0 0 0',cmargins:'0 0 0 0',border:false,contentEl:'data-filter'});};Ext.extend(DataFilterPanel,Ext.Panel,{show:function(){Ext.getCmp('program-grid').hide();Ext.getCmp('video-grid').hide();Ext.getCmp('cluster-grid').hide();var $filter_layer=$("div#data-filter");$filter_layer.show();this.setHeight(Ext.getCmp("center-grid").getSize().height);this.ownerCt.doLayout();},hide:function(){Ext.getCmp('program-grid').show();Ext.getCmp('video-grid').show();Ext.getCmp('cluster-grid').show();var $filter_layer=$("div#data-filter");$filter_layer.hide();this.setHeight(0);this.ownerCt.doLayout();}});var FolderCategoryStore=function(conf){var config={proxy:new Ext.data.HttpProxy({url:'/folder/category/'}),reader:new Ext.data.JsonReader({root:'list',id:'id',totalProperty:'total',fields:[{name:'id'},{name:'name'}]})};Ext.apply(config,conf||{});FolderCategoryStore.superclass.constructor.call(this,config);};Ext.extend(FolderCategoryStore,Ext.data.Store);var FolderCategoryComboBox=function(conf){var config={name:'category',beforeBlur:Ext.emptyFn,grow:true,listWidth:180,valueField:'id',displayField:'name',triggerAction:'all',forceSelection:false,selectOnFocus:false,editable:false,allowBlank:true,hideOnSelect:false,listeners:{expand:function(combo){var dq=Ext.DomQuery;var view=combo.view;if(!view)return;if(this.createBtnEl)return;var btn=dq.selectNode("div.btn-create-category",view.dom);this.createBtnEl=Ext.get(btn);this.createBtnEl.on('click',this.showDialog.createDelegate(this));}}};Ext.apply(config,conf||{});FolderCategoryComboBox.superclass.constructor.call(this,config);this.tpl='<tpl for=".">'
+'<div class="x-combo-list-item">'
+'<img src="'+Ext.BLANK_IMAGE_URL+'" '
+'class="ux-lovcombo-icon ux-lovcombo-icon-'
+'{[values.'+this.checkField+'?"checked":"unchecked"'+']}">'
+'<div class="ux-lovcombo-item-text">{'+(this.displayField||'text')+'}</div>'
+'</div>'
+'</tpl>'
+'<div class="btn-create-category">Create Category</div>';};Ext.extend(FolderCategoryComboBox,Ext.ux.form.LovCombo,{onSelect:function(record,index){if(this.fireEvent('beforeselect',this,record,index)!==false){if(!record.get(this.checkField)){this.clearValue();}}
FolderCategoryComboBox.superclass.onSelect.apply(this,arguments);},onEmptyResults:function(){this.collapse();this.hide();var dialog=new FolderCategoryDialog(this);dialog.show();},showDialog:function(){this.collapse();this.hide();var dialog=new FolderCategoryDialog(this);dialog.show();}});var FolderCategoryDialog=function(comp){this.comp=comp;this.store=comp.store;this.formPanel=new Ext.FormPanel({formId:"folderCategoryForm",width:260,labelWidth:60,border:false,defaultType:'textfield',autoHeight:true,autoDestroy:true,items:[{fieldLabel:'Category',name:'name',width:160}]});this.actionBtn=new Ext.Button({text:"Confirm",minWidth:80,handler:this.updateCategory.createDelegate(this)});FolderCategoryDialog.superclass.constructor.call(this,{title:"Create New Category",layout:"fit",width:320,plain:true,modal:true,items:this.formPanel,autoHeight:true,buttonAlign:'center',buttons:[this.actionBtn,{text:'Cancel',handler:this.close.createDelegate(this)}]});};Ext.extend(FolderCategoryDialog,Ext.Window,{close:function(){FolderCategoryDialog.superclass.close.apply(this,arguments);this.comp.show();this.comp.expand();},updateCategory:function(){var form=this.formPanel.getForm();var name=form.findField("name").getValue();if(name.trim()==""){alert("category name is empty.");form.findField("name").focus(true);}
else{this.actionBtn.disable();var handleSuccess=function(o){if(o.responseText!==undefined){var data=Ext.decode(o.responseText);if(data.success){var category=data.category;var Record=Ext.data.Record.create([{name:'id'},{name:'name'}]);var r=new Record({id:category.id,name:category.name});this.store.insert(0,r);this.close();this.comp.show();this.comp.expand();}}
else{alert((data.msg?data.msg:'죄송합니다. 요청을 처리하지 못했습니다.'));this.actionBtn.enable();}};Ext.Ajax.request({url:'/folder/category/new/',success:handleSuccess,form:form.formId,scope:this});}}});Ext.ns('Analytics');Analytics.ReportRecordFields=[{name:'id',type:'int'},'release_date','file_name','desc',{name:'download',type:'boolean'},'group_id','folder_id','report_type'];Analytics.ReportDownloadLink=function(url){var $iframe=$("#hidden_iframe");$iframe.attr('src',url);return false;};Analytics.ReportPanel=function(pkgId,pkgType){if(pkgType=='F')this.folderId=pkgId;else this.groupId=pkgId;this.pageSize=40;this.store=new Ext.data.JsonStore({url:'/report/list/json/',root:'list',id:'id',totalProperty:'total',fields:Analytics.ReportRecordFields,sortInfo:{field:'release_date',direction:'DESC'},remoteSort:true});this.store.baseParams={folder_id:this.folderId,group_id:this.groupId,limit:this.pageSize};Analytics.ReportPanel.superclass.constructor.call(this,{applyTo:'report_grid',trackMouseOver:false,store:this.store,cm:new Ext.grid.ColumnModel({columns:[{id:'release_date',header:gettext('Release date'),dataIndex:'release_date',sorttable:false,menuDisabled:true,width:140},{id:'file_name',header:gettext('File name'),dataIndex:'file_name',sorttable:false,menuDisabled:true,width:420},{id:'download',header:gettext('Download'),dataIndex:'download',sorttable:false,menuDisabled:true,width:210,align:'center',renderer:function(val,md,record){var url="/report/download/"+record.get('id')+"/";var t=new Ext.Template('<div onclick="return Analytics.ReportDownloadLink(\'{url}\');" style="cursor:pointer;" >','<img src="{MEDIA_URL}/ext/resources/images/adview/download.png">{download}</img></div>');return t.apply({url:url,MEDIA_URL:MEDIA_URL,download:gettext('Download')});}},{id:'desc',header:'',dataIndex:'desc',sorttable:false,menuDisabled:true,width:320}]}),sm:new Ext.grid.RowSelectionModel({singleSelect:true}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Report found')})});};Ext.extend(Analytics.ReportPanel,Widget.ContentBasePanel,{load:function(){this.store.load();}});Search.FilterKeys=new Array("playtime","date","adv","sort");Search.Filters=function(config){Ext.apply(this,config||{});this.filterValue=null;this.sortValues=new Ext.util.MixedCollection();this.tpl=new Ext.XTemplate('<div class="contents_filtering">','<ul>','<li id="filter_playtime" class="closed">','<span class="filter"> ',gettext('Length'),' </span>','<ol><li><span cate="playtime" opt="all" > ',gettext('All length'),' </span>','<li><span cate="playtime" opt="-10" > ',gettext('~ 10 min.'),'</span>','<li><span cate="playtime" opt="10-30" >',gettext('10 ~ 30 min.'),'</span>','<li><span cate="playtime" opt="30-1h" >',gettext('30 ~ 1 hour'),'</span></li>','<li><span cate="playtime" opt="1h-" > ',gettext('over 1 hour'),'</span></li></ol>','</li>','<li id="filter_date" class="closed">','<span class="filter"> ',gettext('Date'),'</span>','<ol><li><span cate="date" opt="all"> ',gettext('All date'),' </span>','<li><span cate="date" opt="today">',gettext('Today'),' </span></li>','<li><span cate="date" opt="week">',gettext('This week'),' </span></li>','<li><span cate="date" opt="month">',gettext('This month'),' </span></li>','</ol>','</li>','</ul>','</div>','<div class="contents_sorting">','<ul>','<li><span class="selected" opt="issue"> ',gettext('Most Relevant'),' </span></li>','<li><span>|</span></li>','<li><span opt="date" > ',gettext('Most Recent'),' </span></li>','</ul>','</div>');Search.Filters.superclass.constructor.call(this);if(this.autoRender)this.render();};Ext.extend(Search.Filters,Ext.util.Observable,{render:function(el){if(el)this.el=el;this.tpl.overwrite(this.el);this.bindEvents();},bindEvents:function(){var filtersEl=Ext.select("div.contents_filtering > ul > li",true,this.el.dom);var that=this;filtersEl.each(function(el){var btnEl=Ext.select("span.filter",true,el.dom);btnEl.on('click',that.onClickFilterExpandBtn(el));});var filterOptsEl=Ext.select("div.contents_filtering ol > li > span",true,this.el.dom);filterOptsEl.each(function(el){el.on('click',that.onClickFilterOption,that);});var sortsEl=Ext.select("div.contents_sorting span",true,this.el.dom);sortsEl.each(function(el){el.on('click',that.onClickSort,that);});},onClickFilterOption:function(evt,htmlEl){var cate=htmlEl.getAttribute("cate");var els=Ext.select("#filter_"+cate+" ol li span ",true);els.removeClass("selected");htmlEl.setAttribute("class","selected");var opt=htmlEl.getAttribute("opt");Search.Action(cate,opt);Ext.get("filter_"+cate).addClass("closed");Ext.select("#filter_"+cate+" span.filter").update(htmlEl.innerHTML);},onClickFilterExpandBtn:function(el){return function(){if(el.hasClass("closed")){el.removeClass("closed");}
else{el.addClass("closed");}}},onClickSort:function(evt,htmlEl){Ext.select("div.contents_sorting span").removeClass("selected");var opt=htmlEl.getAttribute("opt");Search.Action('sort',opt);htmlEl.setAttribute("class","selected");}});Search.VideoRecordFields=[{name:'vid',type:'int'},'site_name','site_logo','region_name','region_logo','title','date'];Search.VideoView=function(config){Ext.apply(this,config||{});this.isShow=false;this.el=Ext.get("column-right");this.videoPlayerEl=Ext.get("video_player");this.videoListEl=Ext.get("video_list");this.videoEmptyEl=Ext.get("video_empty");this.videoEmptyEl.setVisibilityMode(Ext.Element.DISPLAY);this.videoPageSize=10;this.videoStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/search/video/list/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'vid',totalProperty:'total',fields:Search.VideoRecordFields}),sortInfo:{field:'date',direction:'DESC'},remoteSort:true});this.videoStore.baseParams={limit:this.videoPageSize};this.videoListGrid=new Search.VideoListGrid({store:this.videoStore,pageSize:this.videoPageSize,videoView:this});Search.VideoView.superclass.constructor.call(this);};Ext.extend(Search.VideoView,Ext.util.Observable,{show:function(vid,dvid){this.videoStore.baseParams.vid=vid;this.videoStore.baseParams.dvid=dvid;if(this.isShow==false){this.el.removeClass("nodata");this.videoPlayerEl.show();this.videoListEl.show();this.videoEmptyEl.hide();this.isShow=true;}
this.showVideoListGrid();},hide:function(){this.isShow=false;this.el.addClass("nodata");this.videoPlayerEl.hide();this.videoListEl.hide();this.videoEmptyEl.show();},showVideoPlayer:function(vid){var playerEl=this.videoPlayerEl;$.ajax({url:'/video/player/embed/'+vid+'/',dataType:'html',success:function(result){var html=String.format('<div id="video_player_container_{0}" class="video_player_container">{1}</div>',vid,result);playerEl.update(html,true);}});},showVideoListGrid:function(){var videoListEl=Ext.get("video_list");if(!this.videoListGrid.isVisible()){this.videoListGrid.render(videoListEl);}
this.videoStore.load();},setVideoGridSize:function(height){this.videoListGrid.setHeight(height);if(this.videoListGrid.isVisible()){this.videoListGrid.syncSize();}}});Search.VideoListGridView=function(config){Search.VideoListGridView.superclass.constructor.call(this,config);};Ext.extend(Search.VideoListGridView,Ext.grid.GridView,{});Search.VideoListGrid=function(conf){this.store=conf.store;this.pageSize=conf.pageSize;delete conf.store;delete conf.pageSize;var config={loadMask:{msg:'Loading...'},viewConfig:{deferEmptyText:true,emptyText:'No Videos',forceFit:true},cm:new Ext.grid.ColumnModel({columns:[{id:'region',header:gettext('Region'),dataIndex:'region_name',align:'center',width:50,sortable:false,renderer:function(value,metadata,record){var logo_url=record.get("region_logo");if(logo_url&&logo_url.length>1){return String.format('&nbsp;<img src="{0}" ext:qtip="{1}" align="center" />',logo_url,value);}
return value;}},{id:'site',header:gettext('Site'),dataIndex:'site_name',align:'center',width:50,sortable:true,renderer:function(value,metadata,record){var logo_url=record.get('site_logo');if(logo_url&&logo_url.length>1){return String.format('&nbsp;<img src="{0}" ext:qtip="{1}" />',logo_url,value);}
return value;}},{id:'title',header:gettext('Title'),dataIndex:'title',width:300,sortable:true},{id:'date',header:gettext('Date'),dataIndex:'date',width:120,sortable:true}]}),bbar:new Ext.PagingToolbar({pageSize:this.pageSize,store:this.store,displayInfo:true,displayMsg:'{0} - {1} of {2}',emptyMsg:gettext('No Videos')}),sm:new Ext.grid.RowSelectionModel({singleSelect:true,listeners:{rowselect:function(thisSelModel,rowIndex,record){var vid=record.data.vid;var videoView=this.grid.videoView;videoView.showVideoPlayer(vid);}}})};Ext.apply(config,conf||{});Search.VideoListGrid.superclass.constructor.call(this,config);this.bindStore(true);};Ext.extend(Search.VideoListGrid,Ext.grid.GridPanel,{getView:function(){if(!this.view){this.view=new Search.VideoListGridView(this.viewConfig);}
return this.view;},bindStore:function(initial){if(!initial){this.store.un('load',this.onLoadStore,this);}
else{this.store.on('load',this.onLoadStore,this);}},onLoadStore:function(){this.selModel.selectRow(0);},onDestory:function(){this.bindStore(null);Search.VideoListGrid.superclass.onDestory.call(this);}});Search.DvidRecordFields=[{name:'dvid',type:'int'},{name:'vid',type:'int'},'title','playtime',{name:'recommend',type:'boolean'},'timetrack','thumb_url_small',{name:'added',type:'boolean'}];Search.DvidListView=function(conf){var config={listeners:{selectionchange:function(thisView,selections){if(selections&&selections.length<1)return;var selection=selections[0];var record=this.getRecord(selection);this.ct.showVideo(record.data.vid,record.data.dvid);this.resultView.changeVideo(this.vid,{'vid':record.data.vid,'dvid':record.data.dvid,'title':record.data.title,'timetrack':record.data.timetrack,'thumbnail':record.data.thumb_url_small});}}};Ext.apply(config,conf||{});this.pageSize=10;this.store=new Ext.data.JsonStore({url:'/search/dvid/list/json/',root:'list',id:'dvid',totalProperty:'total',fields:Search.DvidRecordFields,remoteSort:true});this.tpl=new Ext.XTemplate('<tpl for=".">','<p class="recommend {[this.addedCSS(values)]}">','<span class="cluster_timedata"> {[this.timetrack(values)]}</span>','<span class="provider_time">{playtime}</span> <em>|</em> <span class="s-icon" style="display:inline-block;"> </span><tpl if="recommend == true"><span class="r-icon"> </span></tpl> ','<a class="videolink" rel="videoplayer" href="#"> {title} </a> </p>','</tpl>',{addedCSS:function(values){if(values.added)return"added";return'';},timetrack:function(item){var start=item.timetrack.start;var end=item.timetrack.end;return String.format('<span style="margin-left:{0}%;width:{1}%;"> <span style="width: 100%;" class="cluster_timeinfo "></span> </span>',start,end);}});Search.ResultView.superclass.constructor.call(this,config);this.store.baseParams={'vid':this.vid,'cid':this.cid,'dvid':this.dvid};this.bindStore(true);};Ext.extend(Search.DvidListView,Ext.DataView,{singleSelect:true,itemSelector:'p',selectedClass:'selected',loadingText:'Loading...',onDestory:function(){this.bindStore(null);Search.DvidListView.superclass.call(this);},bindStore:function(initial){if(!initial){this.store.un('load',this.onLoadStore,this);}
else{this.store.on('load',this.onLoadStore,this);}},onLoadStore:function(thisStore,records,options){var idx=thisStore.indexOfId(this.dvid);this.select(idx,false,false);$("#vid-"+this.vid+" img.loading").hide();},loadAndRender:function(el){$(el).show();if(!this.rendered){$("#vid-"+this.vid+" img.loading").show();this.store.load();this.render(el);}},added:function(dvid){var record=this.store.getById(dvid);if(!record)return;record.data.added=true;this.store.commitChanges();this.refresh();}});Search.AddToLibButtons=function(config){Ext.apply(this,config||{});this.buttons=new Ext.util.MixedCollection();this.tpl=new Ext.XTemplate('<span class="btn-add-content">','<span class="icon"></span> ',gettext('Add to Content Libray'),' <span class="right" ></span> </span>');this.tpl.compile();this.tplAdded=new Ext.XTemplate('<span class="added"><span class="icon"></span><strong ext:qtip="{other_owners}" >{ownername} </strong> {others}',gettext('Added'),'</span>');this.tplAdded.compile();Search.AddToLibButtons.superclass.constructor(this);};Ext.extend(Search.AddToLibButtons,Ext.util.Observable,{getAddBtnTpl:function(item){var data={"ownername":item.ownername,"others":""};if(item.owner_other_names_cnt>0){var _other_names='';for(var i=0;i<item.owner_other_names.length;i++){var _name=item.owner_other_names[i];_other_names=_other_names+_name+"<br />";}
data.others=String.format('<span ext:qtip="{1}"> (+{0}) </span>&nbsp;',item.owner_other_names_cnt,_other_names);}
return data;},addButton:function(item){var el=new Ext.Element(item.btndom);if(item.has_owner){data=this.getAddBtnTpl(item);this.tplAdded.overwrite(el,data);}
if(item.is_mine||!item.has_owner){this.tpl.append(el);this.buttons.add(item.vid,el);el.on('click',this.onClickButton(item.vid,item.dvid,item.viewdom));}},addButtons:function(items,initial){if(initial==true)this.clearButtons();for(var i=0;i<items.length;i++){var item=items[i];this.addButton(item);}},clearButtons:function(){this.buttons.clear();},onClickButton:function(vid,dvid,el){var ct=this.ct;return function(){ct.toggleAddLibView(vid,dvid,el);}},changeAdded:function(data,el){data=this.getAddBtnTpl(data);this.tplAdded.insertBefore(el,data);}});Search.AddToLibView=function(conf){var config={rendered:false};Ext.apply(config,conf||{});Ext.apply(this,config);this.hidden=true;this.tpl=new Ext.XTemplate('<div class="pop-add-content">','<div class="pop-inner" >','<p class="title">',gettext('Add to content library?'),'</p>','<form onSubmit="return false;"><span>',gettext('Select Your Program'),' : </span> <span class="combo"></span>','<div class="btn"><span class="add"> <span class="icon"></span>',gettext('Add to'),'<span class="right"></span> </span>&nbsp;<span class="cancel">',gettext('Cancel'),'<span class="right"></span> </span><img class="loading" style="display:none;" src="'+MEDIA_URL+'/ext/resources/images/adview/common/ajax-loader.gif" /> </div> ','</form></div>','</div>');this.programStore=new Ext.data.JsonStore({url:'/search/program/list/json/',root:'list',id:'id',totalProperty:'total',fields:['id','name'],baseParams:{group_id:Search.GROUP_ID}});this.comboBox=new Ext.form.ComboBox({store:this.programStore,displayField:'name',valueField:'id',editable:true,selectOnFocus:true,forceSelection:true,width:345,emptyText:'Select your program...',mode:'remote',minListWidth:345,minChars:1,triggerAction:'all',typeAhead:true,lazyInit:false,listeners:{beforequery:function(qe){delete qe.combo.lastQuery;},focus:function(thisField){if(!thisField.isExpanded())thisField.expand();}}});Search.AddToLibView.superclass.constructor.call(this,config);};Ext.extend(Search.AddToLibView,Ext.util.Observable,{render:function(el){this.tpl.overwrite(el);var comboBoxEl=Ext.DomQuery.selectNode("span.combo",el);this.comboBox.render(comboBoxEl);this.rendered=true;this.hidden=false;var addEl=Ext.select("span.add",true,el);addEl.on('click',this.onAddTo,this);var cancelEl=Ext.select("span.cancel",true,el);cancelEl.on('click',function(){this.hide();},this);},load:function(){this.programStore.load();},onAddTo:function(evt,e){if(!this.comboBox.getValue()){Ext.ux.growl.msg(" ",gettext('Please,Select your program'));return;}
if(!this.vid){Ext.ux.growl.msg(" ",'Input error!');return;}
var addEl=Ext.select("span.add",true,this.el);var cancelEl=Ext.select("span.cancel",true,this.el);var loadingEl=Ext.select("img.loading",true,this.el);addEl.setVisibilityMode(Ext.Element.DISPLAY);cancelEl.setVisibilityMode(Ext.Element.DISPLAY);loadingEl.setVisibilityMode(Ext.Element.DISPLAY);loadingEl.show();addEl.hide();cancelEl.hide();var ar=Ext.Ajax.request({url:'/search/add/',params:{vid:this.vid,fid:this.comboBox.getValue()},success:function(resp,opt){this.hide();var result=Ext.util.JSON.decode(resp.responseText);Ext.ux.growl.msg('',result.message);if(result.result=='success'){var vid=this.id.replace("addToLibView:","");this.ct.dvidListViews.get(vid).added(this.dvid);var btnEl=Ext.DomQuery.selectNode("#vid-"+vid+" span.btn-add-content");$("#vid-"+vid+" span.added").remove();this.ct.addToLibButtons.changeAdded({ownername:result.groupname,owner_other_names:result.owner_other_names,owner_other_names_cnt:result.owner_other_names_cnt},btnEl);}
loadingEl.hide();addEl.show();cancelEl.show();},failure:function(resp,opt){loadingEl.hide();addEl.show();cancelEl.show();},disableCaching:false,scope:this});},show:function(){if(this.el){var el=new Ext.Element(this.el);el.setVisibilityMode(Ext.Element.DISPLAY);el.show();this.hidden=false;}},hide:function(){if(this.el){var el=new Ext.Element(this.el);el.setVisibilityMode(Ext.Element.DISPLAY);el.hide();this.hidden=true;}},renderAfterLoaded:function(el){var that=this;this.el=el;this.programStore.load({callback:function(){that.render(el);}});}});Search.ResultView=function(conf){this.currentVid=null;this.currentDvid=null;var config={applyTo:'search-result-video-list',listeners:{selectionchange:function(thisView,selections){if(selections&&selections.length<1){this.ct.currentVideo={vid:null,dvid:null};this.ct.hideVideo();return;}
var selection=selections[0];var record=this.getRecord(selection);if(thisView.currentVid==record.data.vid)return;$("#vid-"+thisView.currentVid+" div.cluster-container").hide();if(thisView.addToLibViews.containsKey(thisView.currentVid)){thisView.addToLibViews.get(thisView.currentVid).hide();}
thisView.currentVid=record.data.vid;thisView.currentDvid=record.data.dvid;this.ct.showVideo(record.data.vid,record.data.dvid);this.showDvidList(selection,record.data.cid,record.data.vid,record.data.dvid);},containerclick:function(thisView,e){return false;}}};Ext.apply(config,conf||{});this.tpl=new Ext.XTemplate('<div class="searchresult-scroller">','<tpl for=".">','<dl id="vid-{vid}" >','<dt><a href="#" class="video_title">{title}</a>','<div class="btn add-lib-btn"></div>','<span class="add-lib-view"></span></dt>','<dd><p class="cluster_detail"><span class="cluster_timedata">','<span style="margin-left:{vd_timet_start}%;width:{vd_timet_width}%;"><span class="cluster_timeinfo" style="margin-left:0%;width:100%;"></span></span>','</span><span class="overlapping">{dvid_total} ',gettext('Overlapping segments'),'<img class="loading" style="display:none;" src="'+MEDIA_URL+'/ext/resources/images/adview/common/ajax-loader.gif" /></span> <em>|</em> ',gettext('Total length'),': {cl_length} ','<div class="cluster-container">','<div class="bg-cluster-container"><div class="bg_relevant" style="margin-left:{vd_timet_start}%; width:{vd_timet_width}%;"></div></div>','<div class="cluster-list"><img src="'+MEDIA_URL+'/ext/resources/images/adview/common/bg_timeline_bottom.gif" class="bottom" /></div>','</div>','</dd>','<dd class="thumbnail"><a href="#"><img src="{thumb_url_small}" /></a></dd>','</dl>','</tpl>','</div>');this.emptyText=$("#search-result-empty").html();this.dvidListViews=new Ext.util.MixedCollection();this.addToLibViews=new Ext.util.MixedCollection();this.addToLibButtons=new Search.AddToLibButtons({store:this.store,ct:this});Search.ResultView.superclass.constructor.call(this,config);this.bindStore(true);};Ext.extend(Search.ResultView,Ext.DataView,{singleSelect:true,itemSelector:'dl',selectedClass:'selected',refresh:function(){this.clearSelections(false,true);this.el.update("");var records=this.store.getRange();if(records.length<1){$("#search-result-video-list").addClass("nodata");this.el.update(String.format(this.emptyText,this.store.baseParams.q||''));this.all.clear();}else{$("#search-result-video-list").removeClass("nodata");this.tpl.overwrite(this.el,this.collectData(records,0));this.all.fill(Ext.query(this.itemSelector,this.el.dom));this.updateIndexes(0);}
this.hasSkippedEmptyText=true;this.initButtons(records);},showDvidList:function(node,cid,vid,dvid){var el=Ext.DomQuery.selectNode("div.cluster-container",node);if(!this.dvidListViews.containsKey(vid)){var listView=new Search.DvidListView({id:'dvidListView:'+vid,cid:cid,vid:vid,dvid:dvid,resultView:this,ct:this.ct});this.dvidListViews.add(vid,listView);}
this.dvidListViews.get(vid).loadAndRender(el);},initButtons:function(records){var btndoms=Ext.query("div.add-lib-btn",this.el.dom);var viewdoms=Ext.query("span.add-lib-view",this.el.dom);var items=new Array(records.length);for(var i=0;i<records.length;i++){items[i]={vid:records[i].data.vid,dvid:records[i].data.dvid,owner_id:records[i].data.owner_id,ownername:records[i].data.owner_name,has_owner:records[i].data.has_owner,is_mine:records[i].data.is_mine,owner_other_names:records[i].data.owner_other_names,owner_other_names_cnt:records[i].data.owner_other_names_cnt,btndom:btndoms[i],viewdom:viewdoms[i]};}
this.addToLibButtons.addButtons(items,true);var dvidbtnEl=Ext.select("span.overlapping",true,this.el.dom);dvidbtnEl.each(function(el){el.on('click',function(evt,el){var $el=$(el);$el.parent().next("div.cluster-container").toggle();});});},toggleAddLibView:function(vid,dvid,el){if(typeof vid=='undefined'||!vid)return;if(typeof dvid=='undefined'||!dvid)return;if(!this.addToLibViews.containsKey(vid)){var view=new Search.AddToLibView({store:this.store,id:"addToLibView:"+vid,vid:vid,dvid:dvid,ct:this});this.addToLibViews.add(vid,view);}
if(!this.addToLibViews.get(vid).rendered){this.addToLibViews.get(vid).renderAfterLoaded(el);}
if(this.currentVid!=vid){this.addToLibViews.get(vid).show();}
else
{if(this.addToLibViews.get(vid).hidden){this.addToLibViews.get(vid).show();}
else{this.addToLibViews.get(vid).hide();}}},changeVideo:function(vid,video){if(video.dvid==this.currentDvid)return;this.currentDvid=video.dvid;if(this.addToLibViews.containsKey(vid)){var addToLibView=this.addToLibViews.get(vid);addToLibView.vid=video.vid;addToLibView.dvid=video.dvid;}
else{var view=new Search.AddToLibView({store:this.store,id:"addToLibView:"+vid,vid:video.vid,dvid:video.dvid,ct:this});this.addToLibViews.add(vid,view);}
var $videoel=$("#vid-"+vid);$videoel.find("dt a.video_title").html(video.title);$videoel.find("dd.thumbnail a img").attr("src",video.thumbnail);$videoel.find("p.cluster_detail span.cluster_timedata span:first").css('margin-left',video.timetrack.start+"%").css('width',video.timetrack.end+"%");$videoel.find("div.cluster-container div.bg_relevant").css("margin-left",video.timetrack.start+"%").css("width",video.timetrack.end+"%");},bindStore:function(initial){if(!initial){this.store.un('load',this.onLoadStore,this);}
else{this.store.on('load',this.onLoadStore,this);}},onLoadStore:function(){this.dvidListViews.clear();this.addToLibViews.clear();this.currentVid=null;this.currentDvid=null;},onDestory:function(){this.bindStore(null);this.dvidListViews.clear();this.dvidListViews=null;this.addToLibViews.clear();this.addToLibViews=null;this.currentVid=null;this.currentDvid=null;Search.ResultView.superclass.onDestory.call(this);},onBeforeLoad:function(){this.clearSelections(false,true);this.el.update('<div class="loading">'+$("#loading").html()+"</div>");this.all.clear();}});Search.ResultRecordFields=[{name:'vid',type:'int'},{name:'dvid',type:'int'},{name:'cid',type:'int'},'title','thumb_url_small','date','length','cl_total','cl_length','dvid_total','vd_timet_start','vd_timet_width','owner_id','owner_name',{name:'has_owner',type:'boolean'},{name:'is_mine',type:'boolean'},'owner_other_names','owner_other_names_cnt'];Search.ResultContainer=function(config){Ext.apply(this,config||{});this.currentVideo={vid:null,dvid:null};this.resultPageSize=10;this.resultStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'/search/result/json/'}),reader:new Ext.data.JsonReader({root:'list',id:'vid',totalProperty:'total',fields:Search.ResultRecordFields}),remoteSort:true});this.resultStore.baseParams={limit:this.resultPageSize};this.resultView=new Search.ResultView({store:this.resultStore,ct:this});this.resultPaging=new Ext.PagingToolbar({store:this.resultStore,renderTo:'search-result-paging'});this.videoView=new Search.VideoView();this.searchFilters=new Search.Filters({el:Ext.get("search_filter_container"),autoRender:true,ct:this});Search.ResultContainer.superclass.constructor(this);Ext.History.on('change',this.dispatch,this);Ext.History.init(function(){var token=document.location.hash.replace("#","");this.dispatch(token);},this);this.doResize();Ext.EventManager.onWindowResize(this.doResize,this);};Ext.extend(Search.ResultContainer,Ext.util.Observable,{doResize:function(){var totalwidth=$(window).width();var totalheight=$(window).height();$("#contents-container").height(totalheight-120);$("#search-result-video-list").height(totalheight-180);$("#video_list").height(totalheight-441);this.videoView.setVideoGridSize(totalheight-441);},load:function(){this.resultStore.load({callback:function(r,options,success){if(!success)return;$("#search_q").text('"'+this.baseParams.q+'"');$("#searchform_q").attr("value",this.baseParams.q);var total=this.getTotalCount();$("#search_total").text(commify(total));}});},search:function(q){if(!q)return;this.resultStore.baseParams.q=q;},searchFilter:function(key,value){if(this.resultStore.baseParams.hasOwnProperty(key)){if(this.resultStore.baseParams[key]!=value){this.resultStore.baseParams[key]=value;}}
else{this.resultStore.baseParams[key]=value;}
if(key=="sort"){$('div.contents_sorting span[opt="'+value+'"]').addClass("selected");}
else{for(var i=0;i<Search.FilterKeys.length;i++){if(key==Search.FilterKeys[i]){var $filter=$('div.contents_filtering span[cate="'+key+'"][opt="'+value+'"]');if(!$filter.hasClass("selected")){var $filterTitle=$("li#filter_"+key+" span.filter");$filterTitle.html($filter.html());$filter.addClass("selected");}}}}},showVideo:function(vid,dvid){if(this.currentVideo.vid==vid&&this.currentVideo.dvid==dvid)return;this.videoView.show(vid,dvid);this.currentVideo.vid=vid;this.currentVideo.dvid=dvid;},hideVideo:function(){this.videoView.hide();},dispatch:function(token){var token=token||"";var urlQuery=Ext.urlDecode(token);var canLoad=false;if(urlQuery.q){this.search(urlQuery.q);canLoad=true;}
else{document.location="/search/";}
for(var i=0;i<Search.FilterKeys.length;i++){var filterKey=Search.FilterKeys[i];if(filterKey in urlQuery){this.searchFilter(filterKey,urlQuery[filterKey]);canLoad=true;}}
if(canLoad){this.load();}}});Search.Action=function(key,value){var token=document.location.hash.replace("#","");var urlQuery=Ext.urlDecode(token);urlQuery[key]=value;document.location.hash="#"+Ext.urlEncode(urlQuery);};
