/*
 * The Media Database
 * Copyright(c) 2008, Steven C Norder.
 * 
 * All Rights Reserved
 */


Ext.ns('ZP');ZP.Data={Remote:{get:function(config){if(Ext.isAir){var callback=config.callback;Ext.Ajax.request({url:config.url,callback:function(options,success,response){if(success){var errored=false;}else{var errored=true;}
callback(response,options.url,errored);}})}else{ZP.Data.OpenSocial.Remote.get(config);}},post:function(config){if(Ext.isAir){}else{ZP.Data.OpenSocial.Remote.post(config);}}},MySpace:{Viewer:{set:function(A,C){console.log("Saving in Persistance Storage: "+A+"="+C);var B=opensocial.newDataRequest();var C=Ext.util.JSON.encode(C);var C=C.replace(/&amp;/g,'%26');B.add(B.newUpdatePersonAppDataRequest("VIEWER",A,C));B.send(function(D){if(D.hadError()){console.log("Error while saving!");console.log(D);}})},get:function(key,callback){var req=opensocial.newDataRequest();var idspec=opensocial.newIdSpec({'userId':'VIEWER','groupId':'SELF'});req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER),'viewer');req.add(req.newFetchPersonAppDataRequest(idspec,key),'data');req.send(function(resp){var viewerResp=resp.get('viewer');var dataResp=resp.get('data');if(!viewerResp.hadError()&&!dataResp.hadError()){var viewer=viewerResp.getData();var viewerID=viewer.getId();var viewerID=viewerID.replace('myspace.com:','');var data=dataResp.getData();var viewerData=data[viewerID];callback(viewerData);}});}}},OpenSocial:{Remote:{get:function(config){var param={};param[gadgets.io.RequestParameters.AUTHORIZATION]=gadgets.io.AuthorizationType.SIGNED;param[gadgets.io.RequestParameters.CONTENT_TYPE]=gadgets.io.ContentType.JSON;gadgets.io.makeRequest(config.url,config.callback,param);},post:function(config){var param={};param[gadgets.io.RequestParameters.AUTHORIZATION]=gadgets.io.AuthorizationType.SIGNED;param[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;param[gadgets.io.RequestParameters.CONTENT_TYPE]=gadgets.io.ContentType.JSON;param[gadgets.io.RequestParameters.POST_DATA]=config.postdata;gadgets.io.makeRequest(config.url,config.callback,param);}}}};

Ext.app.SearchField=Ext.extend(Ext.form.TwinTriggerField,{initComponent:function(){Ext.app.SearchField.superclass.initComponent.call(this);this.on('specialkey',function(f,e){if(e.getKey()==e.ENTER){this.onTrigger2Click();}},this);},validationEvent:false,validateOnBlur:false,trigger1Class:'x-form-clear-trigger',trigger2Class:'x-form-search-trigger',hideTrigger1:true,width:180,hasSearch:false,paramName:'query',onTrigger1Click:function(){if(this.hasSearch){this.el.dom.value='';var o={start:0,'start-index':1};this.store.baseParams=this.store.baseParams||{};this.store.baseParams[this.paramName]='';this.store.reload({params:o});this.triggers[0].hide();this.hasSearch=false;}},onTrigger2Click:function(){var v=this.getRawValue();if(v.length<1){this.onTrigger1Click();return;}
var o={start:0,'start-index':1};this.store.baseParams=this.store.baseParams||{};this.store.baseParams[this.paramName]=v;this.store.reload({params:o});this.hasSearch=true;this.triggers[0].show();}});

Ext.PagingToolbar.override({startOffset:0,doLoad:function(start){var o={},pn=this.paramNames;o[pn.start]=start+this.startOffset;o[pn.limit]=this.pageSize;if(this.fireEvent('beforechange',this,o)!==false){this.store.load({params:o});}},onLoad:function(store,r,o){if(!this.rendered){this.dsLoaded=[store,r,o];return;}
this.cursor=o.params?(o.params[this.paramNames.start]-this.startOffset):0;var d=this.getPageData(),ap=d.activePage,ps=d.pages;this.afterTextEl.el.innerHTML=String.format(this.afterPageText,d.pages);this.field.dom.value=ap;this.first.setDisabled(ap==1);this.prev.setDisabled(ap==1);this.next.setDisabled(ap==ps);this.last.setDisabled(ap==ps);this.loading.enable();this.updateInfo();this.fireEvent('change',this,d);}});

Ext.namespace('Ext.ux.dd');Ext.ux.dd.GridReorderDropTarget=function(grid,config){this.target=new Ext.dd.DropTarget(grid.getEl(),{ddGroup:grid.ddGroup||'GridDD',grid:grid,gridDropTarget:this,notifyDrop:function(dd,e,data){if(this.currentRowEl){this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
var t=Ext.lib.Event.getTarget(e);var rindex=this.grid.getView().findRowIndex(t);if(rindex===false||rindex==data.rowIndex){return false;}
if(this.gridDropTarget.fireEvent(this.copy?'beforerowcopy':'beforerowmove',this.gridDropTarget,data.rowIndex,rindex,data.selections,123)===false){return false;}
var ds=this.grid.getStore();var selections=new Array();var keys=ds.data.keys;for(var key in keys){for(var i=0;i<data.selections.length;i++){if(keys[key]==data.selections[i].id){if(rindex==key){return false;}
selections.push(data.selections[i]);}}}
if(rindex>data.rowIndex&&this.rowPosition<0){rindex--;}
if(rindex<data.rowIndex&&this.rowPosition>0){rindex++;}
if(rindex>data.rowIndex&&data.selections.length>1){rindex=rindex-(data.selections.length-1);}
if(rindex==data.rowIndex){return false;}
if(!this.copy){for(var i=0;i<data.selections.length;i++){ds.remove(ds.getById(data.selections[i].id));}}
for(var i=selections.length-1;i>=0;i--){var insertIndex=rindex;ds.insert(insertIndex,selections[i]);}
var sm=this.grid.getSelectionModel();if(sm){sm.selectRecords(data.selections);}
this.gridDropTarget.fireEvent(this.copy?'afterrowcopy':'afterrowmove',this.gridDropTarget,data.rowIndex,rindex,data.selections);return true;},notifyOver:function(dd,e,data){var t=Ext.lib.Event.getTarget(e);var rindex=this.grid.getView().findRowIndex(t);var ds=this.grid.getStore();var keys=ds.data.keys;for(var key in keys){for(var i=0;i<data.selections.length;i++){if(keys[key]==data.selections[i].id){if(rindex==key){if(this.currentRowEl){this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
return this.dropNotAllowed;}}}}
if(rindex<0||rindex===false){this.currentRowEl.removeClass('grid-row-insert-above');return this.dropNotAllowed;}
try{var currentRow=this.grid.getView().getRow(rindex);var resolvedRow=new Ext.Element(currentRow).getY()-this.grid.getView().scroller.dom.scrollTop;var rowHeight=currentRow.offsetHeight;this.rowPosition=e.getPageY()-resolvedRow-(rowHeight/2);if(this.currentRowEl){this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
if(this.rowPosition>0){this.currentRowEl=new Ext.Element(currentRow);this.currentRowEl.addClass('grid-row-insert-below');}else{if(rindex-1>=0){var previousRow=this.grid.getView().getRow(rindex-1);this.currentRowEl=new Ext.Element(previousRow);this.currentRowEl.addClass('grid-row-insert-below');}else{this.currentRowEl.addClass('grid-row-insert-above');}}}catch(err){console.warn(err);rindex=false;}
return(rindex===false)?this.dropNotAllowed:this.dropAllowed;},notifyOut:function(dd,e,data){if(this.currentRowEl){this.currentRowEl.removeClass('grid-row-insert-above');this.currentRowEl.removeClass('grid-row-insert-below');}}});if(config){Ext.apply(this.target,config);if(config.listeners){Ext.apply(this,{listeners:config.listeners});}}
this.addEvents({'beforerowmove':true,'afterrowmove':true,'beforerowcopy':true,'afterrowcopy':true});Ext.ux.dd.GridReorderDropTarget.superclass.constructor.call(this);};Ext.extend(Ext.ux.dd.GridReorderDropTarget,Ext.util.Observable,{getTarget:function(){return this.target;},getGrid:function(){return this.target.grid;},getCopy:function(){return this.target.copy?true:false;},setCopy:function(b){this.target.copy=b?true:false;}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.DragZone=function(grid,config){Ext.ux.grid.livegrid.DragZone.superclass.constructor.call(this,grid,config);this.view.ds.on('beforeselectionsload',this._onBeforeSelectionsLoad,this);this.view.ds.on('selectionsload',this._onSelectionsLoad,this);};Ext.extend(Ext.ux.grid.livegrid.DragZone,Ext.grid.GridDragZone,{isDropValid:true,onInitDrag:function(e)
{this.view.ds.loadSelections(this.grid.selModel.getPendingSelections(true));Ext.ux.grid.livegrid.DragZone.superclass.onInitDrag.call(this,e);},_onBeforeSelectionsLoad:function()
{this.isDropValid=false;Ext.fly(this.proxy.el.dom.firstChild).addClass('ext-ux-livegrid-drop-waiting');},_onSelectionsLoad:function()
{this.isDropValid=true;this.ddel.innerHTML=this.grid.getDragDropText();Ext.fly(this.proxy.el.dom.firstChild).removeClass('ext-ux-livegrid-drop-waiting');}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.GridPanel=Ext.extend(Ext.grid.GridPanel,{onRender:function(ct,position)
{Ext.ux.grid.livegrid.GridPanel.superclass.onRender.call(this,ct,position);var ds=this.getStore();if(ds._autoLoad===true){delete ds._autoLoad;ds.load();}},walkCells:function(row,col,step,fn,scope)
{var ds=this.store;var _oF=ds.getCount;ds.getCount=ds.getTotalCount;var ret=Ext.ux.grid.livegrid.GridPanel.superclass.walkCells.call(this,row,col,step,fn,scope);ds.getCount=_oF;return ret;}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.GridView=function(config){this.addEvents({'beforebuffer':true,'buffer':true,'bufferfailure':true,'cursormove':true});this.horizontalScrollOffset=17;this.loadMask=false;Ext.apply(this,config);this.templates={};this.templates.master=new Ext.Template('<div class="x-grid3" hidefocus="true"><div class="ext-ux-livegrid-liveScroller"><div></div></div>','<div class="x-grid3-viewport"">','<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>','<div class="x-grid3-scroller" style="overflow-y:hidden !important;"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',"</div>",'<div class="x-grid3-resize-marker">&#160;</div>','<div class="x-grid3-resize-proxy">&#160;</div>',"</div>");this._gridViewSuperclass=Ext.ux.grid.livegrid.GridView.superclass;this._gridViewSuperclass.constructor.call(this);};Ext.extend(Ext.ux.grid.livegrid.GridView,Ext.grid.GridView,{_maskIndex:20001,hdHeight:0,rowClipped:0,liveScroller:null,liveScrollerInset:null,rowHeight:-1,visibleRows:1,lastIndex:-1,lastRowIndex:0,lastScrollPos:0,rowIndex:0,isBuffering:false,requestQueue:-1,loadMask:null,isPrebuffering:false,reset:function(forceReload)
{if(forceReload===false){this.ds.modified=[];this.rowIndex=0;this.lastScrollPos=0;this.lastRowIndex=0;this.lastIndex=0;this.adjustVisibleRows();this.adjustScrollerPos(-this.liveScroller.dom.scrollTop,true);this.showLoadMask(false);this.refresh(true);this.fireEvent('cursormove',this,0,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);return false;}else{var params={};var sInfo=this.ds.sortInfo;if(sInfo){params={dir:sInfo.direction,sort:sInfo.field};}
return this.ds.load({params:params});}},renderUI:function()
{var g=this.grid;var dEnabled=g.enableDragDrop||g.enableDrag;g.enableDragDrop=false;g.enableDrag=false;this._gridViewSuperclass.renderUI.call(this);var g=this.grid;g.enableDragDrop=dEnabled;g.enableDrag=dEnabled;if(dEnabled){var dd=new Ext.ux.grid.livegrid.DragZone(g,{ddGroup:g.ddGroup||'GridDD'});}
if(this.loadMask){this.loadMask=new Ext.LoadMask(this.mainBody.dom.parentNode.parentNode,this.loadMask);}},init:function(grid)
{this._gridViewSuperclass.init.call(this,grid);grid.on('expand',this._onExpand,this);},initData:function(ds,cm)
{if(this.ds){this.ds.un('bulkremove',this.onBulkRemove,this);this.ds.un('beforeload',this.onBeforeLoad,this);}
if(ds){ds.on('bulkremove',this.onBulkRemove,this);ds.on('beforeload',this.onBeforeLoad,this);}
this._gridViewSuperclass.initData.call(this,ds,cm);},renderBody:function()
{var markup=this.renderRows(0,this.visibleRows-1);return this.templates.body.apply({rows:markup});},doRender:function(cs,rs,ds,startRow,colCount,stripe)
{return this._gridViewSuperclass.doRender.call(this,cs,rs,ds,startRow+this.ds.bufferRange[0],colCount,stripe);},initElements:function()
{var E=Ext.Element;var el=this.grid.getGridEl().dom.firstChild;var cs=el.childNodes;this.el=new E(el);this.mainWrap=new E(cs[1]);this.liveScroller=new E(cs[0]);this.liveScrollerInset=this.liveScroller.dom.firstChild;this.liveScroller.on('scroll',this.onLiveScroll,this,{buffer:this.scrollDelay});var thd=this.mainWrap.dom.firstChild;this.mainHd=new E(thd);this.hdHeight=thd.offsetHeight;this.innerHd=this.mainHd.dom.firstChild;this.scroller=new E(this.mainWrap.dom.childNodes[1]);if(this.forceFit){this.scroller.setStyle('overflow-x','hidden');}
this.mainBody=new E(this.scroller.dom.firstChild);this.mainBody.on('mousewheel',this.handleWheel,this);this.focusEl=new E(this.scroller.dom.childNodes[1]);this.focusEl.swallowEvent("click",true);this.resizeMarker=new E(cs[2]);this.resizeProxy=new E(cs[3]);},layout:function()
{if(!this.mainBody){return;}
var g=this.grid;var c=g.getGridEl(),cm=this.cm,expandCol=g.autoExpandColumn,gv=this;var csize=c.getSize(true);var vw=csize.width;if(vw<20||csize.height<20){return;}
if(g.autoHeight){this.scroller.dom.style.overflow='visible';}else{this.el.setSize(csize.width,csize.height);var hdHeight=this.mainHd.getHeight();var vh=csize.height-(hdHeight);this.scroller.setSize(vw,vh);if(this.innerHd){this.innerHd.style.width=(vw)+'px';}}
this.liveScroller.dom.style.top=this.hdHeight+"px";if(this.forceFit){if(this.lastViewWidth!=vw){this.fitColumns(false,false);this.lastViewWidth=vw;}}else{this.autoExpand();}
this.adjustVisibleRows();this.adjustBufferInset();this.onLayout(vw,vh);},removeRow:function(row)
{Ext.removeNode(this.getRow(row));},removeRows:function(firstRow,lastRow)
{var bd=this.mainBody.dom;for(var rowIndex=firstRow;rowIndex<=lastRow;rowIndex++){Ext.removeNode(bd.childNodes[firstRow]);}},_onExpand:function(panel)
{this.adjustVisibleRows();this.adjustBufferInset();this.adjustScrollerPos(this.rowHeight*this.rowIndex,true);},onColumnMove:function(cm,oldIndex,newIndex)
{this.indexMap=null;this.replaceLiveRows(this.rowIndex,true);this.updateHeaders();this.updateHeaderSortState();this.afterMove(newIndex);},onColumnWidthUpdated:function(col,w,tw)
{this.adjustVisibleRows();this.adjustBufferInset();},onAllColumnWidthsUpdated:function(ws,tw)
{this.adjustVisibleRows();this.adjustBufferInset();},onRowSelect:function(row)
{if(row<this.rowIndex||row>this.rowIndex+this.visibleRows){return;}
this.addRowClass(row,"x-grid3-row-selected");},onRowDeselect:function(row)
{if(row<this.rowIndex||row>this.rowIndex+this.visibleRows){return;}
this.removeRowClass(row,"x-grid3-row-selected");},onClear:function()
{this.reset(false);},onBulkRemove:function(store,removedData)
{var record=null;var index=0;var viewIndex=0;var len=removedData.length;var removedInView=false;var removedAfterView=false;var scrollerAdjust=0;if(len==0){return;}
var tmpRowIndex=this.rowIndex;var removedBefore=0;var removedAfter=0;var removedIn=0;for(var i=0;i<len;i++){record=removedData[i][0];index=removedData[i][1];viewIndex=(index!=Number.MIN_VALUE&&index!=Number.MAX_VALUE)?index+this.ds.bufferRange[0]:index;if(viewIndex<this.rowIndex){removedBefore++;}else if(viewIndex>=this.rowIndex&&viewIndex<=this.rowIndex+(this.visibleRows-1)){removedIn++;}else if(viewIndex>=this.rowIndex+this.visibleRows){removedAfter++;}
this.fireEvent("beforerowremoved",this,viewIndex,record);this.fireEvent("rowremoved",this,viewIndex,record);}
var totalLength=this.ds.totalLength;this.rowIndex=Math.max(0,Math.min(this.rowIndex-removedBefore,totalLength-(this.visibleRows-1)));this.lastRowIndex=this.rowIndex;this.adjustScrollerPos(-(removedBefore*this.rowHeight),true);this.updateLiveRows(this.rowIndex,true);this.adjustBufferInset();this.processRows(0,undefined,false);},onRemove:function(ds,record,index)
{this.onBulkRemove(ds,[[record,index]]);},onAdd:function(ds,records,index)
{var recordLen=records.length;if(index==Number.MAX_VALUE||index==Number.MIN_VALUE){this.fireEvent("beforerowsinserted",this,index,index);if(index==Number.MIN_VALUE){this.rowIndex=this.rowIndex+recordLen;this.lastRowIndex=this.rowIndex;this.adjustBufferInset();this.adjustScrollerPos(this.rowHeight*recordLen,true);this.fireEvent("rowsinserted",this,index,index,recordLen);this.processRows(0,undefined,false);this.fireEvent('cursormove',this,this.rowIndex,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);return;}
this.adjustBufferInset();this.fireEvent("rowsinserted",this,index,index,recordLen);return;}
var start=index+this.ds.bufferRange[0];var end=start+(recordLen-1);var len=this.getRows().length;var firstRow=0;var lastRow=0;if(start>this.rowIndex+(this.visibleRows-1)){this.fireEvent("beforerowsinserted",this,start,end);this.fireEvent("rowsinserted",this,start,end,recordLen);this.adjustVisibleRows();this.adjustBufferInset();}
else if(start>=this.rowIndex&&start<=this.rowIndex+(this.visibleRows-1)){firstRow=index;lastRow=index+(recordLen-1);this.lastRowIndex=this.rowIndex;this.rowIndex=(start>this.rowIndex)?this.rowIndex:start;this.insertRows(ds,firstRow,lastRow);if(this.lastRowIndex!=this.rowIndex){this.fireEvent('cursormove',this,this.rowIndex,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);}
this.adjustVisibleRows();this.adjustBufferInset();}
else if(start<this.rowIndex){this.fireEvent("beforerowsinserted",this,start,end);this.rowIndex=this.rowIndex+recordLen;this.lastRowIndex=this.rowIndex;this.adjustVisibleRows();this.adjustBufferInset();this.adjustScrollerPos(this.rowHeight*recordLen,true);this.fireEvent("rowsinserted",this,start,end,recordLen);this.processRows(0,undefined,true);this.fireEvent('cursormove',this,this.rowIndex,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);}},onBeforeLoad:function(store,options)
{options.params=options.params||{};var apply=Ext.apply;apply(options,{scope:this,callback:function(){this.reset(false);}});apply(options.params,{start:0,limit:this.ds.bufferSize});return true;},onLoad:function(o1,o2,options)
{this.adjustBufferInset();},onDataChange:function(store)
{this.updateHeaderSortState();},liveBufferUpdate:function(records,options,success)
{if(success===true){this.fireEvent('buffer',this,this.ds,this.rowIndex,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength,options);this.isBuffering=false;this.isPrebuffering=false;this.showLoadMask(false);this.grid.selModel.replaceSelections(records);if(this.isInRange(this.rowIndex)){this.replaceLiveRows(this.rowIndex,options.forceRepaint);}else{this.updateLiveRows(this.rowIndex);}
if(this.requestQueue>=0){var offset=this.requestQueue;this.requestQueue=-1;this.updateLiveRows(offset);}
return;}else{this.fireEvent('bufferfailure',this,this.ds,options);}
this.requestQueue=-1;this.isBuffering=false;this.isPrebuffering=false;this.showLoadMask(false);},handleWheel:function(e)
{if(this.rowHeight==-1){e.stopEvent();return;}
var d=e.getWheelDelta();this.adjustScrollerPos(-(d*this.rowHeight));e.stopEvent();},onLiveScroll:function()
{var scrollTop=this.liveScroller.dom.scrollTop;var cursor=Math.floor((scrollTop)/this.rowHeight);this.rowIndex=cursor;if(cursor==this.lastRowIndex){return;}
this.updateLiveRows(cursor);this.lastScrollPos=this.liveScroller.dom.scrollTop;},refreshRow:function(record)
{var ds=this.ds,index;if(typeof record=='number'){index=record;record=ds.getAt(index);}else{index=ds.indexOf(record);}
var viewIndex=index+this.ds.bufferRange[0];if(viewIndex<this.rowIndex||viewIndex>=this.rowIndex+this.visibleRows){this.fireEvent("rowupdated",this,viewIndex,record);return;}
this.insertRows(ds,index,index,true);this.fireEvent("rowupdated",this,viewIndex,record);},processRows:function(startRow,skipStripe,paintSelections)
{skipStripe=skipStripe||!this.grid.stripeRows;startRow=0;var rows=this.getRows();var cls=' x-grid3-row-alt ';var cursor=this.rowIndex;var index=0;var selections=this.grid.selModel.selections;var ds=this.ds;var row=null;for(var i=startRow,len=rows.length;i<len;i++){index=i+cursor;row=rows[i];row.rowIndex=index;if(paintSelections!==false){if(this.grid.selModel.isSelected(this.ds.getAt(index))===true){this.addRowClass(index,"x-grid3-row-selected");}else{this.removeRowClass(index,"x-grid3-row-selected");}
this.fly(row).removeClass("x-grid3-row-over");}
if(!skipStripe){var isAlt=((index+1)%2==0);var hasAlt=(' '+row.className+' ').indexOf(cls)!=-1;if(isAlt==hasAlt){continue;}
if(isAlt){row.className+=" x-grid3-row-alt";}else{row.className=row.className.replace("x-grid3-row-alt","");}}}},insertRows:function(dm,firstRow,lastRow,isUpdate)
{var viewIndexFirst=firstRow+this.ds.bufferRange[0];var viewIndexLast=lastRow+this.ds.bufferRange[0];if(!isUpdate){this.fireEvent("beforerowsinserted",this,viewIndexFirst,viewIndexLast);}
if(isUpdate!==true&&(this.getRows().length+(lastRow-firstRow))>=this.visibleRows){this.removeRows((this.visibleRows-1)-(lastRow-firstRow),this.visibleRows-1);}else if(isUpdate){this.removeRows(viewIndexFirst-this.rowIndex,viewIndexLast-this.rowIndex);}
var lastRenderRow=(firstRow==lastRow)?lastRow:Math.min(lastRow,(this.rowIndex-this.ds.bufferRange[0])+(this.visibleRows-1));var html=this.renderRows(firstRow,lastRenderRow);var before=this.getRow(viewIndexFirst);if(before){Ext.DomHelper.insertHtml('beforeBegin',before,html);}else{Ext.DomHelper.insertHtml('beforeEnd',this.mainBody.dom,html);}
if(isUpdate===true){var rows=this.getRows();var cursor=this.rowIndex;for(var i=0,max_i=rows.length;i<max_i;i++){rows[i].rowIndex=cursor+i;}}
if(!isUpdate){this.fireEvent("rowsinserted",this,viewIndexFirst,viewIndexLast,(viewIndexLast-viewIndexFirst)+1);this.processRows(0,undefined,true);}},getRow:function(row)
{if(row-this.rowIndex<0){return null;}
return this.getRows()[row-this.rowIndex];},getCell:function(row,col)
{var row=this.getRow(row);return row?row.getElementsByTagName('td')[col]:null;},focusCell:function(row,col,hscroll)
{var xy=this.ensureVisible(row,col,hscroll);if(!xy){return;}
this.focusEl.setXY(xy);if(Ext.isGecko){this.focusEl.focus();}else{this.focusEl.focus.defer(1,this.focusEl);}},ensureVisible:function(row,col,hscroll)
{if(typeof row!="number"){row=row.rowIndex;}
if(row<0||row>=this.ds.totalLength){return;}
col=(col!==undefined?col:0);var rowInd=row-this.rowIndex;if(this.rowClipped&&row==this.rowIndex+this.visibleRows-1){this.adjustScrollerPos(this.rowHeight);}else if(row>=this.rowIndex+this.visibleRows){this.adjustScrollerPos(((row-(this.rowIndex+this.visibleRows))+1)*this.rowHeight);}else if(row<=this.rowIndex){this.adjustScrollerPos((rowInd)*this.rowHeight);}
var rowEl=this.getRow(row),cellEl;if(!rowEl){return;}
if(!(hscroll===false&&col===0)){while(this.cm.isHidden(col)){col++;}
cellEl=this.getCell(row,col);}
var c=this.scroller.dom;if(hscroll!==false){var cleft=parseInt(cellEl.offsetLeft,10);var cright=cleft+cellEl.offsetWidth;var sleft=parseInt(c.scrollLeft,10);var sright=sleft+c.clientWidth;if(cleft<sleft){c.scrollLeft=cleft;}else if(cright>sright){c.scrollLeft=cright-c.clientWidth;}}
return cellEl?Ext.fly(cellEl).getXY():[c.scrollLeft+this.el.getX(),Ext.fly(rowEl).getY()];},isRecordRendered:function(record)
{var ind=this.ds.indexOf(record);if(ind>=this.rowIndex&&ind<this.rowIndex+this.visibleRows){return true;}
return false;},isInRange:function(rowIndex)
{var lastRowIndex=Math.min(this.ds.totalLength-1,rowIndex+(this.visibleRows-1));return(rowIndex>=this.ds.bufferRange[0])&&(lastRowIndex<=this.ds.bufferRange[1]);},getPredictedBufferIndex:function(index,inRange,down)
{if(!inRange){if(index+this.ds.bufferSize>=this.ds.totalLength){return this.ds.totalLength-this.ds.bufferSize;}
return Math.max(0,(index+this.visibleRows)-Math.round(this.ds.bufferSize/2));}
if(!down){return Math.max(0,(index-this.ds.bufferSize)+this.visibleRows);}
if(down){return Math.max(0,Math.min(index,this.ds.totalLength-this.ds.bufferSize));}},updateLiveRows:function(index,forceRepaint,forceReload)
{var inRange=this.isInRange(index);if(this.isBuffering){if(this.isPrebuffering){if(inRange){this.replaceLiveRows(index);}else{this.showLoadMask(true);}}
this.fireEvent('cursormove',this,index,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);this.requestQueue=index;return;}
var lastIndex=this.lastIndex;this.lastIndex=index;var inRange=this.isInRange(index);var down=false;if(inRange&&forceReload!==true){this.replaceLiveRows(index,forceRepaint);this.fireEvent('cursormove',this,index,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength);if(index>lastIndex){down=true;var totalCount=this.ds.totalLength;if(index+this.visibleRows+this.nearLimit<=this.ds.bufferRange[1]){return;}
if(this.ds.bufferRange[1]+1>=totalCount){return;}}else if(index<lastIndex){down=false;if(this.ds.bufferRange[0]<=0){return;}
if(index-this.nearLimit>this.ds.bufferRange[0]){return;}}else{return;}
this.isPrebuffering=true;}
this.isBuffering=true;var bufferOffset=this.getPredictedBufferIndex(index,inRange,down);if(!inRange){this.showLoadMask(true);}
this.ds.suspendEvents();var sInfo=this.ds.sortInfo;var params={};if(this.ds.lastOptions){Ext.apply(params,this.ds.lastOptions.params);}
params.start=bufferOffset;params.limit=this.ds.bufferSize;if(sInfo){params.dir=sInfo.direction;params.sort=sInfo.field;}
var opts={forceRepaint:forceRepaint,callback:this.liveBufferUpdate,scope:this,params:params};this.fireEvent('beforebuffer',this,this.ds,index,Math.min(this.ds.totalLength,this.visibleRows-this.rowClipped),this.ds.totalLength,opts);this.ds.load(opts);this.ds.resumeEvents();},showLoadMask:function(show)
{if(this.loadMask==null){if(show){this.loadMask=new Ext.LoadMask(this.mainBody.dom.parentNode.parentNode,this.loadMaskConfig);}else{return;}}
if(show){this.loadMask.show();this.liveScroller.setStyle('zIndex',this._maskIndex);}else{this.loadMask.hide();this.liveScroller.setStyle('zIndex',1);}},replaceLiveRows:function(cursor,forceReplace,processRows)
{var spill=cursor-this.lastRowIndex;if(spill==0&&forceReplace!==true){return;}
var append=spill>0;spill=Math.abs(spill);var bufferRange=this.ds.bufferRange;var cursorBuffer=cursor-bufferRange[0];var lpIndex=Math.min(cursorBuffer+this.visibleRows-1,bufferRange[1]-bufferRange[0]);if(spill>=this.visibleRows||spill==0){this.mainBody.update(this.renderRows(cursorBuffer,lpIndex));}else{if(append){this.removeRows(0,spill-1);if(cursorBuffer+this.visibleRows-spill<=bufferRange[1]-bufferRange[0]){var html=this.renderRows(cursorBuffer+this.visibleRows-spill,lpIndex);Ext.DomHelper.insertHtml('beforeEnd',this.mainBody.dom,html);}}else{this.removeRows(this.visibleRows-spill,this.visibleRows-1);var html=this.renderRows(cursorBuffer,cursorBuffer+spill-1);Ext.DomHelper.insertHtml('beforeBegin',this.mainBody.dom.firstChild,html);}}
if(processRows!==false){this.processRows(0,undefined,true);}
this.lastRowIndex=cursor;},adjustBufferInset:function()
{var liveScrollerDom=this.liveScroller.dom;var g=this.grid,ds=g.store;var c=g.getGridEl();var elWidth=c.getSize().width;var hiddenRows=(ds.totalLength==this.visibleRows-this.rowClipped)?0:Math.max(0,ds.totalLength-(this.visibleRows-this.rowClipped));if(hiddenRows==0){this.scroller.setWidth(elWidth);liveScrollerDom.style.display='none';return;}else{this.scroller.setWidth(elWidth-this.scrollOffset);liveScrollerDom.style.display='';}
var scrollbar=this.cm.getTotalWidth()+this.scrollOffset>elWidth;var contHeight=liveScrollerDom.parentNode.offsetHeight+
((ds.totalLength>0&&scrollbar)?-this.horizontalScrollOffset:0)
-this.hdHeight;liveScrollerDom.style.height=Math.max(contHeight,this.horizontalScrollOffset*2)+"px";if(this.rowHeight==-1){return;}
this.liveScrollerInset.style.height=(hiddenRows==0?0:contHeight+(hiddenRows*this.rowHeight))+"px";},adjustVisibleRows:function()
{if(this.rowHeight==-1){if(this.getRows()[0]){this.rowHeight=this.getRows()[0].offsetHeight;if(this.rowHeight<=0){this.rowHeight=-1;return;}}else{return;}}
var g=this.grid,ds=g.store;var c=g.getGridEl();var cm=this.cm;var size=c.getSize();var width=size.width;var vh=size.height;var vw=width-this.scrollOffset;if(cm.getTotalWidth()>vw){vh-=this.horizontalScrollOffset;}
vh-=this.mainHd.getHeight();var totalLength=ds.totalLength||0;var visibleRows=Math.max(1,Math.floor(vh/this.rowHeight));this.rowClipped=0;if(totalLength>visibleRows&&this.rowHeight/3<(vh-(visibleRows*this.rowHeight))){visibleRows=Math.min(visibleRows+1,totalLength);this.rowClipped=1;}
if(this.visibleRows==visibleRows){return;}
this.visibleRows=visibleRows;if(this.isBuffering){return;}
if(this.rowIndex+(visibleRows-this.rowClipped)>totalLength){this.rowIndex=Math.max(0,totalLength-(visibleRows-this.rowClipped));this.lastRowIndex=this.rowIndex;}
this.updateLiveRows(this.rowIndex,true);},adjustScrollerPos:function(pixels,suspendEvent)
{if(pixels==0){return;}
var liveScroller=this.liveScroller;var scrollDom=liveScroller.dom;if(suspendEvent===true){liveScroller.un('scroll',this.onLiveScroll,this);}
this.lastScrollPos=scrollDom.scrollTop;scrollDom.scrollTop+=pixels;if(suspendEvent===true){scrollDom.scrollTop=scrollDom.scrollTop;liveScroller.on('scroll',this.onLiveScroll,this,{buffer:this.scrollDelay});}}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.JsonReader=function(meta,recordType){Ext.ux.grid.livegrid.JsonReader.superclass.constructor.call(this,meta,recordType);};Ext.extend(Ext.ux.grid.livegrid.JsonReader,Ext.data.JsonReader,{readRecords:function(o)
{var s=this.meta;if(!this.ef&&s.versionProperty){this.getVersion=this.getJsonAccessor(s.versionProperty);}
if(!this.__readRecords){this.__readRecords=Ext.ux.grid.livegrid.JsonReader.superclass.readRecords;}
var intercept=this.__readRecords.call(this,o);if(s.versionProperty){var v=this.getVersion(o);intercept.version=(v===undefined||v==="")?null:v;}
return intercept;}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.RowSelectionModel=function(config){this.addEvents({'selectiondirty':true});Ext.apply(this,config);this.pendingSelections={};Ext.ux.grid.livegrid.RowSelectionModel.superclass.constructor.call(this);};Ext.extend(Ext.ux.grid.livegrid.RowSelectionModel,Ext.grid.RowSelectionModel,{initEvents:function()
{Ext.ux.grid.livegrid.RowSelectionModel.superclass.initEvents.call(this);this.grid.view.on('rowsinserted',this.onAdd,this);this.grid.store.on('selectionsload',this.onSelectionsLoad,this);},onRemove:function(v,index,r)
{var ranges=this.getPendingSelections();var rangesLength=ranges.length;var selectionChanged=false;if(index==Number.MIN_VALUE||index==Number.MAX_VALUE){if(r){if(this.isIdSelected(r.id)&&index==Number.MIN_VALUE){this.shiftSelections(this.grid.store.bufferRange[1],-1);}
this.selections.remove(r);selectionChanged=true;}
if(index==Number.MIN_VALUE){this.clearPendingSelections(0,this.grid.store.bufferRange[0]);}else{this.clearPendingSelections(this.grid.store.bufferRange[1]);}
if(rangesLength!=0){this.fireEvent('selectiondirty',this,index,1);}}else{selectionChanged=this.isIdSelected(r.id);if(!selectionChanged){return;}
this.selections.remove(r);if(rangesLength!=0){var startRange=ranges[0];var endRange=ranges[rangesLength-1];if(index<=endRange||index<=startRange){this.shiftSelections(index,-1);this.fireEvent('selectiondirty',this,index,1);}}}
if(selectionChanged){this.fireEvent('selectionchange',this);}},onAdd:function(store,index,endIndex,recordLength)
{var ranges=this.getPendingSelections();var rangesLength=ranges.length;if((index==Number.MIN_VALUE||index==Number.MAX_VALUE)){if(index==Number.MIN_VALUE){this.clearPendingSelections(0,this.grid.store.bufferRange[0]);this.shiftSelections(this.grid.store.bufferRange[1],recordLength);}else{this.clearPendingSelections(this.grid.store.bufferRange[1]);}
if(rangesLength!=0){this.fireEvent('selectiondirty',this,index,r);}
return;}
var startRange=ranges[0];var endRange=ranges[rangesLength-1];var viewIndex=index;if(viewIndex<=endRange||viewIndex<=startRange){this.fireEvent('selectiondirty',this,viewIndex,recordLength);this.shiftSelections(viewIndex,recordLength);}},shiftSelections:function(startRow,length)
{var index=0;var newIndex=0;var newRequests={};var ds=this.grid.store;var storeIndex=startRow-ds.bufferRange[0];var newStoreIndex=0;var totalLength=this.grid.store.totalLength;var rec=null;var ranges=this.getPendingSelections();var rangesLength=ranges.length;if(rangesLength==0){return;}
for(var i=0;i<rangesLength;i++){index=ranges[i];if(index<startRow){continue;}
newIndex=index+length;newStoreIndex=storeIndex+length;if(newIndex>=totalLength){break;}
rec=ds.getAt(newStoreIndex);if(rec){this.selections.add(rec);}else{newRequests[newIndex]=true;}}
this.pendingSelections=newRequests;},onSelectionsLoad:function(store,records,ranges)
{this.replaceSelections(records);},hasNext:function()
{return this.last!==false&&(this.last+1)<this.grid.store.getTotalCount();},getCount:function()
{return this.selections.length+this.getPendingSelections().length;},isSelected:function(index)
{if(typeof index=="number"){var orgInd=index;index=this.grid.store.getAt(orgInd);if(!index){var ind=this.getPendingSelections().indexOf(orgInd);if(ind!=-1){return true;}
return false;}}
var r=index;return(r&&this.selections.key(r.id)?true:false);},deselectRecord:function(record,preventViewNotify)
{if(this.locked){return;}
var isSelected=this.selections.key(record.id);if(!isSelected){return;}
var store=this.grid.store;var index=store.indexOfId(record.id);if(index==-1){index=store.findInsertIndex(record);if(index!=Number.MIN_VALUE&&index!=Number.MAX_VALUE){index+=store.bufferRange[0];}}else{delete this.pendingSelections[index];}
if(this.last==index){this.last=false;}
if(this.lastActive==index){this.lastActive=false;}
this.selections.remove(record);if(!preventViewNotify){this.grid.getView().onRowDeselect(index);}
this.fireEvent("rowdeselect",this,index,record);this.fireEvent("selectionchange",this);},deselectRow:function(index,preventViewNotify)
{if(this.locked)return;if(this.last==index){this.last=false;}
if(this.lastActive==index){this.lastActive=false;}
var r=this.grid.store.getAt(index);delete this.pendingSelections[index];if(r){this.selections.remove(r);}
if(!preventViewNotify){this.grid.getView().onRowDeselect(index);}
this.fireEvent("rowdeselect",this,index,r);this.fireEvent("selectionchange",this);},selectRow:function(index,keepExisting,preventViewNotify)
{if(this.locked||index<0||index>=this.grid.store.getTotalCount()){return;}
var r=this.grid.store.getAt(index);if(this.fireEvent("beforerowselect",this,index,keepExisting,r)!==false){if(!keepExisting||this.singleSelect){this.clearSelections();}
if(r){this.selections.add(r);delete this.pendingSelections[index];}else{this.pendingSelections[index]=true;}
this.last=this.lastActive=index;if(!preventViewNotify){this.grid.getView().onRowSelect(index);}
this.fireEvent("rowselect",this,index,r);this.fireEvent("selectionchange",this);}},clearPendingSelections:function(startIndex,endIndex)
{if(endIndex==undefined){endIndex=Number.MAX_VALUE;}
var newSelections={};var ranges=this.getPendingSelections();var rangesLength=ranges.length;var index=0;for(var i=0;i<rangesLength;i++){index=ranges[i];if(index<=endIndex&&index>=startIndex){continue;}
newSelections[index]=true;}
this.pendingSelections=newSelections;},replaceSelections:function(records)
{if(!records||records.length==0){return;}
var ds=this.grid.store;var rec=null;var assigned=[];var ranges=this.getPendingSelections();var rangesLength=ranges.length;var selections=this.selections;var index=0;for(var i=0;i<rangesLength;i++){index=ranges[i];rec=ds.getAt(index);if(rec){selections.add(rec);assigned.push(rec.id);delete this.pendingSelections[index];}}
var id=null;for(i=0,len=records.length;i<len;i++){rec=records[i];id=rec.id;if(assigned.indexOf(id)==-1&&selections.containsKey(id)){selections.add(rec);}}},getPendingSelections:function(asRange)
{var index=1;var ranges=[];var currentRange=0;var tmpArray=[];for(var i in this.pendingSelections){tmpArray.push(parseInt(i));}
tmpArray.sort(function(o1,o2){if(o1>o2){return 1;}else if(o1<o2){return-1;}else{return 0;}});if(!asRange){return tmpArray;}
var max_i=tmpArray.length;if(max_i==0){return[];}
ranges[currentRange]=[tmpArray[0],tmpArray[0]];for(var i=0,max_i=max_i-1;i<max_i;i++){if(tmpArray[i+1]-tmpArray[i]==1){ranges[currentRange][1]=tmpArray[i+1];}else{currentRange++;ranges[currentRange]=[tmpArray[i+1],tmpArray[i+1]];}}
return ranges;},clearSelections:function(fast)
{if(this.locked)return;if(fast!==true){var ds=this.grid.store;var s=this.selections;var ind=-1;s.each(function(r){ind=ds.indexOfId(r.id);if(ind!=-1){this.deselectRow(ind+ds.bufferRange[0]);}},this);s.clear();this.pendingSelections={};}else{this.selections.clear();this.pendingSelections={};}
this.last=false;},selectRange:function(startRow,endRow,keepExisting)
{if(this.locked){return;}
if(!keepExisting){this.clearSelections();}
if(startRow<=endRow){for(var i=startRow;i<=endRow;i++){this.selectRow(i,true);}}else{for(var i=startRow;i>=endRow;i--){this.selectRow(i,true);}}}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.Store=function(config){config=config||{};config.remoteSort=true;this._autoLoad=config.autoLoad?true:false;config.autoLoad=false;this.addEvents('bulkremove','versionchange','beforeselectionsload','selectionsload');Ext.ux.grid.livegrid.Store.superclass.constructor.call(this,config);this.totalLength=0;this.bufferRange=[-1,-1];this.on('clear',function(){this.bufferRange=[-1,-1];},this);if(this.url&&!this.selectionsProxy){this.selectionsProxy=new Ext.data.HttpProxy({url:this.url});}};Ext.extend(Ext.ux.grid.livegrid.Store,Ext.data.Store,{version:null,insert:function(index,records)
{records=[].concat(records);index=index>=this.bufferSize?Number.MAX_VALUE:index;if(index==Number.MIN_VALUE||index==Number.MAX_VALUE){var l=records.length;if(index==Number.MIN_VALUE){this.bufferRange[0]+=l;this.bufferRange[1]+=l;}
this.totalLength+=l;this.fireEvent("add",this,records,index);return;}
var split=false;var insertRecords=records;if(records.length+index>=this.bufferSize){split=true;insertRecords=records.splice(0,this.bufferSize-index)}
this.totalLength+=insertRecords.length;if(this.bufferRange[0]<=-1){this.bufferRange[0]=0;}
if(this.bufferRange[1]<(this.bufferSize-1)){this.bufferRange[1]=Math.min(this.bufferRange[1]+insertRecords.length,this.bufferSize-1);}
for(var i=0,len=insertRecords.length;i<len;i++){this.data.insert(index,insertRecords[i]);insertRecords[i].join(this);}
while(this.getCount()>this.bufferSize){this.data.remove(this.data.last());}
this.fireEvent("add",this,insertRecords,index);if(split==true){this.fireEvent("add",this,records,Number.MAX_VALUE);}},remove:function(record,suspendEvent)
{var index=this._getIndex(record);if(index<0){this.totalLength-=1;if(this.pruneModifiedRecords){this.modified.remove(record);}
this.bufferRange[0]=Math.max(-1,this.bufferRange[0]-1);this.bufferRange[1]=Math.max(-1,this.bufferRange[1]-1);if(suspendEvent!==true){this.fireEvent("remove",this,record,index);}
return index;}
this.bufferRange[1]=Math.max(-1,this.bufferRange[1]-1);this.data.removeAt(index);if(this.pruneModifiedRecords){this.modified.remove(record);}
this.totalLength-=1;if(suspendEvent!==true){this.fireEvent("remove",this,record,index);}
return index;},_getIndex:function(record)
{var index=this.indexOfId(record.id);if(index<0){index=this.findInsertIndex(record);}
return index;},bulkRemove:function(records)
{var rec=null;var recs=[];var ind=0;var len=records.length;var orgIndexes=[];for(var i=0;i<len;i++){rec=records[i];orgIndexes[rec.id]=this._getIndex(rec);}
for(var i=0;i<len;i++){rec=records[i];this.remove(rec,true);recs.push([rec,orgIndexes[rec.id]]);}
this.fireEvent("bulkremove",this,recs);},removeAll:function()
{this.totalLength=0;this.bufferRange=[-1,-1];this.data.clear();if(this.pruneModifiedRecords){this.modified=[];}
this.fireEvent("clear",this);},loadRanges:function(ranges)
{var max_i=ranges.length;if(max_i>0&&!this.selectionsProxy.activeRequest&&this.fireEvent("beforeselectionsload",this,ranges)!==false){var lParams=this.lastOptions.params;var params={};params.ranges=Ext.encode(ranges);if(lParams){if(lParams.sort){params.sort=lParams.sort;}
if(lParams.dir){params.dir=lParams.dir;}}
var options={};for(var i in this.lastOptions){options.i=this.lastOptions.i;}
options.ranges=params.ranges;this.selectionsProxy.load(params,this.reader,this.selectionsLoaded,this,options);}},loadSelections:function(ranges)
{if(ranges.length==0){return;}
this.loadRanges(ranges);},selectionsLoaded:function(o,options,success)
{if(this.checkVersionChange(o,options,success)!==false){var r=o.records;for(var i=0,len=r.length;i<len;i++){r[i].join(this);}
this.fireEvent("selectionsload",this,o.records,Ext.decode(options.ranges));}else{this.fireEvent("selectionsload",this,[],Ext.decode(options.ranges));}},checkVersionChange:function(o,options,success)
{if(o&&success!==false){if(o.version!==undefined){var old=this.version;this.version=o.version;if(this.version!==old){return this.fireEvent('versionchange',this,old,this.version);}}}},findInsertIndex:function(record)
{this.remoteSort=false;var index=Ext.ux.grid.livegrid.Store.superclass.findInsertIndex.call(this,record);this.remoteSort=true;if(this.bufferRange[0]<=0&&index==0){return index;}else if(this.bufferRange[0]>0&&index==0){return Number.MIN_VALUE;}else if(index>=this.bufferSize){return Number.MAX_VALUE;}
return index;},sortData:function(f,direction)
{direction=direction||'ASC';var st=this.fields.get(f).sortType;var fn=function(r1,r2){var v1=st(r1.data[f]),v2=st(r2.data[f]);return v1>v2?1:(v1<v2?-1:0);};this.data.sort(direction,fn);},onMetaChange:function(meta,rtype,o)
{this.version=null;Ext.ux.grid.livegrid.Store.superclass.onMetaChange.call(this,meta,rtype,o);},loadRecords:function(o,options,success)
{this.checkVersionChange(o,options,success);if(!o){this.bufferRange=[-1,-1];}else{this.bufferRange=[options.params.start,Math.max(0,Math.min((options.params.start+options.params.limit)-1,o.totalRecords-1))];}
Ext.ux.grid.livegrid.Store.superclass.loadRecords.call(this,o,options,success);},getAt:function(index)
{if(this.bufferRange[0]==-1){return undefined;}
var modelIndex=index-this.bufferRange[0];return this.data.itemAt(modelIndex);},clearFilter:function(){},isFiltered:function(){},collect:function(){},createFilterFn:function(){},sum:function(){},filter:function(){},filterBy:function(){},query:function(){},queryBy:function(){},find:function(){},findBy:function(){}});

Ext.namespace('Ext.ux.grid.livegrid');Ext.ux.grid.livegrid.Toolbar=Ext.extend(Ext.Toolbar,{displayMsg:'Displaying {0} - {1} of {2}',emptyMsg:'No data to display',refreshText:"Refresh",initComponent:function()
{Ext.ux.grid.livegrid.Toolbar.superclass.initComponent.call(this);if(this.grid){this.view=this.grid.getView();}
var me=this;this.view.init=this.view.init.createSequence(function(){me.bind(this);},this.view);},updateInfo:function(rowIndex,visibleRows,totalCount)
{if(this.displayEl){var msg=totalCount==0?this.emptyMsg:String.format(this.displayMsg,rowIndex+1,rowIndex+visibleRows,totalCount);this.displayEl.update(msg);}},unbind:function(view)
{var st;var vw;if(view instanceof Ext.grid.GridView){vw=view;}else{vw=view.getView();}
st=view.ds;st.un('loadexception',this.enableLoading,this);st.un('beforeload',this.disableLoading,this);st.un('load',this.enableLoading,this);vw.un('rowremoved',this.onRowRemoved,this);vw.un('rowsinserted',this.onRowsInserted,this);vw.un('beforebuffer',this.beforeBuffer,this);vw.un('cursormove',this.onCursorMove,this);vw.un('buffer',this.onBuffer,this);vw.un('bufferfailure',this.enableLoading,this);this.view=undefined;},bind:function(view)
{this.view=view;var st=view.ds;st.on('loadexception',this.enableLoading,this);st.on('beforeload',this.disableLoading,this);st.on('load',this.enableLoading,this);view.on('rowremoved',this.onRowRemoved,this);view.on('rowsinserted',this.onRowsInserted,this);view.on('beforebuffer',this.beforeBuffer,this);view.on('cursormove',this.onCursorMove,this);view.on('buffer',this.onBuffer,this);view.on('bufferfailure',this.enableLoading,this);},enableLoading:function()
{this.loading.setDisabled(false);},disableLoading:function()
{this.loading.setDisabled(true);},onCursorMove:function(view,rowIndex,visibleRows,totalCount)
{this.updateInfo(rowIndex,visibleRows,totalCount);},onRowsInserted:function(view,start,end)
{this.updateInfo(view.rowIndex,Math.min(view.ds.totalLength,view.visibleRows-view.rowClipped),view.ds.totalLength);},onRowRemoved:function(view,index,record)
{this.updateInfo(view.rowIndex,Math.min(view.ds.totalLength,view.visibleRows-view.rowClipped),view.ds.totalLength);},beforeBuffer:function(view,store,rowIndex,visibleRows,totalCount,options)
{this.loading.disable();this.updateInfo(rowIndex,visibleRows,totalCount);},onBuffer:function(view,store,rowIndex,visibleRows,totalCount)
{this.loading.enable();this.updateInfo(rowIndex,visibleRows,totalCount);},onClick:function(type)
{switch(type){case'refresh':if(this.view.reset(true)){this.loading.disable();}else{this.loading.enable();}
break;}},onRender:function(ct,position)
{Ext.PagingToolbar.superclass.onRender.call(this,ct,position);this.loading=this.addButton({tooltip:this.refreshText,iconCls:"x-tbar-loading",handler:this.onClick.createDelegate(this,["refresh"])});this.addSeparator();if(this.displayInfo){this.displayEl=Ext.fly(this.el.dom).createChild({cls:'x-paging-info'});}}});

Ext.ns('MDB');MDB.Settings={Panel:Ext.extend(Ext.form.FormPanel,{layout:'form',bodyStyle:'padding:10px 10px 0',labelWidth:100,initComponent:function(){this.items=[{xtype:'combo',fieldLabel:'Profile Playlist',name:'playlist',store:new Ext.data.SimpleStore({id:'settings_combo_store',fields:['display','id'],sortInfo:{field:"display",direction:"ASC"},data:[['Loading...','']]}),displayField:'display',valueField:'id',readOnly:true,forceSelection:true,mode:'local',triggerAction:'all',selectOnFocus:true,id:'settingsProfilePlaylistCombo'},{xtype:'checkbox',fieldLabel:'AutoStart',id:'settings_profile_autostart'}];this.buttons=[{text:"Save",handler:function(button,event){ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/savesettings",postdata:{PlaylistID:Ext.getCmp('settingsProfilePlaylistCombo').getValue(),AutoStart:Ext.getCmp('settings_profile_autostart').getValue()},callback:function(){}});}}];this.on('render',function(panel){ZP.Data.Remote.get({url:"http://www.mediadb.com/json/myspace/loadsettings",callback:function(response,url,errored){var items=response.data.ps;var records=Array();for(var i in items){var item=items[i];if(item.d){records.push(new MDB.PlaylistsRecord({display:item.d,id:item.i}));}}
Ext.StoreMgr.lookup('settings_combo_store').removeAll();Ext.StoreMgr.lookup('settings_combo_store').add(records);Ext.getCmp('settingsProfilePlaylistCombo').setValue(response.data.pp);Ext.getCmp('settings_profile_autostart').setValue(response.data.as);}});});MDB.Settings.Panel.superclass.initComponent.call(this);}})}

Ext.ns('MDB')
MDB.Music={RelatedTab:Ext.extend(Ext.grid.GridPanel,{title:'Related Artists',id:'musicrelatedartists_grid',header:false,border:false,hidden:true,region:'center',loadMask:true,hideHeaders:true,autoExpandMax:4000,autoExpandColumn:'name',initComponent:function(){this.store=new Ext.data.Store({id:"musicrelatedartists_store",proxy:new Ext.data.ScriptTagProxy({url:'http://www.mediadb.com/json/music/relatedmusicartist/',nocache:false}),reader:new Ext.ux.grid.livegrid.JsonReader({root:'i',totalProperty:'t'},[{name:'name',mapping:'n'},{name:'id',mapping:'i'},{name:'thumburl',mapping:'tu'},{name:'thumbwidth',mapping:'tw'},{name:'thumbheight',mapping:'th'}])});this.columns=[{id:'name',dataIndex:"name",renderer:function(v,p,r){return'<center><b>'+r.data.name+'</b><br><img src=\''+r.data.thumburl+'\' width='+r.data.thumbwidth+' height='+r.data.thumbheight+' /></center>';}}];this.on('rowclick',function(grid,rowIdx,e){Ext.getCmp('sideTabPanel').setActiveTab(0);Ext.getCmp('musicrelatedartists_grid').getSelectionModel().selectRow(rowIdx);var r=Ext.getCmp('musicrelatedartists_grid').getSelectionModel().getSelected();if(Ext.StoreMgr.lookup('songs_store').lastOptions){if(r.data.id!=Ext.StoreMgr.lookup('songs_store').lastOptions.params.ID){Ext.StoreMgr.lookup('songs_store').load({params:{ID:r.data.id}});}}else{Ext.StoreMgr.lookup('songs_store').load({params:{ID:r.data.id}});}});MDB.Music.RelatedTab.superclass.initComponent.call(this);}}),Tab:Ext.extend(Ext.Panel,{onContextMenu:function(g,rowIdx,e){if(!Ext.getCmp('songs_grid').getSelectionModel().hasSelection()||!Ext.getCmp('songs_grid').getSelectionModel().isSelected()){Ext.getCmp('songs_grid').getSelectionModel().selectRow(rowIdx);}
if(!this.contextMenu){this.contextMenu=new Ext.menu.Menu({id:'songsgridCtxMenu',items:[{text:'Add to Playlist',handler:function(){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Playlist.add(r)});}},{text:'Add to Favorites',handler:function(){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Favorites.add(r);});}},{text:'Play Now',handler:function(){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Playlist.add(r)});var total=Ext.getCmp('playlist_grid').getSelectionModel().getCount();Ext.getCmp('playlist_grid').getSelectionModel().selectRow(total);Ext.getCmp('player').playVideo(Ext.getCmp('playlist_grid').getSelectionModel().getSelected());}}]});}
var xy=e.getXY();this.contextMenu.showAt(xy);},initComponent:function(){var artistsView=new Ext.ux.grid.livegrid.GridView({nearLimit:50,loadMask:{msg:'Loading...'},autoFill:true,forceFit:true});this.title="Music";this.border=false;this.layout="border";this.items=[new Ext.ux.grid.livegrid.GridPanel({region:"center",id:'artists_grid',loadMask:true,view:artistsView,hideHeaders:true,autoExpandMax:4000,autoExpandColumn:'name',border:false,store:new Ext.ux.grid.livegrid.Store({id:'artists_store',autoLoad:true,bufferSize:300,proxy:new Ext.data.ScriptTagProxy({url:'http://www.mediadb.com/json/music/videoartist2/',nocache:false}),reader:new Ext.ux.grid.livegrid.JsonReader({root:'i',totalProperty:'t'},[{name:'name',mapping:'n'},{name:'id',mapping:'i'}])}),tbar:['Search: ',' ',new Ext.app.SearchField({store:Ext.StoreMgr.lookup('artists_store'),width:170})],bbar:new Ext.ux.grid.livegrid.Toolbar({view:artistsView,displayInfo:true,displayMsg:'Displaying {0} - {1} of {2}',emptyMsg:'No Results Returned',refreshText:'Loading'}),sm:new Ext.ux.grid.livegrid.RowSelectionModel(),columns:[{header:'<b>Artist/Band</b>',hidden:false,id:'name',dataIndex:"name",sortable:false,menuDisabled:true,resizable:false}],listeners:{rowclick:function(grid,rowIdx,e){Ext.getCmp('artists_grid').getSelectionModel().selectRow(rowIdx);var r=Ext.getCmp('artists_grid').getSelectionModel().getSelected();if(Ext.StoreMgr.lookup('songs_store').lastOptions){if(r.data.id!=Ext.StoreMgr.lookup('songs_store').lastOptions.params.ID){Ext.StoreMgr.lookup('songs_store').load({params:{ID:r.data.id}});}}else{Ext.StoreMgr.lookup('songs_store').load({params:{ID:r.data.id}});}}}}),{xtype:'grid',id:'songs_grid',region:"south",height:200,hideHeaders:true,title:'Songs',loadMask:true,enableDragDrop:true,autoExpandMax:4000,autoExpandColumn:'name',border:false,store:new Ext.data.Store({id:"songs_store",proxy:new Ext.data.ScriptTagProxy({url:'http://www.mediadb.com/json/music/video3/',nocache:false}),reader:new Ext.data.JsonReader({root:'i',totalProperty:'t'},[{name:'id',mapping:'i'},{name:'artist_id',mapping:'ai'},{name:'artist',mapping:'an'},{name:'name',mapping:'n'},{name:'url',mapping:'ui'},{name:'duration',mapping:'d'},{name:'link',mapping:'l'},{name:'type',mapping:'t'},{name:'display',mapping:'di'}])}),columns:[{id:'logo',dataIndex:'type',width:30,renderer:function(v,p,r){if(v=='MTV'){return'<center><img src="http://www.mediadb.com/images/logo/mtv-24x16.png" /></center>';}else if(v=='YAHOO'){return'<center><img src="http://www.mediadb.com/images/logo/yahoo_small.gif" /></center>';}}},{hidden:false,id:'name',sortable:true,dataIndex:"name",header:"Song"}],bbar:[{xtype:"toolbar",items:[{text:"Add To Playlist",xtype:"tbbutton",handler:function(button,event){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Playlist.add(r)});}},{text:"Add To Favorites",xtype:"tbbutton",handler:function(button,event){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Favorites.add(r);});}}]}],listeners:{rowcontextmenu:this.onContextMenu,rowdblclick:function(grid,rowIdx,r){Ext.getCmp('songs_grid').getSelectionModel().each(function(r){MDB.Playlist.add(r);});}}}];MDB.Music.Tab.superclass.initComponent.call(this);}})};

Ext.ns('MDB');MDB.Favorites={add:function(r){Ext.StoreMgr.lookup('favorite_store').add(r);ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/addfavorite",callback:function(){},postdata:{artist:r.data.artist,artist_id:r.data.artist_id,song:r.data.name,url:r.data.url,id:r.data.id,type:r.data.type,display:r.data.display,duration:r.data.duration,link:r.data.link}});},remove:function(r){ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/removefavorite",postdata:r.data});Ext.StoreMgr.lookup('favorite_store').remove(r);},get:function(){ZP.Data.Remote.get({url:"http://www.mediadb.com/json/myspace/favoriteslist",callback:MDB.Favorites.got});},got:function(response,url,error){if(!error){var items=response.data;var records=Array();var count=1;for(var i in items){var item=items[i];if(item.di){records.push(new MDB.Favorites.Record({favorite_id:item.fi,artist:item.an,artist_id:item.ai,song:item.s,url:item.u,type:item.t,id:item.i,display:item.di,duration:item.du,link:item.l}));}}
Ext.StoreMgr.lookup('favorite_store').add(records);}},Panel:Ext.extend(Ext.grid.GridPanel,{initComponent:function(){var grid=this;this.title='Favorites';this.store=new Ext.data.SimpleStore({id:'favorite_store',fields:[{name:'favorite_id',type:'string'},{name:'artist',type:'string'},{name:'artist_id',type:'string'},{name:'song',type:'string'},{name:'url',type:'string'},{name:'type',type:'string'},{name:'id',type:'string'},{name:'display',type:'string'},{name:'duration',type:'string'},{name:'link',type:'string'}]});this.columns=[{id:'logo',dataIndex:'type',width:30,renderer:function(v,p,r){if(v=='MTV'){return'<center><img src="http://www.mediadb.com/images/logo/mtv-24x16.png" /></center>';}else if(v=='YAHOO'){return'<center><img src="http://www.mediadb.com/images/logo/yahoo_small.gif" /></center>';}else if(v=='YOUTUBE'){return'<center><img src="http://www.mediadb.com/images/logo/youtube.png" /></center>';}}},{id:'display',dataIndex:"display"}];this.hideHeaders=true;this.autoExpandMax=4000;this.autoExpandColumn='display';this.border=false;var win;this.bbar=[{text:"Play",xtype:"tbbutton",handler:function(button,event){if(grid.getSelectionModel().getCount()>0){}else{grid.getSelectionModel().selectRow(total);}
grid.getSelectionModel().each(function(r){MDB.Playlist.add(r);});var total=Ext.getCmp('playlist_grid').getSelectionModel().getCount();Ext.getCmp('playlist_grid').getSelectionModel().selectRow(total);Ext.getCmp('player').playVideo(Ext.getCmp('playlist_grid').getSelectionModel().getSelected());}},' ',{xtype:'tbseparator'},' ',{text:'Add to Playlist',xtype:'tbbutton',handler:function(button,event){grid.getSelectionModel().each(function(r){MDB.Playlist.add(r);});}},' ',{xtype:'tbseparator'},' ',{text:"Remove",xtype:"tbbutton",handler:function(button,event){grid.getSelectionModel().each(function(r){MDB.Favorites.remove(r);});grid.getView().refresh();}}];this.on('rowdblclick',function(grid,rowIdx,r){grid.getSelectionModel().each(function(r){MDB.Playlist.add(r);});});MDB.Favorites.Panel.superclass.initComponent.call(this);}}),Record:Ext.data.Record.create([{name:'favorite_id',type:'string'},{name:'artist',type:'string'},{name:'artist_id',type:'string'},{name:'song',type:'string'},{name:'url',type:'string'},{name:'type',type:'string'},{name:'id',type:'string'},{name:'display',type:'string'},{name:'duration',type:'string'},{name:'link',type:'string'}])};

Ext.ns('MDB','MDB.YouTube');MDB.YouTube={Tab:Ext.extend(Ext.Panel,{initComponent:function(){this.title="You Tube";this.layout="border";this.border=false;this.tbar=[{xtype:"combo",store:new Ext.data.SimpleStore({fields:['display','feedtype','feedid'],sortInfo:{field:"display",direction:"ASC"},data:[['All','all','videos'],['Top Rated','standardfeeds','top_rated'],['Top Favorites','standardfeeds','top_favorites'],['Most Viewed','standardfeeds','most_viewed'],['Most Popular','standardfeeds','most_popular'],['Most Recent','standardfeeds','most_recent'],['Most Discussed','standardfeeds','most_discussed'],['Most Linked','standardfeeds','most_linked'],['Most Responded','standardfeeds','most_responded'],['Recently Featured','standardfeeds','recently_featured'],['Videos for Mobile Phones','standardfeeds','watch_on_mobile'],['Film & Animation','videos/-','Film'],['Autos & Vehicles','videos/-','Autos'],['Music','videos/-','Music'],['Pets & Animals','videos/-','Animals'],['Sports','videos/-','Sports'],['Travel & Events','videos/-','Travel'],['Short Movies','videos/-','Shortmov'],['Videoblogging','videos/-','Videoblog'],['Gaming','videos/-','Games'],['Comedy','videos/-','Comedy'],['People & Blogs','videos/-','People'],['News & Politics','videos/-','News'],['Entertainment','videos/-','Entertainment'],['Education','videos/-','Education'],['Howto & Style','videos/-','Howto'],['Nonprofits & Activism','videos/-','Nonprofit'],['Science & Technology','videos/-','Tech'],['Movies - Anime/Animation','videos/-','Movies_Anime_animation'],['Movies','videos/-','Movies'],['Movies - Comedy','videos/-','Movies_Comedy'],['Movies - Documentary','videos/-','Movies_Documentary'],['Movies - Action/Adventure','videos/-','Movies_Action_adventure'],['Movies - Classics','videos/-','Movies_Classics'],['Movies - Foreign','videos/-','Movies_Foreign'],['Movies - Horror','videos/-','Movies_Horror'],['Movies - Drama','videos/-','Movies_Drama'],['Movies - Family','videos/-','Movies_Family'],['Movies - Shorts','videos/-','Movies_Shorts'],['Movies - Sci-Fi/Fantasy','videos/-','Movies_Sci_fi_fantasy'],['Movies - Thriller','videos/-','Movies_Thriller']]}),displayField:'display',id:'youtube_combo',valueField:'feedid',value:'videos',readOnly:true,tpl:youtubeComboTpl,forceSelection:true,mode:'local',triggerAction:'all',emptyText:'Select Category or Feed',width:213,selectOnFocus:true,listeners:{select:function(combo,r,i){if(r.data.feedtype!='all'){Ext.StoreMgr.lookup('youtube_store').proxy.url='http://gdata.youtube.com/feeds/api/'+r.data.feedtype+'/'+r.data.feedid;}else{Ext.StoreMgr.lookup('youtube_store').proxy.url='http://gdata.youtube.com/feeds/api/'+r.data.feedid;}
Ext.StoreMgr.lookup('youtube_store').load({params:{'start-index':1,'max-results':50}});}}}];this.bbar=[{xtype:"toolbar",items:[{text:"Add To Playlist",xtype:"tbbutton",handler:function(button,event){Ext.getCmp('youtube_grid').getSelectionModel().each(function(r){Ext.StoreMgr.lookup('playlist_store').add(new MDB.Playlist.Record({artist:r.data.artist_name,artist_id:r.data.artist_id,song:r.data.name,url:r.data.url,id:r.data.id,type:'YOUTUBE',display:r.data.name,duration:r.data.duration,link:r.data.link}));});}},{text:"Add To Favorites",xtype:"tbbutton",handler:function(button,event){Ext.getCmp('youtube_grid').getSelectionModel().each(function(r){Ext.StoreMgr.lookup('favorite_store').add(new MDB.Favorites.Record({artist:r.data.artist_name,artist_id:r.data.artist_id,song:r.data.name,url:r.data.url,id:r.data.id,type:'YOUTUBE',display:r.data.name,duration:r.data.duration,link:r.data.link}));var param={};param[gadgets.io.RequestParameters.AUTHORIZATION]=gadgets.io.AuthorizationType.SIGNED;param[gadgets.io.RequestParameters.CONTENT_TYPE]=gadgets.io.ContentType.JSON;param[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.POST;param[gadgets.io.RequestParameters.POST_DATA]={artist:r.data.artist_name,artist_id:r.data.artist_id,song:r.data.name,url:r.data.url,id:r.data.id,type:'YOUTUBE',display:r.data.name,duration:r.data.duration,link:r.data.link};gadgets.io.makeRequest("http://www.mediadb.com/json/myspace/addfavorite",function(){},param);});}}]}];this.items=[{xtype:'grid',id:'youtube_grid',region:"center",layout:'fit',loadMask:true,hideHeaders:true,header:false,autoExpandMax:4000,autoExpandColumn:'name',border:false,store:new Ext.data.Store({id:'youtube_store',proxy:new Ext.data.ScriptTagProxy({url:'http://gdata.youtube.com/feeds/api/videos',nocache:false}),reader:new Ext.data.JsonReader({root:'feed.entry',totalProperty:'feed.openSearch$totalResults.$t'},[{name:'name',mapping:'media$group.media$title.$t'},{name:'id',mapping:'media$group.yt$videoid.$t'},{name:'thumburl',mapping:'media$group.media$thumbnail[0].url'},{name:'thumbheight',mapping:'media$group.media$thumbnail[0].height'},{name:'thumbwidth',mapping:'media$group.media$thumbnail[0].width'},{name:'duration',mapping:'media$group.yt$duration.seconds'},{name:'description',mapping:'media$group.media$description.$t',convert:function(v,r){return v.replace(/\n/gi,'<br/>');}}]),baseParams:{v:2,alt:'json-in-script',format:5,orderby:'relevance','max-results':50}}),tbar:['Search: ',' ',new Ext.app.SearchField({store:Ext.StoreMgr.lookup('youtube_store'),paramName:'q',width:170})],bbar:new Ext.PagingToolbar({store:Ext.StoreMgr.lookup('youtube_store'),pageSize:50,startOffset:1,paramNames:{start:'start-index',limit:'max-results'}}),listeners:{rowdblclick:function(grid,rowIdx,r){Ext.getCmp('youtube_grid').getSelectionModel().each(function(r){Ext.StoreMgr.lookup('playlist_store').add(new MDB.Playlist.Record({artist:r.data.name,song:'',url:r.data.url,type:'YOUTUBE',id:r.data.id,display:r.data.name,duration:r.data.duration}));});},render:function(grid){Ext.StoreMgr.lookup('youtube_store').proxy.url='http://gdata.youtube.com/feeds/api/videos';Ext.StoreMgr.lookup('youtube_store').load({params:{'start-index':1,'max-results':50}});}},cm:new Ext.grid.ColumnModel([{id:'name',dataIndex:"name"}])}];MDB.YouTube.Tab.superclass.initComponent.call(this);}}),RelatedTab:Ext.extend(Ext.grid.GridPanel,{title:'Related Videos',header:false,border:false,hidden:true,xtype:'grid',region:'west',width:170,id:'youtuberelatedvideos_grid',loadMask:true,hideHeaders:true,autoExpandMax:4000,autoExpandColumn:'name',initComponent:function(){this.store=new Ext.data.Store({id:'youtuberelatedvideos_store',proxy:new Ext.data.ScriptTagProxy({url:'http://www.mediadb.com/json/movie/video/',nocache:false}),reader:new Ext.data.JsonReader({root:'feed.entry',totalProperty:'feed.openSearch$totalResults.$t'},[{name:'name',mapping:'media$group.media$title.$t'},{name:'id',mapping:'media$group.yt$videoid.$t'},{name:'thumburl',mapping:'media$group.media$thumbnail[0].url'},{name:'thumbheight',mapping:'media$group.media$thumbnail[0].height'},{name:'thumbwidth',mapping:'media$group.media$thumbnail[0].width'},{name:'duration',mapping:'media$group.yt$duration.seconds'},{name:'description',mapping:'media$group.media$description.$t',convert:function(v,r){return v.replace(/\n/gi,'<br/>');}}]),baseParams:{v:2,alt:'json-in-script','max-results':50,format:5},listeners:{load:function(store){store.sort('name','ASC');}}});this.columns=[{id:'name',dataIndex:"name",renderer:function(v,p,r){return'<center><div style="white-space:normal;"><b>'+r.data.name+'</b></div><img src=\''+r.data.thumburl+'\' width='+r.data.thumbwidth+' height='+r.data.thumbheight+' /></center>';}}];this.on('rowdblclick',function(grid,rowIdx,e){Ext.getCmp('youtuberelatedvideos_grid').getSelectionModel().each(function(r){Ext.StoreMgr.lookup('playlist_store').add(new MDB.Playlist.Record({artist:r.data.name,song:'',url:r.data.url,type:'YOUTUBE',id:r.data.id,display:r.data.name,duration:r.data.duration}));})});MDB.YouTube.RelatedTab.superclass.initComponent.call(this);}})};

Ext.ns('MDB');MDB.Player=Ext.extend(Ext.Panel,{mtvplayer:false,youtubeplayer:false,yahooplayer:false,playing:null,currentPlayer:null,repeat:false,ismuted:false,stoped:false,totalTime:null,updateTask:false,yplaystate:null,yadstreamid:null,videoMask:null,maximized:false,relatedshown:false,poweredbymtv:new Ext.Toolbar.TextItem({text:' ',xtype:'tbtext'}),task:null,elRuntime:null,playButton:new Ext.Toolbar.Button({iconCls:'play-button',handler:function(button,state){Ext.getCmp('player').play();}}),prevButton:new Ext.Toolbar.Button({iconCls:'prev-button',handler:function(button,state){Ext.getCmp('player').previous();}}),nextButton:new Ext.Toolbar.Button({iconCls:'next-button',handler:function(button,state){Ext.getCmp('player').next();}}),stopButton:new Ext.Toolbar.Button({iconCls:'stop-button',handler:function(button,state){Ext.getCmp('player').stop();}}),pauseButton:new Ext.Toolbar.Button({iconCls:'pause-button',enableToggle:true,toggleHandler:function(button,state){if(state){Ext.getCmp('player').pause();}else{Ext.getCmp('player').unpause();}}}),repeatButton:new Ext.Toolbar.Button({iconCls:'repeat-button',enableToggle:true,toggleHandler:function(button,state){Ext.getCmp('player').repeat=state;}}),volupButton:new Ext.Toolbar.Button({iconCls:'vol-up-button',handler:function(button,state){Ext.getCmp('player').volup();}}),voldownButton:new Ext.Toolbar.Button({iconCls:'vol-down-button',handler:function(button,state){Ext.getCmp('player').voldown();}}),muteButton:new Ext.Toolbar.Button({iconCls:'mute-button',enableToggle:true,toggleHandler:function(button,state){Ext.getCmp('player').ismuted=state;Ext.getCmp('player').mute();}}),sliderField:null,isAdjusting:false,_initListeners:function(){this.on('resize',this._onResize,this);this.on('destroy',this._onDestroy,this);var c=this;this.sliderField.on('dragstart',function(){this.isAdjusting=true;},this);this.sliderField.on('drag',this._onSeekPosition,this);this.sliderField.on('dragend',function(){this.isAdjusting=false;},this);},initComponent:function(){this.border=false;var panel=this;this.title='Welcome To The Media Database';this.bufferResize=true;var html='';if(MDB.Canvas){this.tools=[{id:'restore',qtip:'Restore Video',handler:function(){if(Ext.getCmp('player').relatedshown){Ext.getCmp('relatedPanel').show();}
Ext.getCmp('bottomTabPanel').show();Ext.getCmp('sideTabPanel').show();Ext.getCmp('viewport').syncSize();Ext.getCmp('viewport').doLayout();Ext.getCmp('rightside').syncSize();Ext.getCmp('rightside').doLayout();Ext.getCmp('player').maximized=false;Ext.getCmp('player').syncSize();Ext.getCmp('player').doLayout();Ext.getCmp('player').sliderField.fireEvent('resize');}},{id:'maximize',qtip:'Maximize Video',handler:function(){if(Ext.getCmp('relatedPanel').isVisible()){Ext.getCmp('relatedPanel').hide();Ext.getCmp('player').relatedshown=true;}
Ext.getCmp('bottomTabPanel').hide();Ext.getCmp('sideTabPanel').hide();Ext.getCmp('viewport').syncSize();Ext.getCmp('viewport').doLayout();Ext.getCmp('rightside').syncSize();Ext.getCmp('rightside').doLayout();Ext.getCmp('player').maximized=true;Ext.getCmp('player').syncSize();Ext.getCmp('player').doLayout();Ext.getCmp('player').sliderField.fireEvent('resize');}}];html='<iframe id="homeframe" src="http://www.mediadb.com/frame/myspace/index" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';}
this.html=html+'<div id="mtvdiv" style="display:none;width:100%;height:100%;"><div id="mtvvideodiv"></div></div><div id="youtubediv" style="display:none;width:100%;height:100%;"><div id="youtubevideodiv"></div></div><div id="yahoodiv" style="display:none;width:100%;height:100%;"><div id="yahoovideodiv"></div></div>';this.listeners={render:function(){panel.videoMask=new Ext.LoadMask(Ext.getCmp('videoPanel').getEl(),{msg:"This Video Has Been Removed..."});}};this.sliderField=new MDB.Player.SliderField({minValue:0,maxValue:0,fieldLabel:'Slider',disabled:true,listeners:{render:function(){this.el.dom.parentNode.style.width='100%';}}});window.mtvnPlayerLoaded=this.mtvplayerloaded;var mtvnSetCoad=function(adObject){return};window.mtvnSetCoad=mtvnSetCoad;window.onYouTubePlayerReady=this.onyoutubeplayerready;window.y_up_eventHandler=this.y_up_eventHandler;this.sliderField.on('dragstart',function(){this.isAdjusting=true;},this);this.sliderField.on('drag',this._onSeekPosition,this);this.sliderField.on('dragend',function(){this.isAdjusting=false;},this);this.on('resize',function(p,adjWidth,adjHeight,rawWidth,rawHeight){this._onResize(adjWidth,adjHeight,rawWidth,rawHeight);if(Ext.get('mtvn_player')!=null){Ext.get('mtvn_player').setHeight(Ext.getCmp('player').getInnerHeight()+35);}},this);this.bbar=new Ext.Toolbar({height:30,listeners:{render:function(cmp){var player=Ext.getCmp('player');this.add(player.prevButton);this.add(player.playButton);this.add(player.pauseButton);this.add(player.stopButton);this.add(player.nextButton);this.add(new Ext.Toolbar.Separator());this.add(player.repeatButton);this.add(new Ext.Toolbar.Separator());this.add(new Ext.Toolbar.Spacer());this.add(player.sliderField);this.add(new Ext.Toolbar.Spacer());this.add(new Ext.Toolbar.Spacer());player.elRuntime=Ext.fly(this.el.dom.getElementsByTagName('tr')[0]).createChild({tag:'td',style:'color:#FFFFFF'});player.elRuntime.update('00:00');this.add(new Ext.Toolbar.Spacer());this.add(new Ext.Toolbar.Separator());this.add(new Ext.Toolbar.Spacer());this.add(player.voldownButton);this.add(player.volupButton);this.add(player.muteButton);this.add(new Ext.Toolbar.Spacer());this.add(player.poweredbymtv);}}});this._initListeners();MDB.Player.superclass.initComponent.call(this);},_onResize:function(adjWidth,adjHeight,rawWidth,rawHeight){this.sliderField.fireEvent('resize');},_onDestroy:function(){if(this.task){Ext.TaskMgr.stop(this.task);}},playVideo:function(r){var player=Ext.getCmp('player');player.stoped=true;player.mtvplayer=false;player.yahooplayer=false;try{swfobject.removeSWF('mtvvideodiv');}catch(err){}
try{Ext.DomHelper.overwrite('mtvdiv','<div id="mtvvideodiv"></div>');}catch(err){}
try{swfobject.removeSWF('yahoovideodiv');}catch(err){}
try{Ext.DomHelper.overwrite('yahoodiv','<div id="yahoovideodiv"></div>');}catch(err){}
player.stop();player.setTitle(r.data.display);player.playing=r.id;player.totalTime=r.data.duration;if(player.task){Ext.TaskMgr.stop(player.task);}
var params={allowFullScreen:"true",allowScriptAccess:"always",quality:"high",bgcolor:"#000000",wmode:"transparent",salign:"b",align:"b"};Ext.get('mtvdiv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});Ext.get('youtubediv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:false});Ext.get('yahoodiv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});if(Ext.get('homeframe')!=null){Ext.get('homeframe').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});}
if(r.data.type=='MTV'){if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();Ext.getCmp('youtuberelatedvideos_grid').hide();Ext.getCmp('musicrelatedartists_grid').show();Ext.getCmp('musicrelatedartists_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Artists');Ext.getCmp('musicrelatedartists_grid').store.load({params:{ID:r.data.artist_id,NAME:r.data.artist}});player.poweredbymtv.show();Ext.DomHelper.overwrite(player.poweredbymtv.getEl(),'<a href="'+r.data.link+'" target="_blank"><img src="http://www.mtv.com/shared/promoimages/powered_by_mtv/powered_by_mtv_icon_black_cyan.jpg" /></a>');}
player.currentPlayer='MTV';player.volupButton.show();player.voldownButton.show();player.muteButton.show();Ext.get('mtvdiv').fadeIn({endOpacity:1,duration:0.5,useDisplay:true});swfobject.embedSWF('http://media.mtvnservices.com/mgid:uma:video:mtvmusic.com:'+r.data.url,"mtvvideodiv","100%",Ext.getCmp('player').getInnerHeight()+35,"9.0.0",false,{autoPlay:"true"},params,{id:"mtvn_player",name:"mtvn_player"});}else if(r.data.type=='YOUTUBE'){if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();player.poweredbymtv.hide();Ext.getCmp('musicrelatedartists_grid').hide();Ext.getCmp('youtuberelatedvideos_grid').show();Ext.getCmp('youtuberelatedvideos_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Videos');var relatedurl='http://gdata.youtube.com/feeds/api/videos/'+r.data.id+'/related';if(relatedurl!=Ext.getCmp('youtuberelatedvideos_grid').store.proxy.url){Ext.getCmp('youtuberelatedvideos_grid').store.proxy.url=relatedurl;Ext.getCmp('youtuberelatedvideos_grid').store.load();}}
player.volupButton.show();player.voldownButton.show();player.muteButton.show();Ext.get('youtubediv').fadeIn({endOpacity:1,duration:0.5,useDisplay:false});if(player.youtubeplayer!=false&&player.youtubeplayer!=null){player.youtubeplayer.loadVideoById(r.data.id);}else{var atts={id:"myytplayer"};swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=myytplayer","youtubevideodiv","100%","100%","9.0.0",false,null,params,atts);setTimeout(function(){Ext.getCmp('player').playVideo(r);},2500);}
player.currentPlayer='YOUTUBE';}else if(r.data.type=='YAHOO'){player.poweredbymtv.hide();if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();Ext.getCmp('youtuberelatedvideos_grid').hide();Ext.getCmp('musicrelatedartists_grid').show();Ext.getCmp('musicrelatedartists_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Artists');Ext.getCmp('musicrelatedartists_grid').store.load({params:{ID:r.data.artist_id,NAME:r.data.artist}});}
player.volupButton.hide();player.voldownButton.hide();player.muteButton.hide();Ext.get('yahoodiv').fadeIn({endOpacity:1,duration:0.5,useDisplay:true});swfobject.embedSWF("http://d.yimg.com/cosmos.bcst.yahoo.com/up/fop/embedflv/swf/fop.swf","yahoovideodiv","100%","100%","9.0.0",false,{id:'v'+r.data.url,shareEnable:'0',enableFullScreen:'0',autoStart:'1',controlsEnable:'0',infoEnable:'0',postpanelEnable:'0',prepanelEnable:'0',nowplayingEnable:'0',eh:'y_up_eventHandler'},params,{id:"yplayer"});player.currentPlayer='YAHOO';}
Ext.getCmp('viewport').syncSize();Ext.getCmp('viewport').doLayout();player.doLayout();player.sliderField.fireEvent('resize');player.stoped=false;},loadVideo:function(r){var player=Ext.getCmp('player');player.stoped=true;player.mtvplayer=false;player.yahooplayer=false;try{swfobject.removeSWF('mtvvideodiv');}catch(err){}
try{Ext.DomHelper.overwrite('mtvdiv','<div id="mtvvideodiv"></div>');}catch(err){}
try{swfobject.removeSWF('yahoovideodiv');}catch(err){}
try{Ext.DomHelper.overwrite('yahoodiv','<div id="yahoovideodiv"></div>');}catch(err){}
player.stop();player.setTitle(r.data.display);player.playing=r.id;player.totalTime=r.data.duration;if(player.task){Ext.TaskMgr.stop(player.task);}
var params={allowFullScreen:"true",allowScriptAccess:"always",quality:"high",bgcolor:"#000000",wmode:"transparent",salign:"b",align:"b"};Ext.get('mtvdiv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});Ext.get('youtubediv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:false});Ext.get('yahoodiv').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});if(Ext.get('homeframe')!=null){Ext.get('homeframe').fadeOut({endOpacity:0,easing:'easeOut',duration:0.5,remove:false,useDisplay:true});}
if(r.data.type=='MTV'){if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();Ext.getCmp('youtuberelatedvideos_grid').hide();Ext.getCmp('musicrelatedartists_grid').show();Ext.getCmp('musicrelatedartists_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Artists');Ext.getCmp('musicrelatedartists_grid').store.load({params:{ID:r.data.artist_id,NAME:r.data.artist}});player.poweredbymtv.show();Ext.DomHelper.overwrite(player.poweredbymtv.getEl(),'<a href="'+r.data.link+'" target="_blank"><img src="http://www.mtv.com/shared/promoimages/powered_by_mtv/powered_by_mtv_icon_black_cyan.jpg" /></a>');}
player.currentPlayer='MTV';player.volupButton.show();player.voldownButton.show();player.muteButton.show();Ext.get('mtvdiv').fadeIn({endOpacity:1,duration:0.5,useDisplay:true});swfobject.embedSWF('http://media.mtvnservices.com/mgid:uma:video:mtvmusic.com:'+r.data.url,"mtvvideodiv","100%",Ext.getCmp('player').getInnerHeight()+35,"9.0.0",false,{autoPlay:"false"},params,{id:"mtvn_player",name:"mtvn_player"});}else if(r.data.type=='YOUTUBE'){if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();player.poweredbymtv.hide();Ext.getCmp('musicrelatedartists_grid').hide();Ext.getCmp('youtuberelatedvideos_grid').show();Ext.getCmp('youtuberelatedvideos_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Videos');var relatedurl='http://gdata.youtube.com/feeds/api/videos/'+r.data.id+'/related';if(relatedurl!=Ext.getCmp('youtuberelatedvideos_grid').store.proxy.url){Ext.getCmp('youtuberelatedvideos_grid').store.proxy.url=relatedurl;Ext.getCmp('youtuberelatedvideos_grid').store.load();}}
player.volupButton.show();player.voldownButton.show();player.muteButton.show();Ext.get('youtubediv').fadeIn({endOpacity:1,duration:0.5,useDisplay:false});if(player.youtubeplayer!=false&&player.youtubeplayer!=null){player.youtubeplayer.cueVideoById(r.data.id);}else{var atts={id:"myytplayer"};swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=myytplayer","youtubevideodiv","100%","100%","9.0.0",false,null,params,atts);setTimeout(function(){Ext.getCmp('player').loadVideo(r);},2500);}
player.currentPlayer='YOUTUBE';}else if(r.data.type=='YAHOO'){player.poweredbymtv.hide();if(Ext.getCmp('relatedPanel')&&!Ext.getCmp('player').maximized){Ext.getCmp('relatedPanel').show();Ext.getCmp('youtuberelatedvideos_grid').hide();Ext.getCmp('musicrelatedartists_grid').show();Ext.getCmp('musicrelatedartists_grid').doLayout();Ext.getCmp('relatedPanel').setTitle('Related Artists');Ext.getCmp('musicrelatedartists_grid').store.load({params:{ID:r.data.artist_id,NAME:r.data.artist}});}
player.volupButton.hide();player.voldownButton.hide();player.muteButton.hide();Ext.get('yahoodiv').fadeIn({endOpacity:1,duration:0.5,useDisplay:true});swfobject.embedSWF("http://d.yimg.com/cosmos.bcst.yahoo.com/up/fop/embedflv/swf/fop.swf","yahoovideodiv","100%","100%","9.0.0",false,{id:'v'+r.data.url,shareEnable:'0',enableFullScreen:'0',autoStart:'0',controlsEnable:'0',infoEnable:'0',postpanelEnable:'0',prepanelEnable:'0',nowplayingEnable:'0',eh:'y_up_eventHandler'},params,{id:"yplayer"});player.currentPlayer='YAHOO';}
Ext.getCmp('viewport').syncSize();Ext.getCmp('viewport').doLayout();player.doLayout();player.sliderField.fireEvent('resize');player.stoped=false;},mtvplayerloaded:function(playerId){Ext.getCmp('player').mtvplayer=document.getElementById(playerId);Ext.getCmp('player').mtvplayer.addEventListener('STATE_CHANGE',"Ext.getCmp('player').mtvonStateChange");Ext.getCmp('player').mtvplayer.addEventListener('PLAYHEAD_UPDATE',"Ext.getCmp('player').mtvonPlayheadUpdate");Ext.getCmp('player').mtvplayer.addEventListener('MEDIA_ENDED',"Ext.getCmp('player').mtvmediaEnded");Ext.getCmp('player').mtvplayer.addEventListener('READY',"Ext.getCmp('player').mtvonReady");},mtvmediaEnded:function(){},mtvonPlayheadUpdate:function(){if(Ext.getCmp('player').currentPlayer=='MTV')Ext.getCmp("player").updateVideoInfo();},mtvonReady:function(){},mtvonStateChange:function(state){switch(state){case("stopped"):if(Ext.getCmp('player').stoped!=true){Ext.getCmp('player').next();}
break;case("playing"):Ext.getCmp('player').mute();break}},onyoutubeplayerready:function(playerId){Ext.getCmp('player').youtubeplayer=document.getElementById("myytplayer");Ext.getCmp('player').youtubeplayer.addEventListener("onStateChange","Ext.getCmp('player').youtubeonStateChange");Ext.getCmp('player').youtubeplayer.addEventListener("onError","Ext.getCmp('player').youtubeonError");},youtubeonStateChange:function(state){switch(state){case(0):if(Ext.getCmp('player').task){Ext.TaskMgr.stop(Ext.getCmp('player').task);}
if(Ext.getCmp('player').stoped!=true){Ext.getCmp('player').next();}
break;case(1):Ext.getCmp('player').task={run:function(){Ext.getCmp('player').updateVideoInfo();},interval:500};Ext.TaskMgr.start(Ext.getCmp('player').task);Ext.getCmp('player').mute();break;}},youtubeonError:function(error,error2){if(Ext.getCmp('player').task){Ext.TaskMgr.stop(Ext.getCmp('player').task);}
Ext.getCmp('player').videoMask.show();Ext.getCmp('player').currentPlayer=null;setTimeout(function(){Ext.getCmp('player').videoMask.hide();Ext.getCmp('player').next();},5000);},y_up_eventHandler:function(pType,pItem){switch(pType){case"init":Ext.getCmp('player').yahooplayer=document.getElementById("yplayer");break;case"itemBegin":if(pItem.type=='S_AD'){Ext.getCmp('player').yadstreamid=pItem.clipsid;}
Ext.getCmp('player').task={run:function(){Ext.getCmp('player').updateVideoInfo();},interval:500};Ext.TaskMgr.start(Ext.getCmp('player').task);break;case"itemEnd":case"done":if(Ext.getCmp('player').stoped!=true&&Ext.getCmp('player').yadstreamid!=pItem.clipsid){Ext.getCmp('player').next();}
if(Ext.getCmp('player').task){Ext.TaskMgr.stop(Ext.getCmp('player').task);}
break;case"streamPlay":case"streamPause":case"streamStop":case"streamError":case"userClick":break;}},getCurrentTime:function(){if(Ext.getCmp('player').mtvplayer){return Ext.getCmp('player').mtvplayer.getPlayheadTime();}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){return Ext.getCmp('player').youtubeplayer.getCurrentTime();}else if(Ext.getCmp('player').yahooplayer){return Ext.getCmp('player').yahooplayer.getVidTime();}},getVideoBytesLoaded:function(){if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){return Ext.getCmp('player').youtubeplayer.getVideoBytesLoaded();}else{return-1;}},getVideoBytesTotal:function(){if(Ext.getCmp('player').mtvplayer){return-1;}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){return Ext.getCmp('player').youtubeplayer.getVideoBytesTotal();}},pause:function(){if(Ext.getCmp('player').mtvplayer){Ext.getCmp('player').mtvplayer.pause();}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){if(Ext.getCmp('player').youtubeplayer!=null)Ext.getCmp('player').youtubeplayer.pauseVideo();}else if(Ext.getCmp('player').yahooplayer){Ext.getCmp('player').yahooplayer.vidPause();}},unpause:function(){if(Ext.getCmp('player').mtvplayer){Ext.getCmp('player').mtvplayer.unpause();}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){Ext.getCmp('player').youtubeplayer.playVideo();}else if(Ext.getCmp('player').yahooplayer){Ext.getCmp('player').yahooplayer.vidPlay();}},play:function(){if(Ext.getCmp('player').mtvplayer){Ext.getCmp('player').mtvplayer.unpause();}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){Ext.getCmp('player').youtubeplayer.playVideo();}else if(Ext.getCmp('player').yahooplayer){Ext.getCmp('player').yahooplayer.vidPlay();}},previous:function(){var index=Ext.StoreMgr.lookup('playlist_store').indexOfId(Ext.getCmp('player').playing);var total=Ext.StoreMgr.lookup('playlist_store').getCount();index=index-1;if(index>=0){Ext.getCmp('player').playVideo(Ext.StoreMgr.lookup('playlist_store').getAt(index));Ext.getCmp('playlist_grid').getView().focusRow(index);Ext.getCmp('playlist_grid').getSelectionModel().selectRow(index);}else if(Ext.getCmp('player').repeat==true){Ext.getCmp('player').playVideo(Ext.StoreMgr.lookup('playlist_store').getAt(total-1));Ext.getCmp('playlist_grid').getView().focusRow(total-1);Ext.getCmp('playlist_grid').getSelectionModel().selectRow(total-1);}},next:function(){var index=Ext.StoreMgr.lookup('playlist_store').indexOfId(Ext.getCmp('player').playing);var total=Ext.StoreMgr.lookup('playlist_store').getCount();index=index+1;if(index<total){Ext.getCmp('player').playVideo(Ext.StoreMgr.lookup('playlist_store').getAt(index));Ext.getCmp('playlist_grid').getView().focusRow(index);Ext.getCmp('playlist_grid').getSelectionModel().selectRow(index);}else if(Ext.getCmp('player').repeat==true){Ext.getCmp('player').playVideo(Ext.StoreMgr.lookup('playlist_store').getAt(0));Ext.getCmp('playlist_grid').getView().focusRow(0);Ext.getCmp('playlist_grid').getSelectionModel().selectRow(0);}},stop:function(){Ext.getCmp('player').stoped=true;if(Ext.getCmp('player').mtvplayer){Ext.getCmp('player').mtvplayer.pause();Ext.getCmp('player').mtvplayer.setPlayheadTime(0);}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){Ext.getCmp('player').youtubeplayer.stopVideo();}else if(Ext.getCmp('player').yahooplayer){Ext.getCmp('player').yahooplayer.vidStop();}},seekTo:function(){if(Ext.getCmp('player').mtvplayer){Ext.getCmp('player').mtvplayer.setPlayheadTime(this.sliderField.getValue());}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){Ext.getCmp('player').youtubeplayer.seekTo(this.sliderField.getValue());}else if(Ext.getCmp('player').yahooplayer){Ext.getCmp('player').yahooplayer.vidSeek(this.sliderField.getValue());}},voldown:function(){if(Ext.getCmp('player').mtvplayer){if(Ext.getCmp('player').mtvplayer.getVolume()!=0)Ext.getCmp('player').mtvplayer.setVolume(Ext.getCmp('player').mtvplayer.getVolume()-0.1);}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){if(Ext.getCmp('player').youtubeplayer.getVolume()!=0)Ext.getCmp('player').youtubeplayer.setVolume(Ext.getCmp('player').youtubeplayer.getVolume()-10);}},volup:function(){if(Ext.getCmp('player').mtvplayer){if(Ext.getCmp('player').mtvplayer.getVolume()!=1)Ext.getCmp('player').mtvplayer.setVolume(Ext.getCmp('player').mtvplayer.getVolume()+0.1);}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){if(Ext.getCmp('player').youtubeplayer.getVolume()!=1)Ext.getCmp('player').youtubeplayer.setVolume(Ext.getCmp('player').youtubeplayer.getVolume()+10);}},mute:function(){if(Ext.getCmp('player').mtvplayer){if(Ext.getCmp('player').ismuted===false){Ext.getCmp('player').mtvplayer.unmute();}else{Ext.getCmp('player').mtvplayer.mute();}}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){if(Ext.getCmp('player').ismuted===false){Ext.getCmp('player').youtubeplayer.unMute();}else{Ext.getCmp('player').youtubeplayer.mute();}}},getPlayState:function(){if(Ext.getCmp('player').mtvplayer){return Ext.getCmp('player').mtvplayer.getPlayState();}else if(Ext.getCmp('player').currentPlayer=='YOUTUBE'&&Ext.getCmp('player').youtubeplayer!=null&&Ext.getCmp('player').youtubeplayer!=false){var state=Ext.getCmp('player').youtubeplayer.getPlayerState();switch(state){case-1:state='unstarted';break;case 0:state='ended';break;case 1:state='playing';break;case 2:state='paused';break;case 3:state='buffering';break;case 5:state='video_cued';break;default:state='unknown';break;}
return state;}else if(Ext.getCmp('player').yahooplayer){return Ext.getCmp('player').yahooplayer.getVidState();}else{return false;}},updateVideoInfo:function(){var totalTime=Ext.getCmp('player').totalTime;var loaded=Ext.getCmp('player').getVideoBytesLoaded();var crem=Math.floor(Ext.getCmp('player').getCurrentTime());var width=Ext.getCmp('player').sliderField.sbar.getWidth();if(loaded!=-1){var total=Ext.getCmp('player').getVideoBytesTotal();var percLoaded=Math.floor(((loaded/total)*100));var pixels=Math.floor((width/100)*percLoaded);Ext.getCmp('player').sliderField.updateSliderBg(pixels);}else{Ext.getCmp('player').sliderField.updateSliderBg(1);}
if(totalTime>0){Ext.getCmp('player').sliderField.fireEvent('resize');Ext.getCmp('player').sliderField.setDisabled(false);var cminutes=Math.floor(crem/60);var cseconds=(crem%60);var trem=Math.floor(totalTime);var tminutes=Math.floor(trem/60);var tseconds=(trem%60);this.elRuntime.update((cminutes<10?'0'+cminutes:cminutes)+':'+(cseconds<10?'0'+cseconds:cseconds)+' / '+(tminutes<10?'0'+tminutes:tminutes)+':'+(tseconds<10?'0'+tseconds:tseconds));Ext.getCmp('player').sliderField.maxValue=trem;if(!Ext.getCmp('player').isAdjusting){Ext.getCmp('player').sliderField.setValue(crem,true);}}else{Ext.getCmp('player').sliderField.setDisabled(true);Ext.getCmp('player').sliderField.setValue(0,true);var cminutes=Math.floor(crem/60);var cseconds=(crem%60);this.elRuntime.update((cminutes<10?'0'+cminutes:cminutes)+':'+(cseconds<10?'0'+cseconds:cseconds));}},_onSeekPosition:function(){this.seekTo(this.sliderField.getValue());}});

Ext.ns('MDB','MDB.Player');MDB.Player.SliderField=Ext.extend(Ext.form.Field,{defaultAutoCreate:{tag:'input',type:'hidden'},thumbX:0,thumbY:0,initComponent:function(){MDB.Player.SliderField.superclass.initComponent.call(this);this.minValue=this.minValue||0;this.maxValue=this.maxValue||1;this.addEvents('dragstart','drag','dragend');this.on('resize',this.onResize,this);},onResize:function(){this.adjustPixelMax();},adjustPixelMax:function(){if(!this.sbar){return;}
var bb=this.sbar.getBox();var tb=this.sthumb.getBox();if(this.vertical===true){this.pixelMax=bb.height-tb.height;}else{this.pixelMax=bb.width-tb.width;}},onRender:function(ct,position){MDB.Player.SliderField.superclass.onRender.call(this,ct,position);this.sbar=Ext.DomHelper.append(ct,{tag:'div',cls:'mdb-player-slider-'+(this.vertical===true?'v':'h')+'bar'},true);this.sthumb=Ext.DomHelper.append(ct,{tag:'img',src:Ext.BLANK_IMAGE_URL,cls:'mdb-player-slider-'+(this.vertical===true?'v':'')+'thumb'},true);this.sthumb.addClassOnOver('mdb-player-slider-'+(this.vertical===true?'v':'')+'thumb-over');this.setValue(this.getValue()||this.minValue);},afterRender:function(){MDB.Player.SliderField.superclass.afterRender.call(this);if(this.vertical===true){this.sbar.setHeight(parseInt(this.el.dom.style.height,10));}else{var w=parseInt(this.el.dom.style.width,10);if(!isNaN){this.sbar.setWidth(w);}}
this.thumbX=parseInt(this.sthumb.getStyle('left'));this.thumbY=parseInt(this.sthumb.getStyle('bottom'));this.dd=new Ext.dd.DD(this.sthumb.id,'slider-'+this.sthumb.id,{constrainX:!this.vertical,constrainY:this.vertical});this.dd.slider=this;this.dd.onDrag=this.onDrag;this.dd.startDrag=this.startDrag;this.dd.endDrag=this.endDrag;if(this.disabled){this.dd.lock();}},updateSliderBg:function(percentage){this.sbar.dom.style.backgroundPosition='-'+(1280-percentage)+'px 0';},setValue:function(value,moveThumb){MDB.Player.SliderField.superclass.setValue.call(this,value);if(moveThumb===true){if(!this.pixelMax){this.adjustPixelMax();}
var min=this.minValue;var max=this.maxValue;if(this.vertical===true){this.dd.getEl().style.bottom=(Math.floor((value*this.pixelMax)/(min+(max-min)))+this.thumbY)+'px';}else{this.dd.getEl().style.left=Math.floor((value*this.pixelMax)/(min+(max-min)))+'px';}}},resetPositions:function(){this.sthumb.dom.style.left='0px';this.sbar.dom.style.backgroundPosition='-1280px 0';},onDisable:function(){MDB.Player.SliderField.superclass.onDisable.call(this);this.sbar.addClass(this.disabledClass);this.sthumb.addClass(this.disabledClass);this.dd.lock();},onEnable:function(){MDB.Player.SliderField.superclass.onEnable.call(this);this.sbar.removeClass(this.disabledClass);this.sthumb.removeClass(this.disabledClass);this.dd.unlock();},startDrag:function(x,y){var slider=this.slider;var bb=slider.sbar.getBox();var tb=slider.sthumb.getBox();this.resetConstraints();if(!slider.pixelMax){slider.adjustPixelMax();}
if(this.slider.vertical===true){this.setXConstraint(0,0);this.setYConstraint(tb.y-bb.y+1,bb.y+bb.height-tb.y-tb.height-1);}else{this.setYConstraint(0,0);this.setXConstraint(tb.x-bb.x+1,bb.x+bb.width-tb.x-tb.width-1);}
this.slider.fireEvent('dragstart');},endDrag:function(e){this.slider.fireEvent('dragend');},onDrag:function(e){var min=this.slider.minValue;var max=this.slider.maxValue;if(this.slider.vertical===true){var pixelPos=Math.abs(parseInt(this.getEl().style.top,10))-this.slider.thumbY;this.slider.setValue(min+(max-min)*pixelPos/this.slider.pixelMax);}else{var pixelPos=parseInt(this.getEl().style.left,10);this.slider.setValue(min+(max-min)*pixelPos/this.slider.pixelMax);}
this.slider.fireEvent('drag');}});

Ext.ns('MDB');MDB.Playlist={add:function(r){Ext.StoreMgr.lookup('playlist_store').add(r);},Panel:Ext.extend(Ext.grid.GridPanel,{mask:null,ddGroup:'playlistDDGroup',enableDragDrop:true,initComponent:function(){var grid=this;this.store=new Ext.data.SimpleStore({id:'playlist_store',fields:[{name:'artist',type:'string'},{name:'artist_id',type:'string'},{name:'song',type:'string'},{name:'url',type:'string'},{name:'type',type:'string'},{name:'id',type:'string'},{name:'display',type:'string'},{name:'duration',type:'string'},{name:'link',type:'string'}]});this.columns=[new Ext.grid.RowNumberer(),{id:'display',dataIndex:"display"}];this.hideHeaders=true;this.autoExpandMax=4000;this.autoExpandColumn='display';this.border=false;var win;this.bbar=[{text:"Play",xtype:"tbbutton",handler:function(button,event){if(grid.getSelectionModel().getCount()>0){Ext.getCmp('player').playVideo(grid.getSelectionModel().getSelected());}else{Ext.getCmp('player').playVideo(grid.getStore().getAt(0));grid.getSelectionModel().selectRow(0);}}},{xtype:'tbseparator'},{text:"Remove",xtype:"tbbutton",handler:function(button,event){grid.getSelectionModel().each(function(r){grid.getStore().remove(r);});grid.getView().refresh();}},{xtype:'tbseparator'},{text:"Clear Playlist",xtype:"tbbutton",handler:function(button,event){grid.getStore().removeAll();}},{xtype:'tbseparator'},{text:"Save/Load/Delete Playlists",xtype:"tbbutton",handler:function(button,event){win=new Ext.Window({xtype:'form',layout:'form',id:'playlistSaveLoadWin',width:300,height:175,mask:null,autoShow:true,title:'Playlists',labelWidth:45,bodyStyle:'padding:15px',defaults:{width:200},items:[{xtype:'combo',fieldLabel:'Playlists',name:'playlist',store:new Ext.data.SimpleStore({id:'playlist_combo_store',fields:['display','id','profile'],sortInfo:{field:"display",direction:"ASC"},data:[['Loading...','']]}),displayField:'display',valueField:'id',value:'0',readOnly:true,forceSelection:true,mode:'local',triggerAction:'all',selectOnFocus:true,id:'playlistSaveLoadPlaylist',listeners:{select:function(combo,r,i){if(r.data.id!=0){Ext.getCmp('playlistSaveLoadName').setValue(r.data.display);Ext.getCmp('playlistSaveLoadProfile').setValue(r.data.profile);}else{Ext.getCmp('playlistSaveLoadName').setValue('');Ext.getCmp('playlistSaveLoadProfile').setValue(0);}},render:function(combo){ZP.Data.Remote.get({url:"http://www.mediadb.com/json/myspace/loadplaylists",callback:function(response,url,errored){Ext.getCmp('playlistSaveLoadWin').mask.hide();var items=response.data;Ext.StoreMgr.lookup('playlist_combo_store').removeAll();var records=Array();for(var i in items){var item=items[i];if(item.d){records.push(new MDB.PlaylistsRecord({display:item.d,id:item.i,profile:item.p}));}}
Ext.StoreMgr.lookup('playlist_combo_store').add(records);Ext.getCmp('playlistSaveLoadPlaylist').setValue(0);}});}}},{xtype:'textfield',fieldLabel:'Name',name:'name',id:'playlistSaveLoadName'},{xtype:'checkbox',fieldLabel:'Profile',name:'profile',id:'playlistSaveLoadProfile'}],buttonAlign:'center',buttons:[{text:'Save',handler:function(){Ext.getCmp('playlistSaveLoadWin').mask.show();var list=Array();var i=1;Ext.StoreMgr.lookup('playlist_store').each(function(r){list.push({ORDER:i,ARTIST:r.data.artist,ARTIST_ID:r.data.artist_id,SONG:r.data.song,URL:r.data.url,ID:r.data.id,TYPE:r.data.type,DISPLAY:r.data.display,DURATION:r.data.duration,LINK:r.data.link});i++;});ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/saveplaylist",postdata:{PlaylistName:Ext.getCmp('playlistSaveLoadName').getValue(),PlaylistID:Ext.getCmp('playlistSaveLoadPlaylist').getValue(),Profile:Ext.getCmp('playlistSaveLoadProfile').getValue(),Playlist:Ext.util.JSON.encode(list)},callback:function(){Ext.getCmp('playlistSaveLoadWin').close();}});}},{text:'Load',handler:function(){Ext.getCmp('playlistSaveLoadWin').mask.show();Ext.getCmp('playlist_grid').mask.show();ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/loadplaylist/",postdata:{PlaylistName:Ext.getCmp('playlistSaveLoadName').getValue(),PlaylistID:Ext.getCmp('playlistSaveLoadPlaylist').getValue()},callback:function(response,url,errored){if(!errored){var items=response.data;Ext.StoreMgr.lookup('playlist_store').removeAll();var records=Array();for(var i in items){var item=items[i];if(item.di){records.push(new MDB.Playlist.Record({artist:item.an,artist_id:item.ai,song:item.s,url:item.u,type:item.t,id:item.i,display:item.di,duration:item.du,link:item.l}));}}
Ext.StoreMgr.lookup('playlist_store').add(records);}
Ext.getCmp('playlist_grid').mask.hide();Ext.getCmp('playlistSaveLoadWin').close();}});}},{text:'Delete',handler:function(){Ext.getCmp('playlistSaveLoadWin').mask.show();ZP.Data.Remote.post({url:"http://www.mediadb.com/json/myspace/deleteplaylist",postdata:{PlaylistName:Ext.getCmp('playlistSaveLoadName').getValue(),PlaylistID:Ext.getCmp('playlistSaveLoadPlaylist').getValue()},callback:function(){Ext.getCmp('playlistSaveLoadWin').close();}});}}],listeners:{render:function(window){window.mask=new Ext.LoadMask(window.getEl(),{msg:"Please wait..."});window.mask.show();}}});win.show();}}];this.on('rowdblclick',function(grid,rowIdx,r){Ext.getCmp('player').playVideo(grid.getSelectionModel().getSelected());});this.on('render',function(g){g.mask=new Ext.LoadMask(g.getGridEl(),{msg:"Please wait..."});var ddrow=new Ext.ux.dd.GridReorderDropTarget(g,{copy:false,listeners:{beforerowmove:function(objThis,oldIndex,newIndex,records){},afterrowmove:function(objThis,oldIndex,newIndex,records){g.getView().refresh();},beforerowcopy:function(objThis,oldIndex,newIndex,records){},afterrowcopy:function(objThis,oldIndex,newIndex,records){}}});Ext.dd.ScrollManager.register(g.getView().getEditorParent());});this.on('beforedestroy',function(g){Ext.dd.ScrollManager.unregister(g.getView().getEditorParent());});MDB.Playlist.Panel.superclass.initComponent.call(this);}}),Record:Ext.data.Record.create([{name:'artist',type:'string'},{name:'artist_id',type:'string'},{name:'song',type:'string'},{name:'url',type:'string'},{name:'type',type:'string'},{name:'id',type:'string'},{name:'display',type:'string'},{name:'duration',type:'string'},{name:'link',type:'string'}])};MDB.PlaylistsRecord=function(){return Ext.data.Record.create([{name:'display',type:'string'},{name:'id',type:'int'}]);}();

Ext.ns('MDB');MDB.Canvas=true;var youtubeComboTpl=new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{display}</div></tpl>');Ext.onReady(function(){Ext.QuickTips.init();var viewport=new Ext.Viewport({layout:'border',id:'viewport',items:[{region:"west",width:215,xtype:"tabpanel",id:'sideTabPanel',activeItem:0,border:false,items:[new MDB.Music.Tab({id:'musicTab'}),new MDB.YouTube.Tab(),new MDB.Favorites.Panel({id:'favorite_grid'})]},{region:"center",layout:"border",id:'rightside',border:false,items:[{region:'center',layout:'border',items:[new MDB.Player({region:'center',border:false,bufferResize:true,id:"player"}),new Ext.Panel({region:'east',border:false,title:'&nbsp;',id:'relatedPanel',hidden:true,layout:'border',width:170,items:[new MDB.Music.RelatedTab(),new MDB.YouTube.RelatedTab()]})]},{activeItem:0,xtype:"tabpanel",region:'south',height:160,id:'bottomTabPanel',border:false,items:[new MDB.Playlist.Panel({id:'playlist_grid',title:'Playlist'}),new MDB.Settings.Panel({border:false,title:'Settings'})]}]}]});viewport.render();MDB.Favorites.get();});if(!Ext.isAir){setTimeout(function(){Ext.get('loading').fadeOut({endOpacity:0,easing:'easeOut',duration:1,remove:true,useDisplay:true});Ext.get('loading-mask').fadeOut({endOpacity:0,easing:'easeOut',duration:1,remove:true,useDisplay:true});},1000);}
