/*
 * JsMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/
*/

var dp={sh:{Toolbar:{},Utils:{},RegexLib:{},Brushes:{},Strings:{AboutDialog:'<html><head><title>About...</title></head><body class="dp-about"><table cellspacing="0"><tr><td class="copy"><p class="title">dp.SyntaxHighlighter</div><div class="para">Version: {V}</p><p><a href="http://www.dreamprojections.com/syntaxhighlighter/?ref=about" target="_blank">http://www.dreamprojections.com/syntaxhighlighter</a></p>&copy;2004-2007 Alex Gorbatchev.</td></tr><tr><td class="footer"><input type="button" class="close" value="OK" onClick="window.close()"/></td></tr></table></body></html>'},ClipboardSwf:null,Version:'1.5.1'}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:'+ expand source',check:function(highlighter){return highlighter.collapse;},func:function(sender,highlighter)
{sender.parentNode.removeChild(sender);highlighter.div.className=highlighter.div.className.replace('collapsed','');}},ViewSource:{label:'view plain',func:function(sender,highlighter)
{var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/</g,'&lt;');var wnd=window.open('','_blank','width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=0');wnd.document.write('<textarea style="width:99%;height:99%">'+code+'</textarea>');wnd.document.close();}},CopyToClipboard:{label:'copy to clipboard',check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null;},func:function(sender,highlighter)
{var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');if(window.clipboardData)
{window.clipboardData.setData('text',code);}
else if(dp.sh.ClipboardSwf!=null)
{var flashcopier=highlighter.flashCopier;if(flashcopier==null)
{flashcopier=document.createElement('div');highlighter.flashCopier=flashcopier;highlighter.div.appendChild(flashcopier);}
flashcopier.innerHTML='<embed src="'+dp.sh.ClipboardSwf+'" FlashVars="clipboard='+encodeURIComponent(code)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';}
alert('The code is in your clipboard now');}},PrintSource:{label:'print',func:function(sender,highlighter)
{var iframe=document.createElement('IFRAME');var doc=null;iframe.style.cssText='position:absolute;width:0px;height:0px;left:-500px;top:-500px;';document.body.appendChild(iframe);doc=iframe.contentWindow.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write('<div class="'+highlighter.div.className.replace('collapsed','')+' printing">'+highlighter.div.innerHTML+'</div>');doc.close();iframe.contentWindow.focus();iframe.contentWindow.print();alert('Printing...');document.body.removeChild(iframe);}},About:{label:'?',func:function(highlighter)
{var wnd=window.open('','_blank','dialog,width=300,height=150,scrollbars=0');var doc=wnd.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace('{V}',dp.sh.Version));doc.close();wnd.focus();}}};dp.sh.Toolbar.Create=function(highlighter)
{var div=document.createElement('DIV');div.className='tools';for(var name in dp.sh.Toolbar.Commands)
{var cmd=dp.sh.Toolbar.Commands[name];if(cmd.check!=null&&!cmd.check(highlighter))
continue;div.innerHTML+='<a href="#" onclick="dp.sh.Toolbar.Command(\''+name+'\',this);return false;">'+cmd.label+'</a>';}
return div;}
dp.sh.Toolbar.Command=function(name,sender)
{var n=sender;while(n!=null&&n.className.indexOf('dp-highlighter')==-1)
n=n.parentNode;if(n!=null)
dp.sh.Toolbar.Commands[name].func(sender,n.highlighter);}
dp.sh.Utils.CopyStyles=function(destDoc,sourceDoc)
{var links=sourceDoc.getElementsByTagName('link');for(var i=0;i<links.length;i++)
if(links[i].rel.toLowerCase()=='stylesheet')
destDoc.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');}
dp.sh.Utils.FixForBlogger=function(str)
{return(dp.sh.isBloggerMode==true)?str.replace(/<br\s*\/?>|&lt;br\s*\/?&gt;/gi,'\n'):str;}
dp.sh.RegexLib={MultiLineCComments:new RegExp('/\\*[\\s\\S]*?\\*/','gm'),SingleLineCComments:new RegExp('//.*$','gm'),SingleLinePerlComments:new RegExp('#.*$','gm'),DoubleQuotedString:new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'",'g')};dp.sh.Match=function(value,index,css)
{this.value=value;this.index=index;this.length=value.length;this.css=css;}
dp.sh.Highlighter=function()
{this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;}
dp.sh.Highlighter.SortCallback=function(m1,m2)
{if(m1.index<m2.index)
return-1;else if(m1.index>m2.index)
return 1;else
{if(m1.length<m2.length)
return-1;else if(m1.length>m2.length)
return 1;}
return 0;}
dp.sh.Highlighter.prototype.CreateElement=function(name)
{var result=document.createElement(name);result.highlighter=this;return result;}
dp.sh.Highlighter.prototype.GetMatches=function(regex,css)
{var index=0;var match=null;while((match=regex.exec(this.code))!=null)
this.matches[this.matches.length]=new dp.sh.Match(match[0],match.index,css);}
dp.sh.Highlighter.prototype.AddBit=function(str,css)
{if(str==null||str.length==0)
return;var span=this.CreateElement('SPAN');str=str.replace(/ /g,'&nbsp;');str=str.replace(/</g,'&lt;');str=str.replace(/\n/gm,'&nbsp;<br>');if(css!=null)
{if((/br/gi).test(str))
{var lines=str.split('&nbsp;<br>');for(var i=0;i<lines.length;i++)
{span=this.CreateElement('SPAN');span.className=css;span.innerHTML=lines[i];this.div.appendChild(span);if(i+1<lines.length)
this.div.appendChild(this.CreateElement('BR'));}}
else
{span.className=css;span.innerHTML=str;this.div.appendChild(span);}}
else
{span.innerHTML=str;this.div.appendChild(span);}}
dp.sh.Highlighter.prototype.IsInside=function(match)
{if(match==null||match.length==0)
return false;for(var i=0;i<this.matches.length;i++)
{var c=this.matches[i];if(c==null)
continue;if((match.index>c.index)&&(match.index<c.index+c.length))
return true;}
return false;}
dp.sh.Highlighter.prototype.ProcessRegexList=function()
{for(var i=0;i<this.regexList.length;i++)
this.GetMatches(this.regexList[i].regex,this.regexList[i].css);}
dp.sh.Highlighter.prototype.ProcessSmartTabs=function(code)
{var lines=code.split('\n');var result='';var tabSize=4;var tab='\t';function InsertSpaces(line,pos,count)
{var left=line.substr(0,pos);var right=line.substr(pos+1,line.length);var spaces='';for(var i=0;i<count;i++)
spaces+=' ';return left+spaces+right;}
function ProcessLine(line,tabSize)
{if(line.indexOf(tab)==-1)
return line;var pos=0;while((pos=line.indexOf(tab))!=-1)
{var spaces=tabSize-pos%tabSize;line=InsertSpaces(line,pos,spaces);}
return line;}
for(var i=0;i<lines.length;i++)
result+=ProcessLine(lines[i],tabSize)+'\n';return result;}
dp.sh.Highlighter.prototype.SwitchToList=function()
{var html=this.div.innerHTML.replace(/<(br)\/?>/gi,'\n');var lines=html.split('\n');if(this.addControls==true)
this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns)
{var div=this.CreateElement('div');var columns=this.CreateElement('div');var showEvery=10;var i=1;while(i<=150)
{if(i%showEvery==0)
{div.innerHTML+=i;i+=(i+'').length;}
else
{div.innerHTML+='&middot;';i++;}}
columns.className='columns';columns.appendChild(div);this.bar.appendChild(columns);}
for(var i=0,lineIndex=this.firstLine;i<lines.length-1;i++,lineIndex++)
{var li=this.CreateElement('LI');var span=this.CreateElement('SPAN');li.className=(i%2==0)?'alt':'';span.innerHTML=lines[i]+'&nbsp;';li.appendChild(span);this.ol.appendChild(li);}
this.div.innerHTML='';}
dp.sh.Highlighter.prototype.Highlight=function(code)
{function Trim(str)
{return str.replace(/^\s*(.*?)[\s\n]*$/g,'$1');}
function Chop(str)
{return str.replace(/\n*$/,'').replace(/^\n*/,'');}
function Unindent(str)
{var lines=dp.sh.Utils.FixForBlogger(str).split('\n');var indents=new Array();var regex=new RegExp('^\\s*','g');var min=1000;for(var i=0;i<lines.length&&min>0;i++)
{if(Trim(lines[i]).length==0)
continue;var matches=regex.exec(lines[i]);if(matches!=null&&matches.length>0)
min=Math.min(matches[0].length,min);}
if(min>0)
for(var i=0;i<lines.length;i++)
lines[i]=lines[i].substr(min);return lines.join('\n');}
function Copy(string,pos1,pos2)
{return string.substr(pos1,pos2-pos1);}
var pos=0;if(code==null)
code='';this.originalCode=code;this.code=Chop(Unindent(code));this.div=this.CreateElement('DIV');this.bar=this.CreateElement('DIV');this.ol=this.CreateElement('OL');this.matches=new Array();this.div.className='dp-highlighter';this.div.highlighter=this;this.bar.className='bar';this.ol.start=this.firstLine;if(this.CssClass!=null)
this.ol.className=this.CssClass;if(this.collapse)
this.div.className+=' collapsed';if(this.noGutter)
this.div.className+=' nogutter';if(this.tabsToSpaces==true)
this.code=this.ProcessSmartTabs(this.code);this.ProcessRegexList();if(this.matches.length==0)
{this.AddBit(this.code,null);this.SwitchToList();this.div.appendChild(this.bar);this.div.appendChild(this.ol);return;}
this.matches=this.matches.sort(dp.sh.Highlighter.SortCallback);for(var i=0;i<this.matches.length;i++)
if(this.IsInside(this.matches[i]))
this.matches[i]=null;for(var i=0;i<this.matches.length;i++)
{var match=this.matches[i];if(match==null||match.length==0)
continue;this.AddBit(Copy(this.code,pos,match.index),null);this.AddBit(match.value,match.css);pos=match.index+match.length;}
this.AddBit(this.code.substr(pos),null);this.SwitchToList();this.div.appendChild(this.bar);this.div.appendChild(this.ol);}
dp.sh.Highlighter.prototype.GetKeywords=function(str)
{return'\\b'+str.replace(/ /g,'\\b|\\b')+'\\b';}
dp.sh.BloggerMode=function()
{dp.sh.isBloggerMode=true;}
dp.sh.HighlightAll=function(name,showGutter,showControls,collapseAll,firstLine,showColumns)
{function FindValue()
{var a=arguments;for(var i=0;i<a.length;i++)
{if(a[i]==null)
continue;if(typeof(a[i])=='string'&&a[i]!='')
return a[i]+'';if(typeof(a[i])=='object'&&a[i].value!='')
return a[i].value+'';}
return null;}
function IsOptionSet(value,list)
{for(var i=0;i<list.length;i++)
if(list[i]==value)
return true;return false;}
function GetOptionValue(name,list,defaultValue)
{var regex=new RegExp('^'+name+'\\[(\\w+)\\]$','gi');var matches=null;for(var i=0;i<list.length;i++)
if((matches=regex.exec(list[i]))!=null)
return matches[1];return defaultValue;}
function FindTagsByName(list,name,tagName)
{var tags=document.getElementsByTagName(tagName);for(var i=0;i<tags.length;i++)
if(tags[i].getAttribute('name')==name)
list.push(tags[i]);}
var elements=[];var highlighter=null;var registered={};var propertyName='innerHTML';FindTagsByName(elements,name,'pre');FindTagsByName(elements,name,'textarea');if(elements.length==0)
return;for(var brush in dp.sh.Brushes)
{var aliases=dp.sh.Brushes[brush].Aliases;if(aliases==null)
continue;for(var i=0;i<aliases.length;i++)
registered[aliases[i]]=brush;}
for(var i=0;i<elements.length;i++)
{var element=elements[i];var options=FindValue(element.attributes['class'],element.className,element.attributes['language'],element.language);var language='';if(options==null)
continue;options=options.split(':');language=options[0].toLowerCase();if(registered[language]==null)
continue;highlighter=new dp.sh.Brushes[registered[language]]();element.style.display='none';highlighter.noGutter=(showGutter==null)?IsOptionSet('nogutter',options):!showGutter;highlighter.addControls=(showControls==null)?!IsOptionSet('nocontrols',options):showControls;highlighter.collapse=(collapseAll==null)?IsOptionSet('collapse',options):collapseAll;highlighter.showColumns=(showColumns==null)?IsOptionSet('showcolumns',options):showColumns;var headNode=document.getElementsByTagName('head')[0];if(highlighter.Style&&headNode)
{var styleNode=document.createElement('style');styleNode.setAttribute('type','text/css');if(styleNode.styleSheet)
{styleNode.styleSheet.cssText=highlighter.Style;}
else
{var textNode=document.createTextNode(highlighter.Style);styleNode.appendChild(textNode);}
headNode.appendChild(styleNode);}
highlighter.firstLine=(firstLine==null)?parseInt(GetOptionValue('firstline',options,1)):firstLine;highlighter.Highlight(element[propertyName]);highlighter.source=element;element.parentNode.insertBefore(highlighter.div,element);}}
/*
 * JsMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/
*/

dp.sh.Brushes.Java=function()
{var keywords='abstract assert boolean break byte case catch char class const '+'continue default do double else enum extends '+'false final finally float for goto if implements import '+'instanceof int interface long native new null '+'package private protected public return '+'short static strictfp super switch synchronized this throw throws true '+'transient try void volatile while';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b','gi'),css:'number'},{regex:new RegExp('(?!\\@interface\\b)\\@[\\$\\w]+\\b','g'),css:'annotation'},{regex:new RegExp('\\@interface\\b','g'),css:'keyword'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-j';this.Style='.dp-j .annotation { color: #646464; }'+'.dp-j .number { color: #C00000; }';}
dp.sh.Brushes.Java.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Java.Aliases=['java'];
/*
 * JsMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/
*/

dp.sh.Brushes.JScript=function()
{var keywords='abstract boolean break byte case catch char class const continue debugger '+'default delete do double else enum export extends false final finally float '+'for function goto if implements import in instanceof int interface long native '+'new null package private protected public return short static super switch '+'synchronized this throw throws transient true try typeof var void volatile while with';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('^\\s*#.*','gm'),css:'preprocessor'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-c';}
dp.sh.Brushes.JScript.prototype=new dp.sh.Highlighter();dp.sh.Brushes.JScript.Aliases=['js','jscript','javascript'];
/*
 * JsMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/
*/

dp.sh.Brushes.Xml=function()
{this.CssClass='dp-xml';this.Style='.dp-xml .cdata { color: #ff1493; }'+'.dp-xml .tag, .dp-xml .tag-name { color: #069; font-weight: bold; }'+'.dp-xml .attribute { color: red; }'+'.dp-xml .attribute-value { color: blue; }';}
dp.sh.Brushes.Xml.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Xml.Aliases=['xml','xhtml','xslt','html','xhtml'];dp.sh.Brushes.Xml.prototype.ProcessRegexList=function()
{function push(array,value)
{array[array.length]=value;}
var index=0;var match=null;var regex=null;this.GetMatches(new RegExp('(\&lt;|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\&gt;|>)','gm'),'cdata');this.GetMatches(new RegExp('(\&lt;|<)!--\\s*.*?\\s*--(\&gt;|>)','gm'),'comments');regex=new RegExp('([:\\w-\.]+)\\s*=\\s*(".*?"|\'.*?\'|\\w+)*|(\\w+)','gm');while((match=regex.exec(this.code))!=null)
{if(match[1]==null)
{continue;}
push(this.matches,new dp.sh.Match(match[1],match.index,'attribute'));if(match[2]!=undefined)
{push(this.matches,new dp.sh.Match(match[2],match.index+match[0].indexOf(match[2]),'attribute-value'));}}
this.GetMatches(new RegExp('(\&lt;|<)/*\\?*(?!\\!)|/*\\?*(\&gt;|>)','gm'),'tag');regex=new RegExp('(?:\&lt;|<)/*\\?*\\s*([:\\w-\.]+)','gm');while((match=regex.exec(this.code))!=null)
{push(this.matches,new dp.sh.Match(match[1],match.index+match[0].indexOf(match[1]),'tag-name'));}}
/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/**
 * @class Ext.ux.StartMenu
 * @extends Ext.menu.Menu
 * A start menu object.
 * @constructor
 * Creates a new StartMenu
 * @param {Object} config Configuration options
 *
 * SAMPLE USAGE:
 *
 * this.startMenu = new Ext.ux.StartMenu({
 *		iconCls: 'user',
 *		height: 300,
 *		shadow: true,
 *		title: get_cookie('memberName'),
 *		width: 300
 *	});
 *
 * this.startMenu.add({
 *		text: 'Grid Window',
 *		iconCls:'icon-grid',
 *		handler : this.createWindow,
 *		scope: this
 *	});
 *
 * this.startMenu.addTool({
 *		text:'Logout',
 *		iconCls:'logout',
 *		handler:function(){ window.location = "logout.php"; },
 *		scope:this
 *	});
 */

Ext.namespace('Ext.exampledata');

Ext.exampledata.states = [
        ['AL', 'Alabama', 'The Heart of Dixie'],
        ['AK', 'Alaska', 'The Land of the Midnight Sun'],
        ['AZ', 'Arizona', 'The Grand Canyon State'],
        ['AR', 'Arkansas', 'The Natural State'],
        ['CA', 'California', 'The Golden State'],
        ['CO', 'Colorado', 'The Mountain State'],
        ['CT', 'Connecticut', 'The Constitution State'],
        ['DE', 'Delaware', 'The First State'],
        ['DC', 'District of Columbia', "The Nation's Capital"],
        ['FL', 'Florida', 'The Sunshine State'],
        ['GA', 'Georgia', 'The Peach State'],
        ['HI', 'Hawaii', 'The Aloha State'],
        ['ID', 'Idaho', 'Famous Potatoes'],
        ['IL', 'Illinois', 'The Prairie State'],
        ['IN', 'Indiana', 'The Hospitality State'],
        ['IA', 'Iowa', 'The Corn State'],
        ['KS', 'Kansas', 'The Sunflower State'],
        ['KY', 'Kentucky', 'The Bluegrass State'],
        ['LA', 'Louisiana', 'The Bayou State'],
        ['ME', 'Maine', 'The Pine Tree State'],
        ['MD', 'Maryland', 'Chesapeake State'],
        ['MA', 'Massachusetts', 'The Spirit of America'],
        ['MI', 'Michigan', 'Great Lakes State'],
        ['MN', 'Minnesota', 'North Star State'],
        ['MS', 'Mississippi', 'Magnolia State'],
        ['MO', 'Missouri', 'Show Me State'],
        ['MT', 'Montana', 'Big Sky Country'],
        ['NE', 'Nebraska', 'Beef State'],
        ['NV', 'Nevada', 'Silver State'],
        ['NH', 'New Hampshire', 'Granite State'],
        ['NJ', 'New Jersey', 'Garden State'],
        ['NM', 'New Mexico', 'Land of Enchantment'],
        ['NY', 'New York', 'Empire State'],
        ['NC', 'North Carolina', 'First in Freedom'],
        ['ND', 'North Dakota', 'Peace Garden State'],
        ['OH', 'Ohio', 'The Heart of it All'],
        ['OK', 'Oklahoma', 'Oklahoma is OK'],
        ['OR', 'Oregon', 'Pacific Wonderland'],
        ['PA', 'Pennsylvania', 'Keystone State'],
        ['RI', 'Rhode Island', 'Ocean State'],
        ['SC', 'South Carolina', 'Nothing Could be Finer'],
        ['SD', 'South Dakota', 'Great Faces, Great Places'],
        ['TN', 'Tennessee', 'Volunteer State'],
        ['TX', 'Texas', 'Lone Star State'],
        ['UT', 'Utah', 'Salt Lake State'],
        ['VT', 'Vermont', 'Green Mountain State'],
        ['VA', 'Virginia', 'Mother of States'],
        ['WA', 'Washington', 'Green Tree State'],
        ['WV', 'West Virginia', 'Mountain State'],
        ['WI', 'Wisconsin', "America's Dairyland"],
        ['WY', 'Wyoming', 'Like No Place on Earth']
    ];
Ext.namespace("Ext.ux");

Ext.ux.StartMenu = function(config){
	Ext.ux.StartMenu.superclass.constructor.call(this, config);
    
    var tools = this.toolItems;
    this.toolItems = new Ext.util.MixedCollection();
    if(tools){
        this.addTool.apply(this, tools);
    }
};

Ext.extend(Ext.ux.StartMenu, Ext.menu.Menu, {
    // private
    render : function(){
        if(this.el){
            return;
        }
        var el = this.el = new Ext.Layer({
            cls: "x-menu ux-start-menu", // this might affect item click
            shadow:this.shadow,
            constrain: false,
            parentEl: this.parentEl || document.body,
            zindex:15000
        });
        
        var header = el.createChild({
        	tag: "div",
        	cls: "x-window-header x-unselectable x-panel-icon "+this.iconCls
        });
		this.header = header;
		var headerText = header.createChild({
			tag: "span",
			cls: "x-window-header-text"
		});
		var tl = header.wrap({
			cls: "ux-start-menu-tl"
		});
		var tr = header.wrap({
			cls: "ux-start-menu-tr"
		});
		var tc = header.wrap({
			cls: "ux-start-menu-tc"
		});
		
		this.menuBWrap = el.createChild({
			tag: "div",
			cls: "x-window-body x-border-layout-ct ux-start-menu-body"
		});
		var ml = this.menuBWrap.wrap({
			cls: "ux-start-menu-ml"
		});
		var mc = this.menuBWrap.wrap({
			cls: "x-window-mc ux-start-menu-bwrap"
		});
		
		this.menuPanel = this.menuBWrap.createChild({
			tag: "div",
			cls: "x-panel x-border-panel ux-start-menu-apps-panel"
		});
		this.toolsPanel = this.menuBWrap.createChild({
			tag: "div",
			cls: "x-panel x-border-panel ux-start-menu-tools-panel"
		});
		
		var bwrap = ml.wrap({cls: "x-window-bwrap"});
		var bc = bwrap.createChild({
			tag: "div",
			cls: "ux-start-menu-bc",
			style: 'height: 30px'
		});
		var bl = bc.wrap({
			cls: "ux-start-menu-bl x-panel-nofooter"
		});
		var br = bc.wrap({
			cls: "ux-start-menu-br"
		});
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: 'blog2j_search.php'
			}),
			reader: new Ext.data.JsonReader({
				/*root: 'topics',
				totalProperty: 'totalCount',*/
				id: 'id'
			}, ['subject', 'id'
				/*{name: 'title', mapping: 'topic_title'},
				{name: 'topicId', mapping: 'topic_id'},
				{name: 'author', mapping: 'author'},
				{name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
				{name: 'excerpt', mapping: 'post_text'}*/
			])
		});		
		/*new Ext.form.ComboBox({
			renderTo: bc,
			displayField:'subject',
	        typeAhead: false,
	        mode: 'remote',
	        triggerAction: 'all',
	        emptyText:'Cerca nel sito...',
	        selectOnFocus:true,
			loadingText: 'Ricerca in corso...',
			store: ds,
		    initList : function(){
		    	Ext.form.ComboBox.prototype.initList.call(this);
		    	this.list.setZIndex(20000);
		    },
		    width: 287,
		    triggerClass: 'x-form-search-trigger'
		})*/
		
        this.keyNav = new Ext.menu.MenuNav(this);

        if(this.plain){
            el.addClass("x-menu-plain");
        }
        if(this.cls){
            el.addClass(this.cls);
        }
        // generic focus element
        this.focusEl = el.createChild({
            tag: "a",
            cls: "x-menu-focus",
            href: "#",
            onclick: "return false;",
            tabIndex:"-1"
        });
        
        var ul = this.menuPanel.createChild({
        	tag: "ul",
        	cls: "x-menu-list"});
        var toolsUl = this.toolsPanel.createChild({
        	tag: "ul",
        	cls: "x-menu-list"
        });
        
        var ulListeners = {
        	"click": {
        		fn: this.onClick,
        		scope: this
        	},
        	"mouseover": {
        		fn: this.onMouseOver,
        		scope: this
        	},
        	"mouseout": {
        		fn: this.onMouseOut,
        		scope: this
        	}
        };
        
        ul.on(ulListeners);
        
        this.items.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            ul.dom.appendChild(li);
	            item.render(li, this);
	        }, this);

        this.ul = ul;
        this.autoWidth();

        toolsUl.on(ulListeners);
        
        this.toolItems.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            toolsUl.dom.appendChild(li);
	            item.render(li, this);
	        }, this);
	        
        this.toolsUl = toolsUl;
        this.autoWidth();
             
        this.menuBWrap.setStyle('position', 'relative');  
        this.menuBWrap.setHeight(this.height);
        
        this.menuPanel.setStyle({
        	padding: '2px',
        	position: 'absolute',
        	overflow: 'auto'
        });
        
        this.toolsPanel.setStyle({
        	padding: '2px 4px 2px 2px',
        	position: 'absolute',
        	overflow: 'auto'
        });
        
        this.setTitle(this.title);
    },
    
    // private
    findTargetItem : function(e){
        var t = e.getTarget(".x-menu-list-item", this.ul,  true);
        if(t && t.menuItemId){
        	if(this.items.get(t.menuItemId)){
            	return this.items.get(t.menuItemId);
            }else{
            	return this.toolItems.get(t.menuItemId);
            }
        }
    },

    /**
     * Displays this menu relative to another element
     * @param {Mixed} element The element to align to
     * @param {String} position (optional) The {@link Ext.Element#alignTo} anchor position to use in aligning to
     * the element (defaults to this.defaultAlign)
     * @param {Ext.ux.StartMenu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
     */
    show : function(el, pos, parentMenu){
        this.parentMenu = parentMenu;
        if(!this.el){
            this.render();
        }

        this.fireEvent("beforeshow", this);
        this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
        
        var tPanelWidth = 120;      
        var box = this.menuBWrap.getBox();
        this.menuPanel.setWidth(box.width-tPanelWidth);
        this.menuPanel.setHeight(box.height);
        
        this.toolsPanel.setWidth(tPanelWidth);
        this.toolsPanel.setX(box.x+box.width-tPanelWidth);
        this.toolsPanel.setHeight(box.height);
    },
    
    addTool : function(){
        var a = arguments, l = a.length, item;
        for(var i = 0; i < l; i++){
            var el = a[i];
            if(el.render){ // some kind of Item
                item = this.addToolItem(el);
            }else if(typeof el == "string"){ // string
                if(el == "separator" || el == "-"){
                    item = this.addToolSeparator();
                }else{
                    item = this.addText(el);
                }
            }else if(el.tagName || el.el){ // element
                item = this.addElement(el);
            }else if(typeof el == "object"){ // must be menu item config?
                item = this.addToolMenuItem(el);
            }
        }
        return item;
    },
    
    /**
     * Adds a separator bar to the Tools
     * @return {Ext.menu.Item} The menu item that was added
     */
    addToolSeparator : function(){
        return this.addToolItem(new Ext.menu.Separator({itemCls: 'ux-toolmenu-sep'}));
    },

    addToolItem : function(item){
        this.toolItems.add(item);
        if(this.ul){
            var li = document.createElement("li");
            li.className = "x-menu-list-item";
            this.ul.dom.appendChild(li);
            item.render(li, this);
            this.delayAutoWidth();
        }
        return item;
    },

    addToolMenuItem : function(config){
        if(!(config instanceof Ext.menu.Item)){
            if(typeof config.checked == "boolean"){ // must be check menu item config?
                config = new Ext.menu.CheckItem(config);
            }else{
                config = new Ext.menu.Item(config);
            }
        }
        return this.addToolItem(config);
    },
    
    setTitle : function(title, iconCls){
        this.title = title;
        this.header.child('span').update(title);
        return this;
    }
});/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/**
 * @class Ext.ux.TaskBar
 * @extends Ext.util.Observable
 */
Ext.ux.TaskBar = function(app){
    this.app = app;
    this.init();
}

Ext.extend(Ext.ux.TaskBar, Ext.util.Observable, {
    init : function(){
		this.startMenu = new Ext.ux.StartMenu(Ext.apply({
			iconCls: 'user',
			height: 300,
			shadow: true,
			title: 'Blog2j',
			width: 300
		}, this.app.startConfig));
		
		this.startBtn = new Ext.Button({
            text: 'Start',
            id: 'ux-startbutton',
            iconCls:'start',
            menu: this.startMenu,
            menuAlign: 'bl-tl',
            renderTo: 'ux-taskbar-start',
            clickEvent:'mousedown',
            template: new Ext.Template(
				'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
				'<td class="ux-startbutton-left"><i>&#160;</i></td><td class="ux-startbutton-center"><em unselectable="on"><button class="x-btn-text" type="{1}" style="height:30px;">{0}</button></em></td><td class="ux-startbutton-right"><i>&#160;</i></td>',
				"</tr></tbody></table>")
        });
        
        var width = Ext.get('ux-startbutton').getWidth()+10;
        
        var sbBox = new Ext.BoxComponent({
			el: 'ux-taskbar-start',
	        id: 'TaskBarStart',
	        minWidth: width,
			region:'west',
			split: true,
			width: width
		});
		
		this.tbPanel = new Ext.ux.TaskButtonsPanel({
			el: 'ux-taskbuttons-panel',
			id: 'TaskBarButtons',
			region:'center'
		});
				
        var container = new Ext.ux.TaskBarContainer({
			el: 'ux-taskbar',
			layout: 'border',
			items: [sbBox,this.tbPanel]
		});
		
		return this;
    },
    
    addTaskButton : function(win){
		return this.tbPanel.addButton(win, 'ux-taskbuttons-panel');
	},
	
	removeTaskButton : function(btn){
		this.tbPanel.removeButton(btn);
	},
	
	setActiveButton : function(btn){
		this.tbPanel.setActiveButton(btn);
	}
});



/**
 * @class Ext.ux.TaskBarContainer
 * @extends Ext.Container
 */
Ext.ux.TaskBarContainer = Ext.extend(Ext.Container, {
    initComponent : function() {
        Ext.ux.TaskBarContainer.superclass.initComponent.call(this);
        
        this.el = Ext.get(this.el) || Ext.getBody();
        this.el.setHeight = Ext.emptyFn;
        this.el.setWidth = Ext.emptyFn;
        this.el.setSize = Ext.emptyFn;
        this.el.setStyle({
            overflow:'hidden',
            margin:'0',
            border:'0 none'
        });
        this.el.dom.scroll = 'no';
        this.allowDomMove = false;
        this.autoWidth = true;
        this.autoHeight = true;
        Ext.EventManager.onWindowResize(this.fireResize, this);
        this.renderTo = this.el;
    },

    fireResize : function(w, h){
        this.fireEvent('resize', this, w, h, w, h);
    }
});



/**
 * @class Ext.ux.TaskButtonsPanel
 * @extends Ext.BoxComponent
 */
Ext.ux.TaskButtonsPanel = Ext.extend(Ext.BoxComponent, {
	activeButton: null,
	enableScroll: true,
	scrollIncrement: 0,
    scrollRepeatInterval: 400,
    scrollDuration: .35,
    animScroll: true,
    resizeButtons: true,
    buttonWidth: 168,
    minButtonWidth: 118,
    buttonMargin: 2,
    buttonWidthSet: false,
	
	initComponent : function() {
        Ext.ux.TaskButtonsPanel.superclass.initComponent.call(this);
        this.on('resize', this.delegateUpdates);
        this.items = [];
        
        this.stripWrap = Ext.get(this.el).createChild({
        	cls: 'ux-taskbuttons-strip-wrap',
        	cn: {
            	tag:'ul', cls:'ux-taskbuttons-strip'
            }
		});
        this.stripSpacer = Ext.get(this.el).createChild({
        	cls:'ux-taskbuttons-strip-spacer'
        });
        this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
        
        this.edge = this.strip.createChild({
        	tag:'li',
        	cls:'ux-taskbuttons-edge'
        });
        this.strip.createChild({
        	cls:'x-clear'
        });
	},
	
	addButton : function(win){
		var li = this.strip.createChild({tag:'li'}, this.edge); // insert before the edge
        var btn = new Ext.ux.TaskBar.TaskButton(win, li);
		
		this.items.push(btn);
		
		if(!this.buttonWidthSet){
			this.lastButtonWidth = btn.container.getWidth();
		}
		
		this.setActiveButton(btn);
		return btn;
	},
	
	removeButton : function(btn){
		var li = document.getElementById(btn.container.id);
		btn.destroy();
		li.parentNode.removeChild(li);
		
		var s = [];
		for(var i = 0, len = this.items.length; i < len; i++) {
			if(this.items[i] != btn){
				s.push(this.items[i]);
			}
		}
		this.items = s;
		
		this.delegateUpdates();
	},
	
	setActiveButton : function(btn){
		this.activeButton = btn;
		this.delegateUpdates();
	},
	
	delegateUpdates : function(){
		/*if(this.suspendUpdates){
            return;
        }*/
        if(this.resizeButtons && this.rendered){
            this.autoSize();
        }
        if(this.enableScroll && this.rendered){
            this.autoScroll();
        }
    },
    
    autoSize : function(){
        var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var aw = this.el.dom.clientWidth;

        if(!this.resizeButtons || count < 1 || !aw){ // !aw for display:none
            return;
        }
        
        var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.buttonMargin, this.buttonWidth), this.minButtonWidth); // -4 for float errors in IE
        var btns = this.stripWrap.dom.getElementsByTagName('button');
        
        this.lastButtonWidth = Ext.get(btns[0].id).findParent('li').offsetWidth;
        
        for(var i = 0, len = btns.length; i < len; i++) {            
            var btn = btns[i];
            
            var tw = Ext.get(btns[i].id).findParent('li').offsetWidth;
            var iw = btn.offsetWidth;
            
            btn.style.width = (each - (tw-iw)) + 'px';
        }
    },
    
    autoScroll : function(){
    	var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var tw = this.el.dom.clientWidth;
        
        var wrap = this.stripWrap;
        var cw = wrap.dom.offsetWidth;
        var pos = this.getScrollPos();
        var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;
        
        if(!this.enableScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
            return;
        }
        
        wrap.setWidth(tw); // moved to here because of problem in Safari
        
        if(l <= tw){
            wrap.dom.scrollLeft = 0;
            //wrap.setWidth(tw); moved from here because of problem in Safari
            if(this.scrolling){
                this.scrolling = false;
                this.el.removeClass('x-taskbuttons-scrolling');
                this.scrollLeft.hide();
                this.scrollRight.hide();
            }
        }else{
            if(!this.scrolling){
                this.el.addClass('x-taskbuttons-scrolling');
            }
            tw -= wrap.getMargins('lr');
            wrap.setWidth(tw > 20 ? tw : 20);
            if(!this.scrolling){
                if(!this.scrollLeft){
                    this.createScrollers();
                }else{
                    this.scrollLeft.show();
                    this.scrollRight.show();
                }
            }
            this.scrolling = true;
            if(pos > (l-tw)){ // ensure it stays within bounds
                wrap.dom.scrollLeft = l-tw;
            }else{ // otherwise, make sure the active button is still visible
				this.scrollToButton(this.activeButton, true); // true to animate
            }
            this.updateScrollButtons();
        }
    },

    createScrollers : function(){
        var h = this.el.dom.offsetHeight; //var h = this.stripWrap.dom.offsetHeight;
		
        // left
        var sl = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-left'
        });
        sl.setHeight(h);
        sl.addClassOnOver('ux-taskbuttons-scroller-left-over');
        this.leftRepeater = new Ext.util.ClickRepeater(sl, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollLeft,
            scope: this
        });
        this.scrollLeft = sl;

        // right
        var sr = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-right'
        });
        sr.setHeight(h);
        sr.addClassOnOver('ux-taskbuttons-scroller-right-over');
        this.rightRepeater = new Ext.util.ClickRepeater(sr, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollRight,
            scope: this
        });
        this.scrollRight = sr;
    },
    
    getScrollWidth : function(){
        return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
    },

    getScrollPos : function(){
        return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
    },

    getScrollArea : function(){
        return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
    },

    getScrollAnim : function(){
        return {
        	duration: this.scrollDuration,
        	callback: this.updateScrollButtons,
        	scope: this
        };
    },

    getScrollIncrement : function(){
    	return (this.scrollIncrement || this.lastButtonWidth+2);
    },
    
    /* getBtnEl : function(item){
        return document.getElementById(item.id);
    }, */
    
    scrollToButton : function(item, animate){
    	item = item.el.dom.parentNode; // li
        if(!item){ return; }
        var el = item; //this.getBtnEl(item);
        var pos = this.getScrollPos(), area = this.getScrollArea();
        var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
        var right = left + el.offsetWidth;
        if(left < pos){
            this.scrollTo(left, animate);
        }else if(right > (pos + area)){
            this.scrollTo(right - area, animate);
        }
    },
    
    scrollTo : function(pos, animate){
        this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
        if(!animate){
            this.updateScrollButtons();
        }
    },
    
    onScrollRight : function(){
        var sw = this.getScrollWidth()-this.getScrollArea();
        var pos = this.getScrollPos();
        var s = Math.min(sw, pos + this.getScrollIncrement());
        if(s != pos){
        	this.scrollTo(s, this.animScroll);
        }        
    },

    onScrollLeft : function(){
        var pos = this.getScrollPos();
        var s = Math.max(0, pos - this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },
    
    updateScrollButtons : function(){
        var pos = this.getScrollPos();
        this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-left-disabled');
        this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-right-disabled');
    }
});



/**
 * @class Ext.ux.TaskBar.TaskButton
 * @extends Ext.Button
 */
Ext.ux.TaskBar.TaskButton = function(win, el){
	this.win = win;
    Ext.ux.TaskBar.TaskButton.superclass.constructor.call(this, {
        iconCls: win.iconCls,
        text: Ext.util.Format.ellipsis(win.title, 22),
        renderTo: el,
        handler : function(){
            if(win.minimized || win.hidden){
                win.show();
            }else if(win == win.manager.getActive()){
                win.minimize();
            }else{
                win.toFront();
            }
        },
        clickEvent:'mousedown',
        template: new Ext.Template(
			'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
			'<td class="ux-taskbutton-left"><i>&#160;</i></td><td class="ux-taskbutton-center"><em unselectable="on"><button class="x-btn-text" type="{1}" style="height:28px;">{0}</button></em></td><td class="ux-taskbutton-right"><i>&#160;</i></td>',
			"</tr></tbody></table>")
    });
};

Ext.extend(Ext.ux.TaskBar.TaskButton, Ext.Button, {
    onRender : function(){
        Ext.ux.TaskBar.TaskButton.superclass.onRender.apply(this, arguments);

        this.cmenu = new Ext.menu.Menu({
            items: [{
                text: 'Restore',
                handler: function(){
                    if(!this.win.isVisible()){
                        this.win.show();
                    }else{
                        this.win.restore();
                    }
                },
                scope: this
            },{
                text: 'Minimize',
                handler: this.win.minimize,
                scope: this.win
            },{
                text: 'Maximize',
                handler: this.win.maximize,
                scope: this.win
            }, '-', {
                text: 'Close',
                handler: this.closeWin.createDelegate(this, this.win, true),
                scope: this.win
            }]
        });

        this.cmenu.on('beforeshow', function(){
            var items = this.cmenu.items.items;
            var w = this.win;
            items[0].setDisabled(w.maximized !== true && w.hidden !== true);
            items[1].setDisabled(w.minimized === true);
            items[2].setDisabled(w.maximized === true || w.hidden === true);
        }, this);

        this.el.on('contextmenu', function(e){
            e.stopEvent();
            if(!this.cmenu.el){
                this.cmenu.render();
            }
            var xy = e.getXY();
            xy[1] -= this.cmenu.el.getHeight();
            this.cmenu.showAt(xy);
        }, this);
    },
    
    closeWin : function(cMenu, e, win){
		if(!win.isVisible()){
			win.show();
		}else{
			win.restore();
		}
		win.close();
	}
});/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.Desktop = function(app){
	this.taskbar = new Ext.ux.TaskBar(app);
	var taskbar = this.taskbar;
	
	var desktopEl = Ext.get('x-desktop');
    var taskbarEl = Ext.get('ux-taskbar');
    var shortcuts = Ext.get('x-shortcuts');

    var windows = new Ext.WindowGroup();
    var activeWindow;
		
    function minimizeWin(win){
        win.minimized = true;
        win.hide();
    }

    function markActive(win){
        if(activeWindow && activeWindow != win){
            markInactive(activeWindow);
        }
        taskbar.setActiveButton(win.taskButton);
        activeWindow = win;
        Ext.fly(win.taskButton.el).addClass('active-win');
        win.minimized = false;
    }

    function markInactive(win){
        if(win == activeWindow){
            activeWindow = null;
            Ext.fly(win.taskButton.el).removeClass('active-win');
        }
    }

    function removeWin(win){
    	taskbar.removeTaskButton(win.taskButton);
        layout();
    }

    function layout(){
        desktopEl.setHeight(Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight());
    }
    Ext.EventManager.onWindowResize(layout);

    this.layout = layout;

    this.createWindow = function(config, cls){
    	var win = new (cls||Ext.Window)(
            Ext.applyIf(config||{}, {
                manager: windows,
                minimizable: true,
                maximizable: true
            })
        );
        win.render(desktopEl);
        win.taskButton = taskbar.addTaskButton(win);

        win.cmenu = new Ext.menu.Menu({
            items: [

            ]
        });

        win.animateTarget = win.taskButton.el;
        
        win.on({
        	'activate': {
        		fn: markActive
        	},
        	'beforeshow': {
        		fn: markActive
        	},
        	'deactivate': {
        		fn: markInactive
        	},
        	'minimize': {
        		fn: minimizeWin
        	},
        	'close': {
        		fn: removeWin
        	}
        });
        
        layout();
        return win;
    };

    this.getManager = function(){
        return windows;
    };

    this.getWindow = function(id){
        return windows.get(id);
    }
    
    this.getWinWidth = function(){
		var width = Ext.lib.Dom.getViewWidth();
		return width < 200 ? 200 : width;
	}
		
	this.getWinHeight = function(){
		var height = (Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight());
		return height < 100 ? 100 : height;
	}
		
	this.getWinX = function(width){
		return (Ext.lib.Dom.getViewWidth() - width) / 2
	}
		
	this.getWinY = function(height){
		return (Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight() - height) / 2;
	}

    layout();

    if(shortcuts){
        shortcuts.on('click', function(e, t){
            if(t = e.getTarget('dt', shortcuts)){
                e.stopEvent();
                var module = app.getModule(t.id.replace('-shortcut', ''));
                if(module){
                    module.createWindow();
                }
            }
        });
    }
};
/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.app.App = function(cfg){
    Ext.apply(this, cfg);
    this.addEvents({
        'ready' : true,
        'beforeunload' : true
    });

    Ext.onReady(this.initApp, this);
};

Ext.extend(Ext.app.App, Ext.util.Observable, {
    isReady: false,
    startMenu: null,
    modules: null,

    getStartConfig : function(){

    },

    initApp : function(){
    	this.startConfig = this.startConfig || this.getStartConfig();

        this.desktop = new Ext.Desktop(this);

		this.launcher = this.desktop.taskbar.startMenu;

		this.modules = this.getModules();
        if(this.modules){
            this.initModules(this.modules);
        }

        this.init();
        
        this.initAutorun(this.modules);

        Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
		this.fireEvent('ready', this);
        this.isReady = true;
    },

	initAutorun : function(ms){
		Ext.each(ms, function(m) {
			if (m.autoRun) {
	            m.createWindow();       
			}
		});
    },
    
    getModules : Ext.emptyFn,
    init : Ext.emptyFn,

    initModules : function(ms){
		for(var i = 0, len = ms.length; i < len; i++){
            var m = ms[i];
            this.launcher.add(m.launcher);
            m.app = this;
        }
    },

    getModule : function(name){
    	var ms = this.modules;
    	for(var i = 0, len = ms.length; i < len; i++){
    		if(ms[i].id == name || ms[i].appType == name){
    			return ms[i];
			}
        }
        return '';
    },

    onReady : function(fn, scope){
        if(!this.isReady){
            this.on('ready', fn, scope);
        }else{
            fn.call(scope, this);
        }
    },

    getDesktop : function(){
        return this.desktop;
    },

    onUnload : function(e){
        if(this.fireEvent('beforeunload', this) === false){
            e.stopEvent();
        }
    }
});/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.app.Module = function(config){
    Ext.apply(this, config);
    Ext.app.Module.superclass.constructor.call(this);
    this.init();
}

Ext.extend(Ext.app.Module, Ext.util.Observable, {
    init : Ext.emptyFn
});GridWindow = function(text, params, autoRun) {
	this.id = Ext.id();
	this.text = text
	if (params) {
		this.params = "&" + params;
	}
	else {
		this.params = "";
	}
	this.autoRun = autoRun;
	GridWindow.superclass.constructor.call(this);
};

function linkResto(values) {
	var r = '<p>'
	var t = entryTitle(values.subject);
	if (values.content) {
		r += String.format(
			'<a href="#" onclick=\'MyDesktop.getEntryModule().createWindow(\"{0}\", \"{1}\")\'>Leggi il resto</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 
			t, values.id);
	}

	var commentId = entryCommentId(values.subject);
	if (commentId) {
		r += String.format("<a href='#' onclick='MyDesktop.getCommentModule().createWindow({0}, \"{1}\")'>Commenti</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 
		commentId, t);
	}

/*	r += String.format(
		'<a href="desktop?{0}" target="_blank">Link diretto</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 
		Ext.urlEncode({entry: values.id}));
	if (blog2jUser.isAdmin) {
		r += String.format("<a href='#' onclick='MyDesktop.getEditPostModule().createWindow({0}, \"{1}\")'>Edit</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 
			values.id);
	}*/
	return r + '</p>';
}

Ext.extend(GridWindow, Ext.app.Module, {
	
    init : function(){
        this.launcher = {
            text: this.text,
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },

	createStore: function(link, expander) {
	},
	
	createColumnModel: function() {
	},
	
	autoExpandColumn: null,

	populateGrid: function() {
		var desktop = this.app.getDesktop();
		var expander = new Ext.grid.RowExpander({
			tpl : new Ext.XTemplate(
				'{abstract} {[linkResto(values)]}'
			)
		});
		
        var cm = this.createColumnModel(expander);
        var store = this.createStore();
        
        var grid = new Ext.grid.GridPanel({
            border:false,
            trackMouseOver: false,
            ds: store,
            cm: cm,
            viewConfig: {
                forceFit:true
            },
            plugins: expander,
            autoExpandColumn: 'titoloCol',
            disableSelection: true
        });
        win = desktop.createWindow({
            id: this.id,
            title: this.text,
            width:740,
            height:480,
            iconCls: 'icon-grid',
            shim:false,
            animCollapse:false,
            constrainHeader:true,

            layout: 'fit',
            items: grid,
            bbar: this.getBbar(),
            tools: [{
			    id:'refresh',
			    qtip: 'Refresh',
			    handler: function(event, toolEl, panel) {
			    	store.load();
			    }
			}]
        });
		
		store.load();        
        store.on('load', function(records) {
	        for (var i=0; i<Math.min(3, records.getCount()); i++) {
	        	expander.expandRow(i);
	        }
        }, this);
        
        win.show();
        return win;		
	},
	
	getBbar: function() {
	},

    createWindow : function(){
        var win = null;
        if (this.app) {
	        var desktop = this.app.getDesktop();
	        var win = desktop.getWindow(this.id);
        }
        if(!win){
        	win = this.populateGrid();
        }
        else {
	        win.show();
        }
    }
});
EntryListModule = function(text, params, autoRun) {
	EntryListModule.superclass.constructor.call(this, text, params, autoRun);
};

function entryTitle(s) {
	var i = s.indexOf('<');
	if (i != -1) {
		return s.substring(0, i);
	}
	return s;	
}

function entryCommentId(s) {
	var i = s.indexOf('topic/');
	if (i != -1) {
		return s.substring(i + 6, s.lastIndexOf('"'));
	}
}

Ext.extend(EntryListModule, GridWindow, {
	
	boldRenderer: function(s) {
		return '<b>' + s + '</b>';
	},
	
	titleRenderer: function(s) {
		return '<b>' + entryTitle(s) + '</b>';
	},
	
	categoryRenderer: function(c) {
		var s = '';
		if (c) {
			Ext.each(c, function(cat) {
				if (s.length) {
					s += ', ';
				}
				s += String.format('<a href="#" onclick=\'MyDesktop.createCategoryEntryList("{0}")\'>{0}</a>', cat);
			});
		}
		return s;
	},

	createStore: function() {
    	var store = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
	            url: 'searchPost?abc=1' + this.params
	        }),
	
	        // create reader that reads the Topic records
	        reader: new Ext.data.JsonReader({
	            root: 'entries',
	            totalProperty: 'totalCount',
	            id: 'id',
	            fields: [
	                'subject', 'id', 'abstract', 'content', 'date', 'categories'//, 'comments', 'views', 'permalink', 'ratings'
	            ]
	        })
        });
		return store;
	},
	
	createColumnModel: function(expander) {
		return new Ext.grid.ColumnModel([
            expander,
            {header: "Data", width: 33, sortable: true, dataIndex: 'date', renderer: this.boldRenderer},
            {header: "Titolo", id: "titoloCol", width: 120, sortable: true, dataIndex: 'subject', renderer: this.titleRenderer},
            //{header: "id", width: 70, sortable: true, dataIndex: 'id'},
            //{header: "Contenuto", width: 70, sortable: true, dataIndex: 'content'},
            {header: "Categorie", width: 70, sortable: true, dataIndex: 'categories', renderer: this.categoryRenderer}
            //{header: "Commenti", width: 70, sortable: true, dataIndex: 'subject', renderer: this.commentRenderer}
            //{header: "Visualizzazioni", width: 70, sortable: true, dataIndex: 'views'},
            //{header: "Ratings", width: 70, sortable: true, dataIndex: 'ratings'}
        ]);
	},
		
	autoExpandColumn: 'titoloCol'

});
EntryModule = Ext.extend(Ext.app.Module, {
	id: 'entryModule',
	
    init : function(){
    },
    
    reload: function() {
  		Ext.Ajax.request({
           url: "searchPost?entry=" + this.entryId + "&theme=json&allPost=true",
           success: function(resp) {
	           	var r = Ext.decode(resp.responseText);
	           	var cont = r.entries[0].content;
	           	if (cont.indexOf('<script src="') === 0) {
	           		inc(cont.substring(13, cont.indexOf('">')));
	           	}
	           	win.setTitle(r.entries[0].subject);
	           	/*
	           	var adEl = Ext.get('ad_' + this.entryId);
	           	adEl.update("document.write('<s'+'cript type=\"text/javascript\" src=\"http://ad.altervista.org/js.ad/size=728X90/r='+new Date().getTime()+'\"><\/s'+'cript>');");
	           	* */
	           	var commentEl = Ext.get('inner_' + this.entryId);
	           	commentEl.update(r.entries[0].abstract + cont);
	           	dp.SyntaxHighlighter.HighlightAll('code');
	            CommentModule.addTanglerFrame(entryCommentId(r.entries[0].subject), 'tangler-entry-embed-topic-' + this.entryId);
           },
           scope: this
       });
	},

    createWindow : function(title, id){
    	this.entryId = id;
		if (typeof(pageTracker) != 'undefined' && pageTracker._trackPageview) {
			pageTracker._trackPageview("/post/" + title);
		}
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('entryModule-win' + id);
        if(!win){
            win = desktop.createWindow({
                id: 'entryModule-win' + id,
                title: title,
                width: Ext.get('x-desktop').getWidth() * 0.8,
                height:480,
                items: [
	                {
	                	id: 'inner_' + id
	                },
	                /*{
						html: '<script type="text/javascript">' +
							'//<![CDATA[' +
							"document.write('<s'+'cript type=\"text/javascript\" src=\"http://ad.altervista.org/js.ad/size=728X90/r='+new Date().getTime()+'\"><\/s'+'cript>');" +
							'//]]>' +
							'</script>'
	                },
	                {
						html: '<script type="text/javascript" id="ad_' + id + '"></script>'	                
	                },*/
	                {
						html: '<span id="tangler-entry-embed-topic-' + id + '"></span>'	                
	                }
	            ],
                bodyStyle: {'background-color':'white'},
                icon: '/images/email_edit.png',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                autoScroll: true,
	            tools: [{
				    id:'refresh',
				    qtip: 'Refresh',
				    handler: function(event, toolEl, panel) {
				    	this.reload();
				    },
				    scope: this
				}]
            });
			this.reload();
        }
        win.show();
    }
});CommentModule = Ext.extend(Ext.app.Module, {
	id: 'CommentModule',
	
    init : function(){
    },

    createWindow : function(id, title){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('CommentModule-win' + id);
        if(!win){
            win = desktop.createWindow({
                id: 'CommentModule-win' + id,
                title: 'Commenti ' + title,
                width:650,
                height:480,
                html: '<span id="tangler-embed-topic-' + id + '"></span>',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                autoScroll: true
            });
        }
        win.show();
        win.on('show', function() {
        	CommentModule.addTanglerFrame(id, 'tangler-embed-topic-' + id);
        });
    }
});

CommentModule.addTanglerFrame = function(id, spanId) {
	var sp = Ext.get(spanId);
	if (sp) {
		var gId = 23939;
		
		var width = "100%";
		var height = "100%";
		
		var iframeSrc = 'http://www.tangler.com/embed/topic/' + id;
			
		var iframe = document.createElement("iframe");
		iframe.id = "tangler-iframe-" + id;
		iframe.src = iframeSrc;
		iframe.width = width;
		iframe.height = height;
		iframe.scolling = 'no';
		iframe.marginwidth = '0';
		iframe.marginheight = '0';
		iframe.frameborder = '0';
		iframe.style.border = 0;
		var isIE = window.ActiveXObject?true:false;
		if( !isIE ) 
		{
			var a = document.createElement("a");
			a.href = 'http://localhost:8080/forum/id-' + gId + '/topic/' + id;
			a.target = "_blank";
			a.appendChild(document.createTextNode("Join this disucssion"));
			iframe.appendChild(a);
		}
	
		sp.replaceWith(iframe);  		
	}
};ContactModule = Ext.extend(Ext.app.Module, {
	id: 'ContactModule',
	
    init : function(){
        this.launcher = {
            text: 'Contatti',
            iconCls: 'contatti-icon',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('ContactModule-win');
        if(!win){
            win = desktop.createWindow(blog2j.creaContactWindowConfig());
        }
        win.show();
    }
});ServerPageModule = function(title, iconCls, page) {
	this.title = title;
	this.iconCls = iconCls;
	this.page = page;
	this.id = Ext.id();
	ServerPageModule.superclass.constructor.call(this);
}

Ext.extend(ServerPageModule, Ext.app.Module, {
    init : function(){
        this.launcher = {
            text: this.title,
            iconCls: this.iconCls,
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow(this.id + '-win');
        if(!win){
            win = desktop.createWindow({
                id: this.id + '-win',
                title: this.title,
                width: 600,
                height:320,
                iconCls: this.iconCls,
                layout: 'fit',
                items: {
                	id: this.id + '_inner'
                },
                bodyStyle: {
                	'background-color':'white'
                },
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                autoScroll: true
            });
			Ext.Ajax.request({
	            url: this.page,
	            success: function(resp) {
	            	Ext.get(this.id + '_inner').update(resp.responseText);
	            },
	            scope: this
	        });            
        }
        win.show();
    }
});Ext.namespace('blog2j');

if(Ext.form.DateField){
   Ext.apply(Ext.form.DateField.prototype, {
      altFormats        : "d/m/Y|d-m-y|d-m-Y|d/m|d-m|dm|dmy|dmY|d|Y-m-d|Y-m-d H:i:s"
   });
   Ext.apply(Ext.form.TimeField.prototype, {
   	  format: 'H:i',
      altFormats        : Ext.form.TimeField.prototype.altFormats + '|H:i:s' 
   });
}

function inc(filename) {
	var script = document.createElement("script");
    script.setAttribute("src", filename);
    script.setAttribute("type", "text/javascript");
    script.setAttribute("id", Ext.id());
    document.getElementsByTagName("head")[0].appendChild(script);
}

MyDesktop = new Ext.app.App({
	init :function(){
		Ext.QuickTips.init();
		if (this.entry) {
			this.getEntryModule().createWindow(this.entryTitle, this.entry);
		}
	},
	
	getCommentModule: function() {
		if (!this.commentModule) {
			this.commentModule = new CommentModule();
			this.commentModule.app = this;
		}
		return this.commentModule;
	},
		
	getEntryModule: function() {
		if (!this.entryModule) {
			this.entryModule = new EntryModule();
			this.entryModule.app = this;
		}
		return this.entryModule;
	},
		
	getEditPostModule: function() {
		var editEntryModule = new EditPostModule();
		editEntryModule.app = this;
		return editEntryModule;
	},
	
	createCategoryEntryListModule: function(text) {
		var tmp = this.entryListModules[text] = new EntryListModule(text, "category=" + text);
		tmp.app = this;
		return tmp;		
	},

	createCategoryEntryList: function(text) {
		if (!this.entryListModules[text]) {
			this.entryListModules[text] = this.createCategoryEntryListModule(text);
		}
		this.entryListModules[text].createWindow();
	},
	
	getModules : function(){
		if (!this.mainModules) {
			var paramsString = location.search;
			if (paramsString) {
				var params = Ext.urlDecode(paramsString.substring(1));
				if (params) {
					this.entry = params.entry;
					//TODO
					//this.entryTitle = mainEntrySubject;
				}
			}
			this.mainModules = [
				new EntryListModule('Post recenti', undefined, this.entry == null)
			];
			if (blog2jUser.isAdmin)
				this.mainModules.push(new EditPostModule());
			this.mainModules.push(new ContactModule());
			//this.mainModules.push(new ServerPageModule('Links', 'links-icon', "docs/links.html"));
			/*if (!blog2jUser.nickname)
				this.mainModules.push(
				{
					launcher: {
						text: 'Login',
						href: 'login',
						hrefTarget: '_blank',
						icon: 'images/layout_content.png'
					}
				});*/
			if (blog2jUser.nickname)
				this.mainModules.push(
				{
					launcher: {
						text: 'Logout',
						href: 'logout',
						hrefTarget: '_blank',
						icon: 'images/layout_content.png'
					}
				});
			this.mainModules.push(
			{
				launcher: {
					text: 'Versione classica',
					href: '/',
					hrefTarget: '_blank',
					icon: 'images/layout_content.png'
				}
			});
			this.mainModules.push(
			{
				launcher: {
					text: 'Feed rss',
					href: 'rss',
					hrefTarget: '_blank',
					icon: 'images/feed_add.png'
				}
			});
			this.mainModules.push(
				new ServerPageModule('Licenza e liberatoria', 'licenza-icon', "docs/licenza.html")
			);
		}
		return this.mainModules;
	},
	
	changeMenu: function(modules) {
		this.launcher.removeAll();
		this.initModules(modules);
	},
	
	entryListModules: {},
	
    // config for the start menu
    getStartConfig : function(){
    	this.entryListModules[1] = this.createCategoryEntryListModule('Java');
    	this.entryListModules[2] = this.createCategoryEntryListModule('Javascript');
    	this.entryListModules[4] = this.createCategoryEntryListModule('Groovy');
    	this.entryListModules[5] = this.createCategoryEntryListModule('Tutorials');
        return {
            iconCls: 'user',
            toolItems: [
            {
                text:'Home',
                icon: 'http://www.cachefile.net/graphics/ui/famfamfam/silk/icons/application_home.png',
                handler: this.changeMenu.createDelegate(this, [this.getModules()]),
                hideOnClick: false
            },
            {
                text:'Categorie',
                icon: 'images/layers.png',
                handler: this.changeMenu.createDelegate(this, [[
					this.entryListModules[1],
					this.entryListModules[4],
					this.entryListModules[5]
                ]]),
                hideOnClick: false
            }]
        };
    }
});
