/**
 * @author Willy
 */
Ext.BLANK_IMAGE_URL = "lib/ext/resources/images/default/s.gif";

App = function() {
	var layout;
	var conf = { IsOffline: true };
	var north, east, south, west, westcenter, center;
	return {
		// namespace for classes
		cls: {}
		// default user object
		, User: {}
		, query: null
		, searchMenu: null
		, profileMenu: null
		, loginButton: null

		, util: {
	        ensureBoolean: function(v){
	            return (v === true || v === 1 || v === '1' || v === 'true');
    	    }
		}
		, isReady: function() {
			return App.User.isReady && App.Basket.isReady;
		}

		, getLayout: function() {
			return layout;
		}

		, init: function() {
			function filterTree(value) {
				switch (value.length) {
				case 0:
				case 1:
					break;
				default:
					App.Categories.loadFilterList(f.getValue());
					break;
				}
				return true;
			}
			
			var tb = new Ext.Toolbar('cat-tb'), b, c, f;
			tb.add(new Ext.Toolbar.TextItem('Filter:'));
			tb.addField(f = new Ext.form.TextField({
				autoCreate: true
				, id: 'cat-filter'
				, qtip: 'mindestens 2 Zeichen'
				, size: 20
				, selectOnFocus: true
				, validator: filterTree
				, validateOnBlur: false
			}));
			f.el.on('keyup', function(e) { // setup an onkeyup event handler
				if((e.getKey() == e.BACKSPACE || e.getKey() == e.DELETE) && this.getValue().length == 0)
					App.Categories.reload();
			});
			
			tb.add(c = new Ext.Toolbar.Button({
				cls: 'x-btn-icon'
				, icon: '/lib/images/cross.png'
				, tooltip: 'Filterung deaktivieren'
				, handler: function() { f.reset(); App.Categories.reload(); }
			}));
			
			layout = new Ext.BorderLayout(document.body,{
				 north: { split: false }
				, south: { split: false }
				, west: {
					title: 'Warengruppen'
					, split: true
					, minSize: 200
					, maxSize: 400
					, titlebar: true
					, toolbar: tb
					, autoScroll:true
					, initialSize: 300
					, collapsible: true
				}
				, center: {
					autoScroll: true,
					autoTabs: false,
					hideTabs: true
				}
			});

			layout.beginUpdate();
				layout.add('north', App.north = new Ext.ContentPanel('north'));
				layout.add('south', App.south = new Ext.ContentPanel('south'));
				layout.add('west', App.west = new Ext.ContentPanel('west'));
				layout.add('center', App.center = new Ext.ContentPanel ('center'));
			layout.endUpdate();
			App.Toolbar.create();
			App.User.on('login', this.home, this);
			App.User.on('logout', this.home, this);
		}

		, home: function() {
			var l = this.getLayout(), c = l.getRegion('center');
			if (! this.homePanel) {
				l.beginUpdate();
					this.homePanel = c.add(new Ext.ContentPanel('home-panel', { autoCreate: true, preservePanel: true, fitToFrame:true, closable:false, autoScroll: true }, '<div id="fa"><div id="fa-hd"></div><div id="fa-ct"></div><div id="fa-ft">&#160;</div></div>'));
				l.endUpdate();
				this.buildStartPage();
			}
			l.showPanel(this.homePanel);
		}
		
		, getTemplate: function() {
			return '<div class="x-box" style="margin:0 0 10px 10px; width:200px;">' +
					'<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">' +
					'<div class="hd"><h3>{Name}</h3></div>' +
					'<div class="ct"><img src="getImage.php?filename={Filename}" alt="" height="125" width="125" border="0" ext:qtip="{Description}" /></div>' +
					'<div class="ft">' +
					'<div>Artikelnummer: {CatalogueId}</div>' +
					'{dis}<div>statt {Netto} € nur <span>{DiscountPrice} €</span></div>{edis}' +
					'{nodis}<div>{DiscountString}</div>{enodis}' +
					'</div>' +
					'</div></div></div>' +
					'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' +
					'</div>';
		}
		
		, buildStartPage: function() {
			this.Template = new Ext.Template(this.getTemplate());
			this.Template.soldOut = function(value) { return value ? 'sold-out' : ''; };
			this.Template.compile();
			this.view = new Ext.JsonView("fa-ct", this.Template, {
				jsonRoot: 'articles',
				emptyText: '<h3>Keine aktuellen Fokus-Artikel.'
			});
			this.view.on('load', function(view, data, response) {
				var r = Ext.decode(response.responseText);
				if (r.success) {
					Ext.fly('fa-hd').update('<div>Unsere Fokusartikel vom ' + r.data.DateStart + ' bis ' + r.data.DateEnd + '</div><h4>Sehr geehrte Damen und Herren,</h4>' + r.data.HeaderText);
					for (var i = 0, len = view.jsonData.length; i < len; i++) {
						if (view.jsonData[i].IsSoldOut != '0')
							Ext.DomHelper.append(view.getNode(i), { tag: 'div', cls: 'sold-out' });
					};
					// Ext.fly('fa-ft').update('<h4>' + r.data.FooterText + '</h4>');
					Ext.fly('fa-ft').update('<div style="background-color:#E53534;"><h4>' + r.data.FooterText + '</h4></div>');
				}
			}, this);
			function createDiscountString(rec){
				switch (true){
					case rec.IsDiscountVisible == '1' && rec.IsDiscountValueVisible == '1': 
						rec.DiscountString = 'Sie sparen ' + rec.Discount + '% (' + rec.DiscountValue + ' €)';
						break;
					case rec.IsDiscountVisible == '1':
						rec.DiscountString = 'Sie sparen ' + rec.Discount + '%';
						break;
					case rec.IsDiscountValueVisible == '1':
						rec.DiscountString = 'Sie sparen ' + rec.DiscountValue + ' €';
						break;
					default:
						rec.dis = '<div>Aktuell f&uuml;r <span>' + rec.DiscountPrice + ' €</span></div><!--';
						rec.edis = '-->';
						break;
				}
			}
			this.view.on('beforerender', function(view, data) {
				Ext.each(data, createDiscountString);
			});
			this.view.on('click', function(view, index, node, event) {
				var data = view.jsonData[index];
				if(data.IsSoldOut == '0') {
					App.ArticleView.show(data.Id);
				}
			});
			this.view.on('loadexception', function() { alert('OnLoadException'); }, this.view);
			this.view.on('contextmenu', function(o, i, n, e) { e.stopEvent(); }, this.view);
			this.view.load({ method: 'POST', url: 'shop.php', params: { realm: 'Article', action: 'getFocusArticles' } });
		}

		, showStartupDialog: function() {
			this.startupDialog = new Ext.BasicDialog('startup-dialog', {
				animateTarget: 'logo'
				, width: 420
				, height: 230
				, collapsible: false
				, closable: false
				, autoScroll: false
				, resizable: false
				, modal: true
				, proxyDrag: true
				, shadow: true
				, syncHeightBeforeShow: true
				, buttonAlign: 'center'
			});
			this.startupDialog.addKeyListener(Ext.EventObject.ESC, this.run, this); // ESC can also close the dialog
			this.startupDialog.addKeyListener(Ext.EventObject.ENTER, this.run, this); // ESC can also close the dialog
			this.startupDialog.addButton('Shop starten', this.run, this);    // Could call a save function instead of hiding
			this.startupDialog.show('logo');
		}
	};
}();

Ext.onReady(App.init, App, true);

App.conf = {
	itemsPerPage: 25
}

App.templates = {
	getFormHtml: function() {
		return '' +
'<div style="margin:10px auto; width:640px;">' +
'	<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 style="margin-bottom:5px;" id="form-heading"></h3>' +
'			<div id="form-body"></div>' +
'			<div id="form-foot"></div>' +
'	</div></div></div>' +
'	<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' +
'</div>';
	}

	, getFormTemplate: function() {
		var t = new Ext.Template('' +
'<div style="margin:10px auto; width:640px;">' +
'	<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 style="margin-bottom:5px;" id="{formTitleId}">{formTitle}</h3>' +
'			<div id="{formHeadId}">{formHead}</div>' +
'			<div id="{formBodyId}">{formBody}</div>' +
'			<div id="{formFootId}">{formFoot}</div>' +
'	</div></div></div>' +
'	<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' +
'</div>');
		return t.compile();
	}
}



function formatBoolean(value){
	return value ? 'ja' : 'nein';
};

function formatDate(value){
	return value ? value.dateFormat('M d, Y') : '';
};

// plug German currency renderer into formatter
Ext.util.Format.deMoney = function(v)
{
	if (! v) return '&mdash;';
	v = (Math.round((v-0)*100))/100;
	v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
	return (v + ' €').replace(/\./, ',');
};

Ext.util.Format.deDate = function(v){
	return v ? v.dateFormat('d.m.Y') : '';
};

Ext.util.Format.deMoneyEmpty = function(v)
{
	if (! v) return '';
	v = (Math.round((v-0)*100))/100;
	v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
	return (v + ' €').replace(/\./, ',');
};

Ext.util.Format.deBoolean = function(value){
	return value ? 'ja' : 'nein';
};

Ext.util.Format.ellipsis = function(value, len) {
	if(value && value.length > len) {
		return '<span title="' + value + '">' + value.substr(0, len-3) + '...</span>';
	}
	return value;
};

Ext.util.Format.percent = function(value) {
	return (value) ? (Math.floor(parseFloat(value) * 100)) + ' %' : '';
};

Ext.util.Format.nl2br = function(value) {
	var v = value.replace(/(\n|\r\n)/g, '<br />');
	return v;
};

Ext.onReady(function() { Ext.QuickTips.init({ interceptTitles: true, showDelay: 200 }); });

