var tokenDelimiter = ':';
var ContentTypes = {"js" : 0, "jsp" : 1, "htm" : 3};

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', ContentTypes.js, null); break;
			case "vorstand"			: loadContent('vorstandPrim', 'vorstand', ContentTypes.js, null); break;
			case "vorstand-erw"		: loadContent('vorstandSek', 'vorstand-erw', ContentTypes.js, null); break;
			case "geschaeftsstelle"	: loadContent('geschaeftsstelle', 'geschaeftsstelle', ContentTypes.htm, null); break;
			case "termine"			: loadContent('termine', 'termine', ContentTypes.htm, null); break;
			case "trainer"			: {
				if (!parts[1]) {
					loadContent('trainer', 'trainer', ContentTypes.htm, null);
				} else {
					loadContent('user', 'trainer:' + parts[1], ContentTypes.js, {user: parts[1], isTrainer: true});
				}
				break;
			}
			//Navigation links
			case "jugend"			: loadContent('jugend', 'jugend', ContentTypes.htm, null); break;
			case "mannschaften"		: {
				if (!parts[1]) {
					loadContent('mannschaften', 'mannschaften', ContentTypes.jsp, null);
				} else {
					loadContent('mannschaften', 'mannschaften:' + parts[1], ContentTypes.jsp, {season: parts[1]});
				}
				break;
			}
			case "mannschaft"		: {
				if (!parts[1] || !parts[2]) {
					loadContent('news', 'home', ContentTypes.js, null); break;
				} else {
					loadContent('mannschaft', 'mannschaft:' + parts[1] + ":" + parts[2], ContentTypes.jsp, {team: parts[1], season: parts[2]});
				}
				break;
			}
			case "anlage"			: loadContent('anlage', 'anlage', ContentTypes.htm, null); break;
			case "platzwart"		: loadContent('platzwart', 'platzwart', ContentTypes.htm, null); break;
			case "platzbelegung"	: loadContent('platzbelegung', 'platzbelegung', ContentTypes.htm, null); break;
			case "punktspiele"		: {
				if (!parts[1]) {
					loadContent('punktspiele', 'punktspiele', ContentTypes.jsp, null);
				} else if (!parts[2]) {
					loadContent('punktspiele', 'punktspiele:' + parts[1], ContentTypes.jsp, {season: parts[1]});
				} else {
					loadContent('punktspiele', 'punktspiele:' + parts[1] + ':' + parts[2], ContentTypes.jsp, {season: parts[1], association: parts[2]});
				}
				break;
			}
			case "geschichte"		: {
				if (!parts[1]) {
					loadContent('geschichte', 'geschichte', ContentTypes.jsp, null);
				} else {
					loadContent('geschichte', 'geschichte:' + parts[1], ContentTypes.jsp, {page: parts[1]});
				}
				break;
			}
			case "spielerboerse"	: loadContent('spielerboerse', 'spielerboerse', ContentTypes.js, null); break;
			//Navigation rechts
			case "bilder"			: loadContent('bilder', 'bilder', ContentTypes.js, null); break;
			case "traglufthalle"	: loadContent('traglufthalle', 'traglufthalle', ContentTypes.jsp, null); break;
			case "sponsoren"		: loadContent('sponsoren', 'sponsoren', ContentTypes.htm, null); break;
			//case "presse"			: loadContent('presse', 'presse', true, null); break;
			case "gastronomie"		: {
				if (!parts[1]) {
					loadContent('gastronomie', 'gastronomie', ContentTypes.jsp, null); break;
				} else {
					loadContent('gastronomie', 'gastronomie:' + parts[1], ContentTypes.jsp, {page: parts[1]});
				}
				break;
			}
			case "downloads"			: loadContent('downloads', 'downloads', ContentTypes.htm, null); break;
			case "beitragsordnung"		: loadContent('beitragsordnung', 'beitragsordnung', ContentTypes.htm, null); break;
			case "lobkritik"			: loadContent('lobkritik', 'lobkritik', ContentTypes.js, null); break;
			case "impressum"			: loadContent('impressum', 'impressum', ContentTypes.htm, null); break;
			//ohne Navigation
			case "user"					: loadContent('user', 'user', ContentTypes.js, null); break;
			case "newsletterAnmelden"	: verifyNewsletterSubscription(parts[1], parts[2]); break;
			case "newsletterAbmelden"	: unsubscribeNewsletter(parts[1], parts[2]); break;
			case "umfrageAustritt"		: {
				if (!parts[1]) {
					loadContent('news', 'home', ContentTypes.js, null); break;
				} else {
					loadContent('umfrageAustritt', 'umfrageAustritt:' + parts[1], ContentTypes.jsp, {email: parts[1]});
				}
				break;
			}
			//Navigation intern
			case "protokolle"			: loadContent('protokolle', 'protokolle', ContentTypes.js, null); break;
			case "newsletterIntern"		: loadContent('newsletterIntern', 'newsletterIntern', ContentTypes.js, null); break;
			//Specials
			case "potsdamopen2010"		: loadContent('potsdamopen2010', 'potsdamopen2010', ContentTypes.jsp, null); break;
			default						: loadContent('news', null, ContentTypes.js, null); break;
		}
	} else {
		loadContent('news', null, ContentTypes.js, null);
	}
}

function unsubscribeNewsletter(email, unsubscribeCode) {
	NewsletterAction.unsubscribeNewsletter(email, unsubscribeCode, function(result, e) {
		if (result) {
			Ext.Msg.show({
				title	: 'Newsletter abbestellen',
				msg		: 'Sie haben erfolgreich den Newsletter abbestellt und erhalten zukünftig keine E-Mails mehr von uns.',
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.INFO,
				fn		: function(buttonId, text, opt) {
					window.location.href = "http://www.potsdamer-tc.de";
				}
			});
		} else {
			Ext.Msg.show({
				title	: 'Newsletter abbestellen',
				msg		: "<b>Sie konnten leider nicht vom Newsletter abgemeldet werden.</b><br/>" +
							"Dies kann mehrere Ursachen haben:<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Sie sind nicht mehr am Newsletter angemeldet<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Sie haben nicht den Link im Newsletter verwendet um sich abzumelden<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Es trat ein interner Fehler auf",
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.ERROR,
				fn		: function(buttonId, text, opt) {
					window.location.href = "http://www.potsdamer-tc.de";
				}
			});
		}
	});
}

function subscribeNewsletter(email) {
	if (Ext.form.VTypes.email(email)) {
		NewsletterAction.subscribeNewsletter(email, function(result, e) {
			if (result) {
				Ext.Msg.show({
					title	: 'Newsletter erfolgreich bestellt',
					msg		: 'Folgen Sie bitte nun den Anweisungen in Ihrer Bestätigung-Email um den Vorgang abzuschließen.',
					buttons	: Ext.Msg.OK,
					icon	: Ext.MessageBox.INFO
				});
			} else {
				Ext.Msg.show({
					title	: 'Newsletter konnte nicht bestellt werden',
					msg		: "Sie konnten den Newsletter nicht bestellen.</b><br/>" +
						"Dies kann mehrere Ursachen haben:<br/>" +
						"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Sie sind bereits am Newsletter angemeldet<br/>" +
						"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Sie haben Ihre Bestätigung-Email bereits erhalten<br/>" +
						"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Es trat ein interner Fehler auf",
					buttons	: Ext.Msg.OK,
					icon	: Ext.MessageBox.ERROR
				});
			}
		});
	}
	return false;
}

function verifyNewsletterSubscription(email, subscribeCode) {
	NewsletterAction.verifyNewsletterSubscription(email, subscribeCode, function(result, e) {
		if (result) {
			Ext.Msg.show({
				title	: 'Newsletter erfolgreich bestellt',
				msg		: 'Sie haben erfolgreich unseren Newsletter bestellt und werden nun in unregelmäßigen Abständen über Neuigkeiten und Termine informiert.',
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.INFO,
				fn		: function(buttonId, text, opt) {
					window.location.href = "http://www.potsdamer-tc.de";
				}
			});
		} else {
			Ext.Msg.show({
				title	: 'Fehler!',
				msg		: "<b>Sie konnten leider nicht die Bestellung des Newsletter abschließen.</b><br/>" +
							"Dies kann mehrere Ursachen haben:<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Sie sind bereits am Newsletter angemeldet<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Ihr Bestätigungs-Link ist nicht mehr gültig<br/>" +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- Es trat ein interner Fehler auf",
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.ERROR,
				fn		: function(buttonId, text, opt) {
					window.location.href = "http://www.potsdamer-tc.de";
				}
			});
		}
	});
}

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].charAt(i-1).concat(tmp[1].charAt(i)).concat(" ").concat(tel_main);
		}
		if (i == 0) {
			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].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', ContentTypes.js, null);
}

function doLogin(content, historyToken, type, 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, type, 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', ContentTypes.js, 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, type, params) {
	switch(type) {
	case ContentTypes.js:
		loadJs(content, params);
		break;
	case ContentTypes.jsp:
		loadJsp(content, params);
		break;
	case ContentTypes.htm:
		loadHtml(content, params);
	}

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

function loadJs(content, params) {
	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) {
				if (console)
					console.log(e);
				Ext.get('content').load({
					url	: 'content/error/404.htm'
				});
			} finally {
				updateStatistics(content);
			}
		}
	});
}

function loadJsp(content, params) {
	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'
				});
			}
			updateStatistics(content);
		}
	});
}

function loadHtml(content, params) {
	Ext.get('content').load({
		url		: 'content/' + content + '.htm',
		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'
				});
			}
			updateStatistics(content);
		}
	});
}

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

function umfrageAustrittSubmit(form) {
	var email = form.email.value;
	var zeit = form.zeit.checked;
	var umzug = form.umzug.checked;
	var beitrag = form.beitrag.checked;
	var vorstellungen = form.vorstellungen.checked;
	var vorstellungen_grund = form.vorstellungen_grund.value;
	var anschluss = form.anschluss.checked;
	var vorstand = form.vorstand.checked;
	var vorstand_grund = form.vorstand_grund.value;
	var trainer = form.trainer.checked;
	var trainer_grund = form.trainer_grund.value;
	var gastronomie = form.gastronomie.checked;
	var gastronomie_grund = form.gastronomie_grund.value;
	var verbesserungen = form.verbesserungen.value;
	var eintritt_wenn = form.eintritt_wenn.value;
	
	UmfrageAction.addUmfrageErgebnis(email, zeit, umzug, beitrag, vorstellungen, vorstellungen_grund, anschluss, vorstand, vorstand_grund, trainer, trainer_grund, gastronomie, gastronomie_grund, verbesserungen, eintritt_wenn, function(result, e) {
		if (result) {
			Ext.Msg.show({
				title	: 'Vielen Dank',
				msg		: 'Vielen Dank, dass Sie sich die Zeit genommen haben uns mit dieser Umfrage zu unterstützen.',
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.INFO,
				fn		: function(buttonId, text, opt) {
					window.location.href = "http://www.potsdamer-tc.de";
				}
			});
		} else {
			Ext.Msg.show({
				title	: 'Fehler',
				msg		: 'Es ist leider ein Fehler beim Auswerten der Umfrage aufgetreten. Bitte versuchen Sie es erneut.',
				buttons	: Ext.Msg.OK,
				icon	: Ext.MessageBox.ERROR
			});
		}
	});

	return false;
}

/*
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();
}
*/
