// vim: ts=2:sw=2:nu:fdc=4:nospell
/**
	* Ext.InfoPanel and Ext.Accordion Example Application
	*
	* @author  Ing. Jozef Sakalos
	* @version $Id: accordion.js 409 2007-06-09 12:02:15Z jozo $
	*
	*/

// set blank image to local file
Ext.BLANK_IMAGE_URL = '/extjs/resources/images/default/s.gif';

// {{{
/**
	* Ext.example class
	*
	* To display sliding popup. Borrowed from ExtJS examples.
	* 
	* @class Ext.exammple
	* @singleton
	*
	*/
Ext.example = function() {
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, 
								'</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 'bl-bl', [10, -90]);
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('b').pause(1).ghost("b", {remove:true});
				}
    };
}();
// }}}

// run this function when document becomes ready
Ext.onReady(function() {

	// {{{
	// function to remove loading mask
	var unmask = function() {
		var mask = Ext.get('loading-mask');
		var msg = Ext.get('loading-msg');
		if(mask && msg) {
			mask.shift({
				xy:msg.getXY()
				, width:msg.getWidth()
				, height:msg.getHeight()
				, remove: true
				, duration: 1.6
				, opacity: 0.3
				, easing: 'bounceOut'
				, callback: function(){Ext.fly(msg).remove();}
			});
		}
	};
	// }}}

	// install onclick handler to unmask body (for debugging)
	Ext.fly('loading-mask').on('click', unmask);

	// initialize state manager, we will use cookies
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

	// initialize QuickTips
	Ext.QuickTips.init();
	Ext.apply(Ext.QuickTips, {interceptTitles: true});

	// {{{
	// create layout
	var layout = new Ext.BorderLayout(document.body, {
		hideOnLayout: true
		, north: { split: false, initialSize: 34, titlebar: false }
		, west: {
			split: true
			, initialSize: 254
			, minSize: 254
			, maxSize: 300
			, titlebar: false
			, collapsible: true
			, showPin: true
			, animate: true
		}
		, center: { 
			titlebar: true 
			, autoScroll: false 
		}
		, south: { 
			titlebar: true
			, split: true
			, initialSize: 80
			, collapsible: true
			, collapsed: true
			, hidden: false 
			, collapsedTitle: 'South'
			, animate: true
			, showPin: true
		}
	});
	// }}}
	// {{{
	// create accordion in west region
	var acc = new Ext.Accordion('west', { 
		title: 'Accordion' 
		, body: 'west-body'
		, fitContainer: true 
		, fitToFrame: true 
		, useShadow: true
//		, resizable: false
//		, draggable: false
	});
	// }}}
	// {{{
	// create global toolbar
	acc.toolbar = new Ext.Toolbar('acc-tb-global', [

		// reset order
		{	tooltip: 'Reset order'
			, cls: 'x-btn-icon'
			, icon: '../../img/silk/icons/application_put.png'
			, scope: acc
			, handler: acc.resetOrder
		}

		// undockable mode
		, {	tooltip: 'Undockable mode'
			, cls: 'x-btn-icon'
			, enableToggle: true
			, id: 'btn-undockable'
			, icon: '/img/silk/icons/layout_content.png'
			, scope: acc
			, handler: function(btn, e) {
				this.setUndockable(btn.pressed);
			}
		}

		// independent mode
		, {	tooltip: 'Independent mode'
			, cls: 'x-btn-icon'
			, enableToggle: true
			, id: 'btn-independent'
			, icon: '/img/silk/icons/application_tile_vertical.png'
			, scope: acc
			, handler: function(btn, e) {
				if(!btn.pressed) {
					this.collapseAll(false);
				}
				this.setIndependent(btn.pressed);
			}
		}

		// collapse all
		, {	tooltip: 'Collapse all (also pinned)'
			, cls: 'x-btn-icon'
			, icon: '/img/silk/icons/application_view_list.png'
			, scope: acc
			, handler: function(btn, e) {
			  this.collapseAll(true);
			}
		}

		// expand all
		, {	tooltip: 'Expand all (in independent mode)'
			, cls: 'x-btn-icon'
			, icon: '/img/silk/icons/application_view_tile.png'
			, scope: acc
			, handler: function(btn, e) {
			  this.expandAll();
			}
		}

		// use shadows
		, {	tooltip: 'Use shadows for undocked panels'
			, id: 'btn-shadow'
			, cls: 'x-btn-icon'
			, enableToggle: true
			, icon: '/img/silk/icons/contrast_low.png'
			, scope: acc
			, handler: function(btn, e) {
			  this.setShadow(btn.pressed);
			}
		}

		// separator
		, '-'

		// find text
		, 'Find:'

		// search text input field
		, new Ext.form.TextField({
			  id: 'find-field'
			, msgTarget:'side'
			, autoCreate: {
				  tag:'input'
				, type:'text'
				, qtip:'Try to type <b>&quot;acc&quot;</b> here.<br>'
						+ 'Then switch to independent mode and type <b>&quot;note&quot;</b> here.<br>'
						+ 'You can try also <b>&quot;dev&quot;</b> and <b>&quot;comp&quot;</b>'
				, size:3
			}
		})
	]);
	// }}}
	// {{{
	// add panels to accordion
	// Introduction
	var panel1 = new Ext.InfoPanel('panel-1', {
		trigger:'title', collapsed:true
		, icon:'../../img/silk/icons/lightbulb.png'
		, showPin: true
		, collapseOnUnpin: false
	});

	// example of installing custom panel event handlers
	acc.add(panel1);
	panel1.on('expand', function(panel) {
		Ext.example.msg('expand event handler', 'Panel: ' + panel.getTitle());
	});

	panel1.on('collapse', function(panel) {
		Ext.example.msg('collapse event handler', 'Panel: ' + panel.getTitle());
	});

	// extjs
	acc.add(new Ext.InfoPanel('panel-2', {
		trigger:'title', collapsed:true
		, icon:'../../img/silk/icons/brick.png'
		, showPin: true
		, collapseOnUnpin: false
	}));

	// usage
	var panel3 = acc.add(new Ext.InfoPanel('panel-3', {
		trigger:'title', collapsed:true
		, icon:'../../img/silk/icons/layout.png'
	}));

	// create toolbar for panel 3
	var toolbar3 = panel3.createToolbar();

	// add greedy spacer to align button right
	Ext.fly(toolbar3.addSpacer().getEl().parentNode).setStyle('width', '100%');
	toolbar3.add([{
		icon:'../../img/silk/icons/application_put.png'
		, cls: 'x-btn-text-icon'
		, text: 'Reset order'
		, scope: acc
		, handler: acc.resetOrder
	}]);

	// drag & drop
	var panel4 = acc.add(new Ext.InfoPanel('panel-4', {
		trigger:'title', collapsed:true
		, icon:'../../img/silk/icons/mouse.png'
	}));

	// create bottom toolbar for panel 4
	var toolbar4 = panel4.createToolbar([], true);

	// add greedy spacer to align button right
	Ext.fly(toolbar4.addSpacer().getEl().parentNode).setStyle('width', '100%');
	toolbar4.add([{
		icon:'/img/silk/icons/mouse.png'
		, cls: 'x-btn-text-icon'
		, text: 'Button'
		, scope: this
		, handler: function() {
			alert('You clicked me');
		}
	}]);

	// configuration options
	acc.add(new Ext.InfoPanel('panel-5', {
		trigger:'title'
		, collapsed:true
		, icon:'../../img/silk/icons/wrench.png'
//		, autoScroll: true
	}));

	// custom functions
	var panel6 = acc.add(new Ext.InfoPanel({
		title:'6. Custom functions'
		, icon:'../../img/silk/icons/script.png'
		, id:'panel-6'
		, autoCreate: {
			tag:'div'
		}
	}));

	// set content for panel 6
	panel6.update(
		'<div class="text-content">'
		+ '<p>Both Accordion and InfoPanel expose an Application Programming Interface (API) that makes'
		+ ' implementation of custom functions easy.</p>'
		+ '<p>The above Search function is one example of that. Try to'
		+ ' type three or more characters in the Find input.</p>'
		+ '</div>'
	);

	// theme selector
	var panel7 = acc.add(new Ext.InfoPanel('panel-7', {
		icon: '/img/silk/icons/palette.png'
		, showPin: true
		, minWidth: 200
		, minHeight: 100
	}));
	var ctheme = new Ext.form.ComboBox({
		typeAhead: true
		, triggerAction: 'all'
		, transform: 'theme-combo'
		, forceSelection: true
		, width: 140
		, listWidth: 158
	});

	// change theme on combo select
	ctheme.on('select', function() {
		var theme = Ext.getDom('theme');
		var newTheme, headEl;
		if(Ext.isIE) {
			newTheme = document.createElement('link');
			newTheme.rel = 'stylesheet';
			newTheme.type = 'text/css';
			newTheme.href = '../resources/css/' + this.getValue();
			newTheme.id = 'theme';

			headEl = theme.parentNode;
			headEl.removeChild(theme);
			headEl.appendChild(newTheme);
		}
		else {
			theme.href = theme.href.replace(/[^\/]*$/, this.getValue());
		}
	}, ctheme);

	// donate
	var panel8 = acc.add(new Ext.InfoPanel('panel-8', {
		icon: '/img/silk/icons/money.png'
	}));
	// }}}
	// {{{
	// restore dock state
	acc.restoreState();

	// update state of global toolbar buttons
	acc.toolbar.items.get('btn-independent').toggle(acc.independent);	
	acc.toolbar.items.get('btn-undockable').toggle(acc.undockable);	
	acc.toolbar.items.get('btn-shadow').toggle(acc.useShadow);

	// get last selected tab
	var tabId = Ext.state.Manager.get("tab");

	// event handler that saves currently selected tab
	var center = layout.getRegion('center');
	center.on('panelactivated', function(region, panel) {
		var tabId = panel.el.id;
		Ext.state.Manager.set("tab", tabId);
	});
	// }}}
	// {{{
	// create fixed height accordion
	var acc2 = new Ext.Accordion('acc2-body', {
		body: 'acc2-body'
		, boxWrap: true
		, wrapEl: 'acc2-wrap'
		, fitContainer: true
		, fitToFrame: true
		, fitHeight: true
		, initialHeight: 240
		, desktop: 'fixed-height'
	});
	// }}}
	// {{{
	// add panels
	acc2.add(new Ext.InfoPanel('panel2-1', {
		icon: '/img/silk/icons/calendar_view_month.png'
	}));

	acc2.add(new Ext.InfoPanel('panel2-2', {
		icon: '/img/silk/icons/database_table.png'
	}));

	acc2.add(new Ext.InfoPanel('panel2-3', {
		icon: '/img/silk/icons/cart.png'
	}));

	acc2.add(new Ext.InfoPanel('panel2-4', {
		icon: '/img/silk/icons/email.png'
	}));

	acc2.add(new Ext.InfoPanel('panel2-5', {
		icon: '/img/silk/icons/feed.png'
	}));
	// }}}
	// {{{
	// add panels to layout
	layout.beginUpdate();

	// page header (north)
	layout.add('north', new Ext.ContentPanel('north', {}));

	// accordion in west
	layout.add('west', acc);

	// center - Important info
	layout.add('center', new Ext.ContentPanel('important-info', {
		title:"Important Information"
		, fitContainer:true
		, fitToFrame: true
		, autoScroll: true
	}));

	// center - How to
	layout.add('center', new Ext.ContentPanel('howto', {
		title: "How to"
		, autoScroll: true
		, fitContainer: true
		, fitToFrame:true
	}));

	// center - Accordions
	layout.add('center', new Ext.ContentPanel('fixed-height', {
		title: 'Accordions'
		, fitToFrame:true
		, fitContainer:true
		, autoScroll: true
	}));

	// center - Panels
	var panelsTab = new Ext.ContentPanel('panels-tab', {
		title: 'Panels'
		, fitToFrame:true
		, fitContainer:true
		, autoScroll: true
	});
	layout.add('center', panelsTab);

	// {{{
	var url;
	// application code panel
	url = window.location.protocol + '//';
	url += window.location.host;
	url += window.location.pathname.replace(/accordion.html/, 'app-code.php');
	layout.add('center', new Ext.ContentPanel('app-code', {
		title: "Example code"
		, autoScroll: true
		, fitToFrame: true
		, fitContainer: true
		, background: true
		, url: url
		, loadOnce: true
	}));
	// }}}
	// {{{
	// infoPanel code panel
	url = window.location.protocol + '//';
	url += window.location.host;
	url += window.location.pathname.replace(/accordion.html/, 'panel-code.php');
	layout.add('center', new Ext.ContentPanel('panel-code', {
		title: "Ext.InfoPanel code"
		, autoScroll: true
		, fitToFrame: true
		, fitContainer: true
		, background: true
		, url: url
		, loadOnce: true
	}));
	// }}}
	// {{{
	// accordion code panel
	url = window.location.protocol + '//';
	url += window.location.host;
	url += window.location.pathname.replace(/accordion.html/, 'acc-code.php');
	layout.add('center', new Ext.ContentPanel('acc-code', {
		title: "Ext.Accordion code"
		, autoScroll: true
		, fitToFrame: true
		, fitContainer: true
		, background: true
		, url: url
		, loadOnce: true
	}));
	// }}}

	// south
	layout.add('south', new Ext.ContentPanel('south', "South"));

	layout.getRegion('center').showPanel(tabId || 'important-info');
	layout.restoreState();
	layout.endUpdate();

	// {{{
	// code loading masks
	var dummy;
	Ext.fly('app-code').fitToParent();
	dummy = new Ext.LoadMask('app-code', {
		msg: 'Loading example application code...'
	});

	Ext.fly('acc-code').fitToParent();
	dummy = new Ext.LoadMask('acc-code', {
		msg: 'Loading Ext.Accordion code...'
	});

	Ext.fly('panel-code').fitToParent();
	dummy = new Ext.LoadMask('panel-code', {
		msg: 'Loading Ext.InfoPanel code...'
	});
	// }}}
	// }}}
	// {{{
	// resizing of fixed height accordion
	var acc2Ct = Ext.get('acc2-ct');
	var resizer = new Ext.Resizable(acc2Ct, {
		handles:'s e se'
		, transparent: true
		, minHeight: 244
		, minWidth: 224
		, pinned: true
	});
	resizer.on({
		beforeresize: {
			scope:acc2
			, fn: function(r, e) {

				// save old sizes
				r.oldSize = acc2Ct.getSize();
				r.oldAccSize = this.body.getSize();
		}}
		, resize: {
			scope:acc2
			, fn: function(r, w, h, e) {

				// calculate deltas
				var dw, dh;
				dw = w - r.oldSize.width;
				dh = h - r.oldSize.height;

				// resize Accordion 
				this.setSize(r.oldAccSize.width + dw, r.oldAccSize.height + dh);

		}}
	});
	// }}}

	// independent panels example
	var ipanel1 = new Ext.InfoPanel('ipanel-1', {
		collapsed: false
	});
	var ipanel2 = new Ext.InfoPanel('ipanel-2', {
		animate: false
	});
	var ipanel3 = new Ext.InfoPanel('ipanel-3', {
		trigger: 'button'
	});
	var ipanel4 = new Ext.InfoPanel('ipanel-4', {
		title:'4. Container from markup'
		, content: 
			'<div class="text-content">'
			+ '<h3>Container from markup, body from code</h3>'
//			+ '<p>&nbsp;</p>'
			+ '<p>Markup:<p>'
			+ '<pre class="code">'
			+ '&lt;div id="ipanel-4"&gt;&lt/div&gt;'
			+ '</pre>'
			+ '<p>Code:<p>'
			+ '<pre class="code">'
			+ 'new Ext.InfoPanel(\'ipanel-4\', {\n'
			+ '  title:\'4. Container from...\'\n'
			+ '  , content:\'This text.\'\n'
			+ '  , useShadow:true\n'
			+ '  , easingCollapse: \'backIn\'\n'
			+ '  , easingExpand: \'backOut\'\n'
			+ '});'
			+ '</pre>'
			+ '</div>'
		, useShadow: true
		, easingCollapse: 'backIn'
		, easingExpand: 'backOut'
	});

	var ipanel5 = new Ext.InfoPanel('ipanel-5', {
		useShadow: true
		, draggable: true
		, desktop:'panels-tab'
		, duration: 1.0
	});
	panelsTab.on('resize', ipanel5.moveToViewport, ipanel5);

	var ipanel6 = new Ext.InfoPanel({
		title: '6. Auto-created panel, no markup'
		, id:'ipanel-6'
		, desktop: 'panels-tab'
		, draggable: true
		, useShadow: true
		, autoCreate: {
			tag:'div'
			, children:[{
				tag:'div'
				, cls:'text-content'
				, html: '<h3>No html markup, autoCreate object.</h3>'
				+ '<p>&nbsp;</p>'
				+ '<p>Code:</p>'
				+ '<pre class="code">'
				+ 'new Ext.InfoPanel({\n'
				+ '    title: \'6. Auto-created...\'\n'
				+ '  , id: \'ipanel-6\'\n'
				+ '  , desktop: \'panels-tab\'\n'
				+ '  , draggable: true\n'
				+ '  , useShadow: true\n'
				+ '  , autoCreate: {\n'
				+ '      tag: \'div\'\n'
				+ '    , children:[{\n'
				+ '        tag: \'div\'\n'
				+ '      , cls: \'text-content\'\n'
				+ '      , html: \'This text.\'\n'
				+ '    }]\n'
				+ '  }\n'
				+ '});'
				+ '</pre>'
			}]
		}
	});
	panelsTab.on('resize', ipanel6.moveToViewport, ipanel6);

	var ipanel7 = new Ext.InfoPanel({
		title: '7. Auto-created, body from markup'
		, id: 'ipanel-7'
		, desktop: 'panels-tab'
		, bodyEl: 'ipanel-7-body'
		, autoCreate: true
		, draggable: true
		, useShadow: true
		, resizable: true
	});
	panelsTab.on('resize', ipanel7.moveToViewport, ipanel7);

	// restore state of fixed height accordion
	acc2.restoreState();
	acc.constrainToDesktop();
	acc2.constrainToDesktop();

	// {{{
	// searching within panel bodies example
	var find = acc.toolbar.items.get('find-field');
	Ext.fly(find.el).on('keyup', searchPanels, acc, {buffer:150});

	function searchPanels(e) {

		var re, found;
		// ignore special and navigation keys
		if(e.isSpecialKey() || e.isNavKeyPress()) {
			return;
		}

		var val = find.el.value;
		// ignore if length is 1 or 2
		if(val.length < 3 && val.length > 0) {
			return;
		}
		
		// show all panels collapsed when filter is cleared
		else if(0 === val.length) {
			this.showAll();
			this.collapseAll();
		}

		// find panels containing the entered text
		else {
			re = new RegExp('.*' + val + '.*', 'i');
			found = false;
			this.hideAll();
			this.items.each(function(panel) {
				if((found && !this.independent) || !panel.docked) {
					return;
				}
				if(panel.body.dom.innerHTML.match(re)) {
					panel.show();
					panel.expand();
					found = true;
				}
				else {
					panel.collapse();
					panel.hide();
					found = false;
				}
			}, this);
		}
	}
	// }}}

	// Accordion in dialog code
	var accDlgShow = function(btn, e) {

		var dpanel4, stickyNote;

		// {{{
		// lazy create the dialog
		if(!this.dlg) {

			// create the BasicDialog
			this.dlg = new Ext.BasicDialog('acc-dialog', {
				width: 220
				, height: 220
				, x: 620
				, y: 144
				, modal: false
				, shadow: true
				, proxyDrag: true
			});

			// add hide on escape pressed handler
			this.dlg.addKeyListener(27, this.dlg.hide, this.dlg);

			// create the Accordion
			this.acc = new Ext.Accordion(this.dlg.body, {
				fitHeight: true
				, fitToFrame: true
				, fitContainer: true
				, desktop: 'fixed-height'
			});

			// add panels
			this.acc.add(new Ext.InfoPanel('dpanel-1', {
				icon: '/img/silk/icons/application_home.png'
			}));

			this.acc.add(new Ext.InfoPanel('dpanel-2', {
				icon: '/img/silk/icons/emoticon_happy.png'
			}));

			this.acc.add(new Ext.InfoPanel('dpanel-3', {
				icon: '/img/silk/icons/mouse.png'
			}));

//			dpanel4 = new Ext.InfoPanel('dpanel-4', {
//				icon: '/img/silk/icons/note.png'
//				, autoScroll: Ext.isGecko
//			});

			// get reference to sticky note textarea
//			stickyNote = Ext.get('sticky-note');
//			dpanel4.on({
//				beforeexpand: {
//					scope: stickyNote
//					, fn: function() {
//						this.setStyle('position','');
//					}
//				}
//				, beforecollapse: {
//					scope: stickyNote
//					, fn: function() {
//						this.setStyle('position','');
//					}
//				}
//				, animationcompleted: {
//					scope: stickyNote
//					, fn: function(panel) {
//						if(!panel.collapsed) {
//							var box = this.getBox();
//							this.setStyle('position','fixed');
//							this.setBox(box);
//					}}
//				}
//			});
//			stickyNote.on({
//				focus:{
//					scope:stickyNote
//					, fn: function() {
//						this.setStyle('position','fixed');
//					}
//				}
//				, blur:{
//					scope:stickyNote
//					, fn: function() {
//						this.setStyle('position','absolute');
//					}
//				}
//			})

//			dpanel4.fitTaToBody = function() {
//				var w = this.body.getWidth() - this.body.getFrameWidth('lr');
//				var h = this.body.getHeight() - this.body.getFrameWidth('tb');
//				stickyNote.setSize(w, h);
////				this.body.setStyle('overflow', Ext.isGecko ? 'auto' : 'hidden');
//			};

//			// sticky note resizing stuff
//			dpanel4.on('resize', function(panel, w, h) {
//				this.fitTaToBody();
//			}, dpanel4);
//			dpanel4.on('expand', function() {
//				this.fitTaToBody();
//			}, dpanel4);
//			this.acc.on('panelundock', function(panel) {
//				if(panel === dpanel4) {
//					dpanel4.fitTaToBody();
//				}
//			});
//			this.acc.on('paneldock', function(panel) {
//				if(panel === dpanel4) {
//					dpanel4.fitTaToBody();
//				}
//			});
//
//			this.acc.add(dpanel4);

			// inform accordion of dialog resize
			this.dlg.on('resize', function(dlg, w, h) {
				this.setSize(dlg.body.getWidth(), dlg.body.getHeight());
			}, this.acc);

			// update text of show/hide button
			this.dlg.on('show', function() {
				btn.setText('Hide Accordion Dialog');
				this.setPanelHeight();

				// fix the firefox cursor bug
//				var dlgCt;
//				if(Ext.isGecko) {
//					dlgCt = Ext.get('acc-dialog');
//					dlgCt.setStyle('overflow','');
//					dlgCt.setStyle.defer(10, dlgCt, ['overflow','auto']);
//				}

			}, this.acc);
			this.dlg.on('hide', function() {btn.setText('Show Accordion Dialog');});

//			this.acc.restoreState();
//			if(!dpanel4.collapsed) {
//				stickyNote.fitToParent();
//			}

		} // end of dlg lazy creation
		// }}}

		// show/hide dialog on button click
		if(this.dlg.isVisible()) {
			this.dlg.hide(btn.el);
		}
		else {
			this.dlg.show(btn.el);
		}
	}; // end of function accDlgShow

	// create show/hide dialog button
	var btnDlg = new Ext.Button('btn-show-dlg', {
		icon: '/img/silk/icons/application.png'
		, cls: 'x-btn-text-icon'
		, text: 'Show Accordion Dialog'
		, scope: accDlgShow
		, handler: accDlgShow
	});

	// remove the loading mask
	unmask.defer(100);

}); // end of onReady

// end of file
