var tokenDelimiter = ':';

Ext.BLANK_IMAGE_URL = '../js/ext-js/resources/images/default/s.gif';

Ext.onReady(function() {
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Ext.getBody().on("contextmenu", Ext.emptyFn, null, {preventDefault: true});

	Ext.History.on({
		'change'	: historyChange
	});

	Ext.QuickTips.init();
	Ext.History.init(function (history) {
		historyChange(location.hash.substring(1));
	});
});

Ext.apply(Ext.form.VTypes, {
	protocolComment	:  function(v) {
		return /^[a-zA-Z0-9_ ]*$/.test(v);
	},
	protocolCommentText	: 'Es sind nur Buchstaben, Zahlen und _ erlaubt. (Keine Umlaute o.ä.)',
    protocolCommentMask	: /[a-z0-9_ ]/i
});

Ext.getUrlParam = function(param) {
   var params = Ext.urlDecode(location.search.substring(1));
   return param ? params[param] : params;
};

function historyChange(token) {
	if (token) {
		var parts = token.split(tokenDelimiter);
		var menu = parts[0];
		// abort transaction (if any)
		Ext.get('content').getUpdater().abort();
		switch (menu) {
			//Navigation oben
			case "home"				: loadContent('news', 'home', false, null); break;
			case "vorstand"			: loadContent('vorstandPrim', 'vorstand', false, null); break;
			case "vorstand-erw"		: loadContent('vorstandSek', 'vorstand-erw', false, null); break;
			case "geschaeftsstelle"	: loadContent('geschaeftsstelle', 'geschaeftsstelle', true, null); break;
			case "termine"			: loadContent('termine', 'termine', true, null); break;
			case "trainer"			: {
				if (!parts[1]) {
					loadContent('trainer', 'trainer', true, null);
				} else {
					loadContent('user', 'trainer:' + parts[1], false, {user: parts[1], isTrainer: true});
				}
				break;
			}
			//Navigation links
			case "jugend"			: loadContent('jugend', 'jugend', true, null); break;
			case "mannschaften"		: {
				if (!parts[1]) {
					loadContent('mannschaften', 'mannschaften', true, null);
				} else {
					loadContent('mannschaften', 'mannschaften:' + parts[1], true, {season: parts[1]});
				}
				break;
			}
			case "mannschaft"		: {
				if (!parts[1]) {
					loadContent('news', 'home', false, null); break;
				} else {
					loadContent('mannschaft', 'mannschaft:' + parts[1], true, {team: parts[1]});
				}
				break;
			}
			case "anlage"			: loadContent('anlage', 'anlage', true, null); break;
			case "platzwart"		: loadContent('platzwart', 'platzwart', true, null); break;
			case "platzbelegung"	: loadContent('platzbelegung', 'platzbelegung', true, null); break;
			case "punktspiele"		: {
				if (!parts[1]) {
					loadContent('punktspiele', 'punktspiele', true, null);
				} else if (!parts[2]) {
					loadContent('punktspiele', 'punktspiele:' + parts[1], true, {season: parts[1]});
				} else {
					loadContent('punktspiele', 'punktspiele:' + parts[1] + ':' + parts[2], true, {season: parts[1], association: parts[2]});
				}
				break;
			}
			case "geschichte"		: {
				if (!parts[1]) {
					loadContent('geschichte', 'geschichte', true, null);
				} else {
					loadContent('geschichte', 'geschichte:' + parts[1], true, {page: parts[1]});
				}
				break;
			}
			case "spielerboerse"	: loadContent('spielerboerse', 'spielerboerse', false, null); break;
			//Navigation rechts
			case "bilder"			: loadContent('bilder', 'bilder', false, null); break;
			case "traglufthalle"	: loadContent('traglufthalle', 'traglufthalle', true, null); break;
			case "sponsoren"		: loadContent('sponsoren', 'sponsoren', true, null); break;
			//case "presse"			: loadContent('presse', 'presse', true, null); break;
			case "gastronomie"		: {
				if (!parts[1]) {
					loadContent('gastronomie', 'gastronomie', true, null); break;
				} else {
					loadContent('gastronomie', 'gastronomie:' + parts[1], true, {page: parts[1]});
				}
				break;
			}
			case "downloads"		: loadContent('downloads', 'downloads', true, null); break;
			case "beitragsordnung"	: loadContent('beitragsordnung', 'beitragsordnung', true, null); break;
			case "impressum"		: loadContent('impressum', 'impressum', true, null); break;
			//ohne Navigation
			case "user"				: loadContent('user', 'user', false, null); break;
			//Navigation intern
			case "protokolle"		: loadContent('protokolle', 'protokolle', false, null); break;
			//Specials
			case "potsdamopen2010"	: loadContent('potsdamopen2010', 'potsdamopen2010', true, null); break;
			default					: loadContent('news', null, false, null); break;
		}
	} else {
		loadContent('news', null, false, null);
	}
}

function formatTelFax(telFax) {
	if (telFax.length > 0 && telFax.indexOf("/") != -1) {
		var tmp = telFax.split("/");
		var tel_main = "";
		for (i = tmp[1].length - 1; i > 0; i -= 2) {
			//tel_main = tmp[1][i-1] + "" + tmp[1][i] + " " + tel_main;
			tel_main = tmp[1].charAt(i-1).concat(tmp[1].charAt(i)).concat(" ").concat(tel_main);
		}
		if (i == 0) {
			//tel_main = tmp[1][0] + " " + tel_main;
			tel_main = tmp[1].charAt(0).concat(" ").concat(tel_main);
		}
		var tel_vor = "";
		for (i = tmp[0].length - 1; i > 0; i -= 2) {
			//tel_vor = tmp[0][i-1] + tmp[0][i] + " " + tel_vor;
			tel_vor = tmp[0].charAt(i-1).concat(tmp[0].charAt(i)).concat(" ").concat(tel_vor);
		}
		if (i == 0) {
			tel_vor = tmp[0].charAt(0).concat(" ").concat(tel_vor);
		}
		return tel_vor.concat(" / ").concat(tel_main);
	} else {
		return "";
	}
}

function startLightBox(id, dir, startNr, doSlideShow) {
	ImageAction.getAllImages(dir, function(result, e) {
		Ext.each(result, function(image, i) {
			var spec = {
				tag		: 'a',
				id		: 'image_' + dir + '_' + i,
				href	: image.src,
				rel		: dir
			};
			if (!Ext.get(spec.id))
				Ext.DomHelper.append('hiddenLightbox', spec);
		});
		if (result && result.length > 0) {
			Ext.ux.Lightbox.open(Ext.getDom('image_' + dir + '_' + startNr), 'a[rel^=' + dir + ']', true);
			if (!doSlideShow) {
				Ext.ux.Lightbox.stopSlideShow();
			}
		}
	});
}

function doDefaultLogin() {
	doLogin('news', 'home', false, null);
}

function doLogin(content, historyToken, isJsp, params) {
	Ext.get('hiddenLogin').load({
		url			: 'auth/authProcess.jsp',
		nocache		: true,
		scripts		: false,
		text		: 'Lade Login...',
		callback	: function (element, success, response) {
			if (success) {
				loadContent(content, historyToken, isJsp, params);
				Ext.get('navi-right').load({
					url		: 'navi/right.jsp',
					nocache	: true,
					text	: 'Lade Navigation...'
				});
				Ext.get('navi-left').load({
					url		: 'navi/left.jsp',
					nocache	: true,
					text	: 'Lade Navigation...'
				});
				updateLastLogin();
				checkDefaultPassword();	
			}
		}
	});
}

function doLogout() {
	Ext.get('hiddenLogin').load({
		url			: 'auth/authLogout.jsp',
		nocache		: true,
		scripts		: false,
		text		: 'Lade Logout...',
		callback	: function (element, success, response) {
			if (success) {
				loadContent('news', 'home', false, null);
				Ext.get('navi-right').load({
					url		: 'navi/right.jsp',
					nocache	: true,
					text	: 'Lade Navigation...'
				});
				Ext.get('navi-left').load({
					url		: 'navi/left.jsp',
					nocache	: true,
					text	: 'Lade Navigation...'
				});
			}
		}
	});
}

/**
 * checks if user has his default password (password equals login), 
 * and displays password change request
 */
function checkDefaultPassword() {
	UserAction.hasDefaultPassword(function(result, e) {
		if (e.status && result) {
			showChangePasswordDialog();
		}
	});
}

/**
 * Updates the timestamp of the users lastlogin
 */
function updateLastLogin() {
	UserAction.updateLastLogin();
}

/**
 * Displayes a prompt to change the users password
 */
function showChangePasswordDialog() {
	Ext.Msg.prompt("Passwort ändern", "Bitte geben Sie ein neues Passwort ein.", 
		function(btnId, text) {
			if (btnId == "ok") {
				UserAction.changePassword(text, function(result, e) {
					if (e.status && result) {
						Ext.Msg.alert("Passwort geändert", "Ihr Passwort wurde erfolgreich geändert.");
					} else {
						Ext.Msg.alert("Fehler!", "Ihr Passwort konnte nicht geändert werden.");
					}
				});
			}
		}
	);
}

function loadContent(content, historyToken, isJsp, params) {
	//Ext.History.suspendEvents(false);
	if (!isJsp) {
		Ext.ensure({
			js			: ['js/modules/normal/' + content + '.js'],
			callback	: function() {
				try {
					var contentEl = Ext.get("content").dom; 
					contentEl.innerHtml = "";
					while (contentEl.firstChild) {
						contentEl.removeChild(contentEl.firstChild);
					}
					if (params) {
						eval(content + "_build(" + Ext.encode(params) + ");");
					} else {
						eval(content + "_build();");
					}
				} catch (e) {
					Ext.get('content').load({
						url	: 'content/error/404.htm'
					});
				} finally {
					//Ext.History.resumeEvents();
					updateStatistics(content);
				}
			}
		});
	} else {
		Ext.get('content').load({
			url		: 'content/' + content + '.jsp',
			params	: params,
			nocache	: true,
			scripts	: true,
			text	: 'Lade ' + content + "...",
			callback	: function (el, success, response, options) {
				if (!success) {
					Ext.get('content').load({
						url	: 'content/error/404.htm'
					});
				}
				//Ext.History.resumeEvents();
				updateStatistics(content);
			}
		});
	}

	if (historyToken) {
		Ext.History.add(historyToken);
	}
}

function updateStatistics(content) {
	try {
		var pageTracker = _gat._getTracker("UA-12725642-1");
		pageTracker._setDomainName(".potsdamer-tc.de");
		pageTracker._trackPageview(location.pathname + content);
	} catch(err) {}
}


function showSchleifchenTurnier2010() {
	var womenData = [
		[1, 'Edit', 'Schneider', 7, 5, 17, 30, 13],
		[2, 'Christa', 'Helmke', 7, 5, 12, 27, 15],
		[3, 'Sabine', 'Klawes', 7, 4, 8, 27, 19],
		[4, 'Birgit' , 'Winkler', 6, 4, 7, 23, 16],
		[5, 'Antje', 'Reelitz', 7, 4, -2, 22, 24],
		[6, 'Jennifer', 'Klawes', 6, 3, 0, 19, 19],
		[7, 'Katharina', 'Schmalenbach', 6, 3, -2, 16, 18],
		[8, 'Christa', 'Krick', 7, 3, -5, 19, 24],
		[9, 'Monika', 'Schulte-Loh', 6, 2, 0, 19, 19],
		[10, 'Claude', 'Dietze', 6, 2, -12, 11, 23],
		[11, 'Martina', 'Miethke', 7, 1, -23, 12, 35]
	];
	
	var menData = [
		[1, 'Christian', 'Haab', 7, 7, 23, 34, 11],
		[2, 'Dennis' , 'Klawes', 7, 6, 25, 37, 12],
		[3, 'Peter', 'Konrad', 6, 5, 15, 24, 9],
		[4, 'Rainer', 'Klawes', 7, 5, 10, 28, 18],
		[4, 'Henning', 'Metzner', 7, 5, 10, 28, 18],
		[6, 'Wolfgang', 'Puschmann', 7, 5, 4, 23, 19],
		[7, 'Manfred', 'Petrzika', 7, 4, 1, 22, 21],
		[8, 'Ulrich', 'Schmalenbach', 7, 3, -3, 21, 24],
		[9, 'Christian', 'Groß', 7, 2, -4, 20, 24],
		[10, 'Bernhard', 'Meißer', 7, 2, -13, 16, 29],
		[11, 'Robert', 'Kornmesser', 7, 2, -17, 15, 32],
		[12, 'Reinhard', 'König', 6, 1, -14, 10, 24],
		[13, 'Heinz', 'Reelitz', 7, 1, -24, 8, 32],
		[14, 'Uwe', 'Hartmann', 7, 0, -13, 13, 26]
	];
	
	var womenStore = new Ext.data.ArrayStore({
	  fields: [
	    {name: 'Platzierung', type: 'int'},
	    {name: 'Vorname'},
	    {name: 'Nachname'},
	    {name: 'Matches', type: 'int'},
	    {name: 'Punkte', type: 'int'},
	    {name: 'Spieledifferenz', type: 'int'},
	    {name: 'gewonnen', type: 'int'},
	    {name: 'verloren', type: 'int'}
	  ]
	});
	
	var menStore = new Ext.data.ArrayStore({
	  fields: [
	    {name: 'Platzierung', type: 'int'},
	    {name: 'Vorname'},
	    {name: 'Nachname'},
	    {name: 'Matches', type: 'int'},
	    {name: 'Punkte', type: 'int'},
	    {name: 'Spieledifferenz', type: 'int'},
	    {name: 'gewonnen', type: 'int'},
	    {name: 'verloren', type: 'int'}
	  ]
	});
	
	womenStore.loadData(womenData);
	menStore.loadData(menData);
	
	var womenGrid = new Ext.grid.GridPanel({
	  store: womenStore,
	  columns: [
	    {id:'Platzierung',header: 'Platzierung', width: 70, sortable: true, dataIndex: 'Platzierung'},
	    {header: 'Vorname', width: 100, sortable: true, dataIndex: 'Vorname'},
	    {header: 'Nachname', width: 100, sortable: true, dataIndex: 'Nachname'},
	    {header: 'Matches', width: 50, sortable: true, dataIndex: 'Matches'},
	    {header: 'Punkte', width: 40, sortable: true, dataIndex: 'Punkte'},
	    {header: 'Spieledifferenz', width: 90, sortable: true, dataIndex: 'Spieledifferenz'},
	    {header: 'Spiele gewonnen', width: 100, sortable: true, dataIndex: 'gewonnen'},
	    {header: 'Spiele verloren', width: 100, sortable: true, dataIndex: 'verloren'}
	  ],
	  height: 280,
	  width: 660
	});
	
	var menGrid = new Ext.grid.GridPanel({
	  store: menStore,
	  columns: [
	    {id:'Platzierung',header: 'Platzierung', width: 70, sortable: true, dataIndex: 'Platzierung'},
	    {header: 'Vorname', width: 100, sortable: true, dataIndex: 'Vorname'},
	    {header: 'Nachname', width: 100, sortable: true, dataIndex: 'Nachname'},
	    {header: 'Matches', width: 50, sortable: true, dataIndex: 'Matches'},
	    {header: 'Punkte', width: 40, sortable: true, dataIndex: 'Punkte'},
	    {header: 'Spieledifferenz', width: 90, sortable: true, dataIndex: 'Spieledifferenz'},
	    {header: 'Spiele gewonnen', width: 100, sortable: true, dataIndex: 'gewonnen'},
	    {header: 'Spiele verloren', width: 100, sortable: true, dataIndex: 'verloren'}
	  ],
	  height: 340,
	  width: 660
	});

	new Ext.Window({width: 670, height: 660, items: [womenGrid, menGrid], title: 'Ergebnisse'}).show();
}
