function frameBreakout() {
	if (top.location != location) {
		top.location.href = document.location.href;
	}
}

function showModal(title, content, width) {
	Control.Modal.close();
	
	if (width > 0) {
		$('modal').style.width = width + 'px';
	}
	
	$('modal_title').innerHTML = title;
	$('modal_body').innerHTML = content;
	content = $('modal_frame').innerHTML;
	$('modal_body').innerHTML = '';
	
	Control.Modal.calcSize();
	
	if (width > 0) {
		m = new Control.Modal.open(content, {opacity: 0.8, width:width, overlayCloseOnClick: false});
	} else {
		m = new Control.Modal.open(content, {opacity: 0.8, overlayCloseOnClick: false});
	}
	hideFlashLayers();
}

function template(source, data) {
	Template.Pattern = /(^|.|\r|\n)(\#\$(.*?)\#)/;
	var tpl = new Template($(source).innerHTML.unescapeHTML());
	return tpl.evaluate(data);
}

function closeModal(){
	Control.Modal.close();
	showFlashLayers()
}

function hideFlashLayers() {
	$$('.flashobj').each(function (obj) { obj.hide(); })
}

function showFlashLayers() {
	$$('.flashobj').each(function (obj) { obj.show(); })
}

function showErrors(errors) {
	if (errors == 1 || errors == '') {
		return;
	}
	
	var content = '';
	content += '<ul>';
	
	if (typeof(errors) == 'object') {
		var json = eval('(' + errors + ')');
		
		for(i = 0; i < json.errors.length; i++) {
			content += 
				'<li>' + translateError(json.errors[i]) + '</li>';
		}
	} else {
		var list = errors.split(',');
		
		for(i = 0; i < list.length; i++) {
			if (list[i].length > 0) {
				content += 
					'<li>' + translateError(list[i]) + '</li>';
			}
		}
	}
	
	content += '</ul>';
	
	showModal('Ui da ist wohl ein Fehler aufgetreten...', content);
}

function translateError(error) {
	var errors = {
		'LOGOUT_FAILED': 'Du bist doch garnicht eingeloggt?',
		'LOGIN_FAILED': 'E-Mail oder Passwort falsch eingetippt?',
		'NOT_ACTIVATED': 'Du musst erst die E-Mail bestätigen.',
		'NAME_IN_USE': 'Dein Anzeigename ist leider schon vergeben.',
		'INVALID_NAME': 'Dein Anzeigename ist ungültig oder schon belegt (min. 3 Zeichen Länge).',
		'ALIAS_IN_USE': 'Deine Adresse ist leider schon vergeben.',
		'INVALID_ALIAS': 'Dein Alias ist ungültig (min. 3 Zeichen Länge).',
		'INVALID_DATE': 'Das eingegebene Datum ist ungültig.',
		'INVALID_EMAIL': 'Ungültige E-Mail Adresse',
		'PW_MISMATCH': 'Das Passwort stimmt nicht überein oder ist zu kurz.',
		'USERNAME_TAKEN': 'Der Benutzername ist schon vergeben.',
		'ALREADY_REGISTERED': 'Du bist (mit diese E-Mail Adresse) schon registriert.',
		'PAYOFF_NOT_POSSIBLE': 'Eine Auszahlung ist nicht möglich.',
		'INVALID_TYPE': 'Bitte auswählen, ob du Artist oder User bist.',
		'POLICY_NOT_ACCEPTED': 'Vor dem Anmelden bitte die AGB akzeptieren.',
		'NOT_LOGGED_IN': 'Bitte vorher <a style="text-decoration: underline;" href="/login/">einloggen</a> oder <a style="text-decoration: underline;" href="/signup/">neu registrieren</a> :)',
		'ALBUM_ALREADY_PURCHASED': 'Das Album ist doch schon deins...',
		'ALBUM_NOT_AVAILABLE': 'Das Album existiert nicht.',
		'SELFBUY_NOT_ALLOWED': 'Das ist doch deine eigene Musik :)',
		'SONG_ALREADY_PURCHASED': 'Der Song gehört dir schon.',
		'ALREADY_PURCHASED': 'Das gehört dir doch schon...',
		'TRANSACTION_FAILED': 'Oh, du hast wohl nicht genügend Geld auf dem Konto.',
		'UNKNOWN_USER_ALBUM_SONG': 'Oh, ich glaube den User/Artist das Album oder den Song kennen wir nicht?.',
		'INVALID_RECIPIENT': 'Bitte gib einen Namen an.',
		'ALREADY_ADDED': 'Du beobachtest doch schon die Updates?',
		'EMPTY_MESSAGE': 'Du hast hast vergessen einen Text einzugeben.',
		'NO_EMAIL_FOUND': 'Die E-Mail Adresse konnte nicht gefunden werden.',
		'ALREADY_RATED': 'Du hast schon dafür abgestimmt.',
		'SELF_RATING_DISALLOWED': 'Für sich selber stimmen geht doch nicht :)',
		'INVALID_UPLOADED_SONG': 'Der hochgeladene Song ist fehlerhaft.',
		'SONG_ALREADY_EXISTS': 'Der Songname existiert bereits.',
		'INVALID_SONG_TITLE': 'Der Songtitle ist ungültig.',
		'INVALID_SONG_ALIAS': 'Der Alias unter dem der Song erreichbar ist, ist ungültig.',
		'INVALID_SONG': 'Ungültiger Song.',
		'NO_CHANGE': 'Das Skin wurde nicht gewechselt.',
		'INVALID_USER_NAME': 'Ungültiger Benutzername.',
		'FAILED': 'Das ging leider schief...',
		'MESSAGE_FAILED_DEL': 'Die Message konnte nicht gelöcht werden.',
		'NO_VIDEO': 'Das Video existiert leider nicht.',
		'ACTIVATION_CODE_INVALID': 'Ungültiger Aktivierungscode',
		'ALREADY_ACTIVATED': 'Du bist schon aktiv.',
		'NO_GENRE': 'Bitte ein Genre auswählen.',
		'INVALID_ALBUM_NAME': 'Ungültige Album Name',
		'INVALID_ALBUM_ALIAS': 'Ungültiger Album Alias',
		'ALBUM_ALREADY_EXISTS': 'Dieses Album gibt es schon.',
		'WRONG_CODE': 'Ungültiger Einladungscode.',
		'INVALID_POSITION': 'Die Position innerhalb der Band ist falsch.',
		'INVALID_USER_NAME': 'Der Benutzername ist ungültig.',
		'USER_IS_ARTIST': 'Das Bandmitglied ist ein Künstler.',
		'SKIN_ALREADY_EXISTS': 'Dieser Skin existiert bereits unter diesem Namen',
		'INVALID_PRODUCT_NAME': 'Ungültiger Produktname',
		'INVALID_PRODUCT_PRICE': 'Ungültiger Preis',
		'INVALID_PRODUCT_CATEGORY': 'Ungültige Produktkategorie',
		'CONNECTION_LIMIT_REACHED': 'Du kannst nicht mehr als 10 Freundschaften pro Tag schlißen.',
		'UPLOAD_FAILED': 'Leider ist ein Fehler beim Hochladen aufgetreten',
		'INVALID_UPLOADED_PHOTO': 'Dein Bild konnte nicht hochgeladen werden.',
		'INVALID_CHECKCODE': 'Es ist ein interner Fehler aufgetreten. Bitte logge Dich aus und danach wieder ein. Danke.'
	};
	
	for (key in errors) {
		if (key == error) {
			return errors[key];
		} 
	}
	
	if (error.length > 0) {
		return 'Unbekannter Fehler: (' + error + ')';
	} else {
		return '';
	}
}

function showPurchase(hash, type) {
	
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'ressource=purchase&' + 'hash=' + hash + '&type=' + type
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Musik kaufen', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function purchase(hash, type) {
	
	$('modal_body').startWaiting();
	$('purchase_button').disabled = true;

	if ($('followupdates') != null && $('followupdates').checked == true) {
		
		var params = 'hash=' + $('followupdates_hash').value + '&checkcode=' + $('checkcode').innerHTML;
		
		new Ajax.Request(
			'/follower/add/',
			{
				onSuccess: function(json) {
					//alert('following')
				},
				method: 'post',
				parameters: params
			}
		);
	}	

	var params = 'hash=' + hash + '&type=' + type +
		 '&checkcode=' + $('checkcode').innerHTML;

	new Ajax.Request(
		'/purchase/',
		{
			onSuccess: function(json) {
				var result = json.responseText.evalJSON();
		
				$('modal_body').stopWaiting();
				
				if (result.status == 1) {
					showModal(
						'Vielen Dank!', 
						'<h1>Herzlichen Glückwunsch, der Kauf war erfolgreich.</h1>' + 
						'Den Song oder das Album findest du in <a class="menulink" href="/library2/" target="_blank">' + 
						'<u>deiner Musik Bibliothek</u></a> zum Download.'	
					);
					
					//trackPurchase(type, hash, result.price);
				} else {
					showErrors(result.status);	
				}				
			},
			method: 'post',
			parameters: params
		}
	);
}

function trackPurchase(type, id, price) {
	var pageTracker = _gat._getTracker("UA-568520-5");
	pageTracker._initData();
	pageTracker._trackPageview();

	if (type == 0) {
		type = 'album';
	} else {
		type = 'song'
	}

	price = price / 100;

	pageTracker._addTrans(
		"<?=$session['user']['alias']; ?>",
		"Payment",
		price,
		"0",
		"0",
		"Stuttgart",
		"BW",
		"Germany"
	);

	pageTracker._addItem(
		"1",
		id,
		type, 
		"music",
		price,
		"1"
	);

	pageTracker._trackTrans();
}

function showRecommend(hash, type) {
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'ressource=recommend&' + 'hash=' + hash + '&type=' + type;
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Weiterempfehlen', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function sendRecommend(hash, type) {
	var params = $('recommend_form').serialize();
	params += '&hash=' + hash + '&type='+ type +
		'&checkcode=' + $('checkcode').innerHTML;
	
	$('modal_body').startWaiting();
	
	new Ajax.Request(
		'/recommend/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');

				$('modal_body').stopWaiting();

				if (result.status == 1) {
					showModal('Vielen Dank!', 'Deine Empfehlung wurde zugestellt :)');
				} else {
					showErrors(result.status);	
				}				
			},
			method: 'post',
			parameters: params
		}
	);
}

function showConnection(hash) {

	if (globLogin == 0) {
		showRegBox();
		return false;
	}

	var params = 'ressource=connection&' + 'hash=' + hash;
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Follower werden', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function connection(hash) {
	var params = $('connection_form').serialize();
	params += '&hash=' + hash + '&checkcode=' + $('checkcode').innerHTML;
	
	$('modal_body').startWaiting();
	
	new Ajax.Request(
		'/follower/add/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');

				$('modal_body').stopWaiting();

				if (result.status == 1) {
					showModal('Vielen Dank!', 'Wunderbar, das hat geklappt.');
				} else {
					showErrors(result.status);	
				}
			},
			method: 'post',
			parameters: params
		}
	);
}

function delConnection(hash) {
	
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'hash=' + hash + '&checkcode=' + $('checkcode').innerHTML;
	
	$('modal_body').startWaiting();
	
	new Ajax.Request(
		'/follower/del/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');

				if (result.status == 1) {
					document.location.reload();					
				} else {
					showErrors(result.status);	
				}
			},
			method: 'post',
			parameters: params
		}
	);		
}

function showMessage(hash) {
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'ressource=message&' + 'hash=' + hash;
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Eine Nachricht schreiben', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function sendMessage(hash) {
	var params = $('message_form').serialize();
	params += '&hash=' + hash + '&checkcode=' + $('checkcode').innerHTML;

	$('message_button').disabled = false;
	$('modal_body').startWaiting();

	new Ajax.Request(
		'/messages/send/',
		{
			onSuccess: function(json) {
				var result = json.responseText.evalJSON();

				$('modal_body').stopWaiting();

				if (result.status == 1) {
					showModal(
						'Vielen Dank!', 
						'Die Brieftaube war eben da und hat Deine Message abgeholt!'
					);
					$('message_button').disabled = true;
				} else {
					showErrors(result.status);	
				}
			},
			method: 'post',
			parameters: params
		}
	);
}

function showComment(hash, type) {
	
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'ressource=comment&' + 'hash=' + hash + '&type=' + type;
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Einen Kommentar hinterlassen', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function sendComment(hash, type) {
	var params = $('comment_form').serialize();
	params += '&hash=' + hash + '&type=' + type +
		'&checkcode=' + $('checkcode').innerHTML;
	
	$('comment_button').disabled = true;
	
	new Ajax.Request(
		'/comment/',
		{
			onSuccess: function(json) {
				var result = json.responseText.evalJSON();

				if (result.status == 1) {
					document.location.reload();
					$('comment_button').disabled = false;
				} else {
					showErrors(result.status);	
					$('comment_button').disabled = false;
				}
			},
			method: 'post',
			parameters: params
		}
	);
}

function delComment(hash, type) {
	if (!confirm('Wirklich löschen?')) {
		return;
	}

	var params = 'hash=' + hash + '&type=' + type;

	new Ajax.Request(
		'/comment/del/',
		{
			onSuccess: function(json) {
				var result = json.responseText.evalJSON();

				if (result.status == 1) {
					document.location.reload();
				} else {
					showErrors(result.status);	
				}
			},
			method: 'post',
			parameters: params
		}
	);
}

function changeSkin(skin, alias) {
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	if (confirm("Willst du den Skin wirklich für dein Profil benutzen?")) {
		var params = 'skin=' + skin;

		new Ajax.Request(
			'/profile/skin/',
			{
				onSuccess: function(json) {
					var result = json.responseText.evalJSON();

					if (result.status == 1) {
						document.location.href = '/' + alias + '/';
					} else {
						showErrors(result.status);	
					}

				},
				onFailure: function(json) {
				},
				method: 'post',
				parameters: params
			}
		);

	}
}

function showPhoto(name, photo) {
	$('lightbox_photo').src = photo;
	m = new Control.Modal.open($('lightbox').innerHTML, {opacity: 0.8});
}

function limitText(src, target, length) {
	var left = length - $(src).value.length;

	if (left <= 0) {
		$(src).value = $(src).value.substring(0, length);
	}

	$(target).innerHTML = left;
}

function stripText(text, length) {
	if (text.length > length) {
		text = text.substring(0, length-3) + '...';
	}
	
	return text;
}

/* protoload 0.1 beta by Andreas Kalsch
 * last change: 09.07.2007
 *
 * This simple piece of code automates the creating of Ajax loading symbols.
 * The loading symbol covers an HTML element with correct position and size - example:
 * $('myElement').startWaiting() and $('myElement').stopWaiting()
 */
 
Protoload = {
	// the script to wait this amount of msecs until it shows the loading element
	timeUntilShow: 250,
	
	// opacity of loading element
	opacity: 0.8,

	// Start waiting status - show loading element
	startWaiting: function(element, className, timeUntilShow) {
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (className == undefined)
			className = 'waiting';
		if (timeUntilShow == undefined)
			timeUntilShow = Protoload.timeUntilShow;
		
		element._waiting = true;
		if (!element._loading) {
			var e = document.createElement('div');
			(element.offsetParent || document.body).appendChild(element._loading = e);
			e.style.position = 'absolute';
			try {e.style.opacity = Protoload.opacity;} catch(e) {}
			try {e.style.MozOpacity = Protoload.opacity;} catch(e) {}
			try {e.style.filter = 'alpha(opacity='+Math.round(Protoload.opacity * 100)+')';} catch(e) {}
			try {e.style.KhtmlOpacity = Protoload.opacity;} catch(e) {}
			
			/*var zIndex = 0;
			if (window.UI)
				if (UI.zIndex)
					zIndex = ++UI.zIndex;
			if (!zIndex)
				zIndex = ++Protoload._zIndex;
			e.style.zIndex = zIndex;*/
		}
		element._loading.className = className;
		window.setTimeout((function() {
			if (this._waiting) {
				var left = this.offsetLeft, 
					top = this.offsetTop,
					width = this.offsetWidth,
					height = this.offsetHeight,
					l = this._loading;
					
				l.style.left = left+'px';
				l.style.top = top+'px';
				l.style.width = width+'px';
				l.style.height = height+'px';
				l.style.display = 'inline';
			}
		}).bind(element), timeUntilShow);
	},
	
	// Stop waiting status - hide loading element
	stopWaiting: function(element) {
		if (element._waiting) {
			element._waiting = false;
			element._loading.parentNode.removeChild(element._loading);
			element._loading = null;
		}
	}
};

if (Prototype) {
	Element.addMethods(Protoload);
	Object.extend(Element, Protoload);
}

function addColorPickerSkins() {
	['bg', 'main_bg', 'box_bg', 'text', 'link', 'title', 'tab', 'tab_bg', 'tab_selected', 'tab_selected_bg'].each(function(id) {
		new Control.ColorPicker(id, { IMAGE_BASE : "/static/images/colorpicker/" });
	});
}

function addColorPickerPromote() {
	['widget_color', 'widget_font'].each(function(id) {
		new Control.ColorPicker(id, { IMAGE_BASE : "/static/images/colorpicker/" });
	});
}

function addColorPickerWidgets() {
	for (i = 0; i < 20; i++) {
		var id = $('param_' + (i + 1));
		if (id != undefined) {
			new Control.ColorPicker(id, { IMAGE_BASE : "/static/images/colorpicker/" });
		}
	}
}

function validateLightBoxSignup(type) {
	var parameters = $('lb_signup').serialize();

	new Ajax.Request(
		'/signup/check/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');
				if (result.status != 1)  {
					showRegErrors(result.status);
				} else {
					if (type == 'small') {				
						clip20SendSignup();
					} else {
						$('lb_signup').submit();
					}
				}
			},
			parameters: parameters,
			method: 'post'
		}
	);
}

function validateLandingPageSignup() {
	var parameters = $('lb_signup').serialize();

	new Ajax.Request(
		'/signup/check/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');
				if (result.status != 1)  {
					showRegErrors(result.status);
				} else {
					alert('Danke für deine Anmeldung!\n\nDein eventuelles Startguthaben wird dir gutgeschrieben, sobald du deine E-Mail Adresse bestätigst. Den Bestätigungs-Link haben wir an deine Adresse geschickt.\n\nDu wirst jetzt weitergeleitet.\n\nWir wünschen dir viel Spaß auf Justaloud!');
					$('lb_signup').submit();
				}
			},
			parameters: parameters,
			method: 'post'
		}
	);
}

function showRegErrors(errors) {
	
	if (errors == 1 || errors == '') {
		return;
	}
	
	var content = '';
	content += '<ul style="list-style-type: none; margin: 0px; padding: 0px;">';
	
	if (typeof(errors) == 'object') {
		var json = eval('(' + errors + ')');
		
		for(i = 0; i < json.errors.length; i++) {
			content += 
				'<li>' + translateError(json.errors[i]) + '</li>';
		}
	} else {
		var list = errors.split(',');
		
		for(i = 0; i < list.length; i++) {
			if (list[i].length > 0) {
				content += 
					'<li>' + translateError(list[i]) + '</li>';
			}
		}
	}
	
	content += '</ul>';
	
	$('lb_signup_error_text').innerHTML = content;
	$('lb_signup_errors').show();
}

function sendSignup() {
	var params = $('lb_signup').serialize();

	new Ajax.Request(
		'/signup/',
		{
			onSuccess: function(json) {
				var result = eval('(' + json.responseText + ')');
				alert(result.user.alias);
				document.location.reload();
			},
			parameters: params,
			method: 'post'
		}
	);
}

function makeLBAlias(sourceId, displayId, formId) {
	
	/* get value from input text */
	var string = document.getElementById(sourceId).value;

	/* replace accents by their bases */
	string = string.toLowerCase();
	string = string.replace(/[äåæàáâã]/g, 'a');
	string = string.replace(/[ç]/g, 'c');
	string = string.replace(/[Ð]/g, 'd');
	string = string.replace(/[èéêë]/g, 'e');
	string = string.replace(/[ìíîï]/g, 'i');
	string = string.replace(/[ñ]/g, 'n');
	string = string.replace(/[ðòóôõöøŒ]/g, 'o');
	string = string.replace(/[ßŠš]/g, 's');
	string = string.replace(/[ùúûüµ]/g, 'u');
	string = string.replace(/[ýÿ¥]/g, 'y');
	string = string.replace(/[ ]/g, '');
	string = string.replace(/[-,]/g, '');
	string = string.replace(/[&]/g, '');
	string = string.replace(/(\n|\r|' '|[^a-zA-Z0-9-])/g, '');
	string = string.replace(/[-]{2,}/g, '');
	
	/* max 32 chars length */
	if (string.length <= 32) {
		$(displayId).value = string;
	} else {
		$(displayId).value = string.substr(0, 32) + '..';
	}
	
	if (string.length == 0) {
		$(displayId).value = '';
	}
}

function showRegBox(type, code) {
	if (type == 'small') {
		var params = 'ressource=signup_small';
	} else {
		var params = 'ressource=signup';
	}
	
	if (code != null) {
		params += '&code=' + code;
	}

	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Registrierung', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

/* login field */
function showCookieTip() {
	new Effect.Appear('cookietip');
	
	if (navigator.appName == 'Microsoft Internet Explorer') {
		$('search_submit').hide();
		$('search_field').style.margin = '0 73px 0 0'
	}
}

function hideCookieTip() {
	new Effect.Fade('cookietip');
	
	if (navigator.appName == 'Microsoft Internet Explorer') {
		$('search_submit').show();
		$('search_field').style.margin = '0;'
	}
}

function trackGAPI(path) {
	if (typeof (pageTracker) == 'object') {
		pageTracker._trackPageview(path);	
	}
}

function showDownloader() {
	
	if (globLogin == 0) {
		showRegBox();
		return false;
	}
	
	var params = 'ressource=downloader';
	
	new Ajax.Request(
		'/ressources/',
		{
			onSuccess: function(json) {
				showModal('Songs herunterladen', json.responseText);
			},
			parameters: params,
			method: 'post'
		}
	);
}

function g2amzn(query){
	pageTracker._trackPageview("/clickout/amazon/");
	window.open('http://www.amazon.de/gp/search?ie=UTF8&keywords=' + query + '&tag=justaloud-21&index=mp3-downloads&linkCode=ur2&camp=1638&creative=6742');
}

function g2mload(query){
	pageTracker._trackPageview("/clickout/musicload");
	window.open('http://partners.webmasterplan.com/click.asp?ref=651&site=3752&type=text&tnb=8&prd=yes&stext=' + query);
}

function g2itunes(query){
	pageTracker._trackPageview("/clickout/itunes");
	window.open('http://clkde.tradedoubler.com/click?p=23761&a=1780218&g=18460838&td_term=' + query);
}
