// JavaScript Document
function makeIt(a, href, it){
	a = functions(a, it);
	if(!a || !a.a) return;
	if(!it) it = document.getElementById("dummy-link");
	if($(it).attr("not")) return;
	var actions = a.a.split(/-/);
	switch(actions[0]) {
		case "show": 
			if(a.b) lta.showPod(a.m+"_"+a.b); else
			if(actions[1])
			lta.showPod(actions[1]);
		return;
		case "toggle":
			actions = actions[1].split(/\_/);
			var c = (actions[1] == 0) ? 1 : 0;
			if(actions[1] == undefined) c = -1;
			if(c > - 1){
				$("#"+actions[0]+"_"+actions[1]).show();
				$("#"+actions[0]+"_"+c).hide();
				$(it).attr("href", "?a=toggle-"+actions[0]+"_"+c+"&caption="+$( it ).html() );
			} else {
				$("#"+actions[0]).toggle();
				$(it).attr("href", "?a=toggle-"+actions[0]+"&caption="+$( it ).html() );
			}
			$(it).html(a.caption);
		return;
		case "add": 
			if(actions[1] == "list") {
				a[a.m+"s"] = getList(a.m, a[a.m+"list"]);
				a.n = "pl";
			}
		break;
	}

	if(a.nopod || a.cont) return requestP(a, it);
	
	if(a.n == "pl-new"){
		
	}

	var action = actions[0];
	if(a.a == "add" || a.a == "play") a.n = "pl";
	requestP(a, it);
}
//Wird am anfang von makeit durchlaufen
function functions(a, it){
	var p = {};
	switch(a.a) {
		case "translate":
			var text = $("#"+a.text);
			var result = $("#"+a.text+"-translate");
			translate(text.html().toLowerCase(), a.lang, result);
			$(it).hide();
		return false;
	}
	
	return a;
}

function decodeLink(href, as_p){
	href = href.replace(/\?/, "");
	var h2 = "?";
	var h = href.split("&");
	var a = {};
	var last = "";
	for(var i in h) {
		var j = h[i].split("=");
		//Wenn kein = vorhanden &-Zeichen-Fehler
		if(j[0] == h[i]) {
			//a[h[last]] = false; 
			//+= "&"+Url.decode(j[0]);		//dekodieren
			//h2 += "%26"+Url.decode(j[1]); //dekodieren
		} else {
			//Zusätzliche infos aus select holen wenn nötig
			if( j[0].search(/select|input/) == 0 ) {
				var name = $("#"+j[1]).attr("name");
				var val = $( "#"+j[1] ).val(); 
				a[ name ] = Url.decode( val ); 
				href = href.replace(h[i], name+"="+a[name])
			} else
			a[j[0]] = Url.decode(j[1]);		//dekodieren
			last = i;
		}
	}
	a.href = "?"+url_encode(href);
	if(as_p) return a; else
	return h2;
}

function linkP(href){
	return decodeLink(href, true);
}

function Plink(p){
	var href = "?";
	var und = "";
	for(var i in p) {
		if(p[i])
		href += und+i+"="+url_encode(p[i]);
		und = "&";
	}
	return href;
}

function setLinkHtml(pod){
	if(!links[pod]) return;
	links[pod][0].html(links[pod][1]);
	links[pod] = null;
}

function __(p){
	var args = __.arguments;
	var out = $("#lang > #_"+p).html();
	for(var i = 1; i < args.length; i++){ 
		out = out.replace(/\%s/, args[i]);
	}
	return out;
}

function formatter(html, selector, p){
	var $f = $("#formatter");
	$f.html(html);
	setJEvents($f, p);
	if(selector == "*") var $s = $("#formatter > "+selector); else
	var $s = $(selector, $f);
	$("#formatter").html("");
	return $s;
}

function makejq(it){
	if(it instanceof jQuery) return it;
	return $(it);
}

function login(a){
	var p = new Object();
	switch(a){
		case 'lfm':
			//var w = window.open("http://www.last.fm/api/auth/?api_key=45576086078efaa70e6512a10b6edfcb", "Lastfm - Connect", "width=950,height=500,resizable=no,toolbar=no,location=no");
			document.location = "http://www.last.fm/api/auth/?api_key=45576086078efaa70e6512a10b6edfcb";
			return;
		break;
		default: 
			p.a = "login";
			p.m = "user";
			p.uname = $("#login-name").val();
			p.password = $("#login-password").val();		
		break;
	}
	requestP(p);	
}

function register(){
	var p = new Object();
	p.a = "register";
	p.m = "user";
	p.uname = $("#register-name").val();
	p.email = $("#register-email").val();
	p.password = $("#register-password").val();
	p.password2 = $("#register-password2").val();
	p.lang = $("#register-language").val();
	p.recaptcha_challenge = Recaptcha.get_challenge();
	p.recaptcha_response = Recaptcha.get_response();
	requestP(p);
}

function reload_page(){
	document.location = url;
}

function checkUsername(){
	var p = new Object();
	p.a = "exists";
	p.m = "user";
	p.uname = $("#register-name").val();
	requestP(p);
}

function getList(m, list_id){
	var a = [];
	var list = $(".ui-selected:visible", "#"+list_id);
	if(m == "track" || m == "album")
	list.each(function(){
		var b = {};
		b.name = $(this).attr(m);
		b.artist = $(this).attr("artist");
		a.push(b);
	}); 
	else if(m == "video")
	list.each(function(){
		var b = {};
		b.name = $(this).attr("v");
		b.video = $(this).attr("video");
		b.image = $(this).attr("image");
		a.push(b);
	}); 
	return array2json(a);
}

function video_favorite(){
	if(!lta.loaded.infos) return;
	p = new Object();
	p.a = "favorite";
	p.m = "video";
	p.v = pls.playitem.attr("video");
	p.track = pls.playitem.attr("track");
	p.tags = pls.playitem.attr("tags");
	p.artist = pls.playitem.attr("artist");
	p.own = pls.playitem.attr("own");
	p.image = pls.playitem.attr("image");
	p.duration = pc.duration;
	p.display = "video-message";
	user.tracks += p.v+"/";
	requestP(p);
}

function video_hate(v, type){
	if(!lta.loaded.infos) return;
	p = new Object();
	p.a = "hate";
	p.m = "video";
	p.type = type;
	if(v) p.v = v; else
	p.v = pls.playitem.attr("video");
	p.track = pls.playitem.attr("track");
	p.tags = pls.playitem.attr("tags");
	p.artist = pls.playitem.attr("artist");
	p.own = pls.playitem.attr("own");
	p.image = pls.playitem.attr("image");
	p.duration = pc.duration;
	p.display = "video-message";
	user.hates += p.v+"/";
	requestP(p);
	if(!v || v == pls.playitem.attr("video")) pc.videos.next(p.v);

}

function video_download(){
	if(!lta.loaded.infos) return;
	if(pc.videos.download.url) return displayMessage(pc.videos.download.link);
	p = new Object();
	p.a = "download";
	p.m = "video";
	p.v = pls.playitem.attr("video");
	p.track = pls.playitem.attr("track");
	p.duration = pc.duration;
	p.display = "video-message";
	requestP(p);
}

function getCovers(){
	$("img.getcover").each(function(i){
		var href = $(this).parents("a:first").attr("href");
		$(this).removeClass("getcover");
		var p = linkP(href);
		p.a = "getcover";
		p.image = $(this).attr("id");
		requestP(p);
	});
}

function user_listen_noDay(date){
	var t = date.getTime() / 1000;
	var f = 0;
	if(user.listen_days[t]) f = 1;
	return [f, '']; 
}

function hash_change(val, start){
	if(val) {
		val = val.replace(/\&(pod\=[^\&]*|sub\=[^\&]*)/g, "");
		window.location.hash = val;
		lta.hash = window.location.hash;
	} else
	if((window.location.hash != "#"+lta.hash && window.location.hash != lta.hash) || start) {
		//alert(lta.hash+":"+window.location.hash);
		var h = window.location.hash;
		if(start) {
			h = encodeURI(h.replace(/(\%20\&\%20| \& )/, " %26 "));
		}
		h = h.replace(/\#/, "");
		var p = linkP(h);
		makeIt(p, h);
		hash_change(h);
	}
}

function getPod(it){
	var podid = $(it).parents(".pod").attr("id");
	if(!podid) return false;
	return pods[podid];
}

function requestLink(href){
	var a = $("#dummy-link");
	a.attr("href", href);
	a.trigger("click");
}

function setNewPlay(){

}


function trim (s) {
  if(!s) return "";
  return s.replace (/^\s+/, '').replace(/\s+$/, '');
}

function decodeHTML(html) { 
    return html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
}; 
function decodeHTML2(html) { 
    return html.replace(/&amp;/g,'%26').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
};

function url_encode(html) { 
    return html.replace(/\%26/g, escape('%') + '26');
};

var gen_id;
function generateID(){
	gen_id = ""+getRandom(1000, 9999)+getRandom(1000, 9999)+getRandom(1000, 9999)+getRandom(1000, 9999);
	return gen_id;
}

function getRandom(min, max ) {
	  return min + parseInt(Math.random() * (max - min + 1));
}

function playlists_length(){
	return $(".playlist", ".pods").length;
}

function arrcount(array){	
	var length = 0;
	for (var object in array) length++;
	return length;
}
function arrelement(arr, ind){
	var i = 0;
	for (var object in arr) {
		if(i == ind) { 
			i = object;
			break;
		}
		i++;
	}
	return arr[i];
}

function is_there_a_playlist(){
	if(!trim($(".playlist:first", ".pods").html())) return false;
	return true;
}

function scroll_dom(container, it){
	if(typeof(it) == "number") var top = it; else
	if(!it.position()) return;
	else var top = it.position().top;
	container.animate({"scrollTop": top}, 500);
}

function ActionHandler(buttons){
	this.undos = [];
	this.redos = [];
	this.last = "";
	this.btn = {undo:$("#undo-btn"),redo:$("#redo-btn")};
	this.pos = 0;
	this.act = function(a, c){
		var b = {};
		switch(a.action) {
			case "delete-pod":
				b.action = "repair-pod";
				b.pod = pods[a.pod];
				var nochmal = true;
			break;
			case "delete-tracks": 
				b.action = "delete-tracks";
				b.pid = a.pid;
				b.tracks = pls.list.html();
			break;
		}
		if(c) {
			b.action = a.action;
			this.redos.push(b);
		} else this.undos.push(b);
		if(this.redos.length == 4) {
			this.undos.splice(0, 1);
			this.redos.splice(0, 1);
		}
		this.last = "";
		this.pos = this.redos.length - 1;
		if(nochmal && !c) this.act(a, 1);
		this.btn.undo.show();
		this.btn.redo.hide();
	}
	
	this.undo = function (){
		if(this.redos.length == 0 || this.pos < 0) return false;
		if(this.last == "undo") this.pos--;
		this.doIt(this.undos);
		if(this.pos == 0) this.btn.undo.hide();
		this.btn.redo.show();
		this.last = "undo";
	}
	
	this.redo = function (){
		if(this.redos.length == 0 || this.pos < 0) return false;
		if(this.last == "redo") this.pos++;
		this.doIt(this.redos);
		if(this.pos == this.redos.length - 1) this.btn.redo.hide();
		this.btn.undo.show();
		this.last = "redo";
	}
	
	this.doIt = function(w){
		var a = w[this.pos];
		//alert(this.pos);
		//alert(a.action);
		switch(a.action) {
			case "delete-tracks": pls.undoDeletion(a.tracks); break;
			case "delete-pod": a.pod.deleteIt("undoredo"); break;
			case "repair-pod": a.pod.repair("undoredo"); break;
		}
	}
}











//For Translation!//For Translation!
//For Translation!//For Translation!
//For Translation!//For Translation!
function checkSelection(){
	
}

function translate(text, lang, container, append){
	if(!append) container.html("<h3>"+__("translation")+"</h3>");
	var again = false;
	if(text.length > 1000) {
		var s = text.substr(0, 1000);
		var i = 0;
		var b = s[s.length - 1];
		var max = text.length - 1;
		while (b != " " && 1000 + i < max) {
			i++;
			b = text[1000 + i];
			s += b;
		}
		again = true;
	} else var s = text;
	google.language.translate(s, "", lang, function(result) {
		container.append(result.translation);
		scroll_dom(container.parents(".sub:first"), container);
	});		
	if(again) translate(text.substr(1000 + i), lang, container, true);
}

var displayTimer;
function displayMessage(m, klasse){
	lta.messageDisplay.tipTip({
		content : "<div class='"+klasse+"'>"+m+"</div>", 
		defaultPosition : "right", 
		activation : "click",
		maxWidth : "400px"
	});
	lta.messageDisplay.triggerHandler("click");
	window.setTimeout(function(){
		lta.messageDisplay.triggerHandler("mouseout");				   
	}, 5000);
}
function hideMessage(){
	scroll_dom(lta.messageDisplay, 0);
	lta.messageDisplay.stop();
	lta.messageDisplay.hide();
}


	
function laden(){
	
}

function newScript(url){
	var head = document.getElementsByTagName('head')[0]
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", url);
    head.appendChild(script);
}

function unload(){
	if(!player) return;
	player.stopVideo();
}

//Nach request für EVENTS

function setJEvents(pod, p){
	if(pod != "body") pod = pod.self;

	$(".textfield", pod).each(function(i){
		$(this).val($(this).attr("default"));
		$(this).addClass("default");
	});

	$(".textfield, .req-input", pod).keydown(function(e){
		switch(e.keyCode){
			
			case 13: request_input();
		}
	});
	$(".textfield, .req-input", pod).live('blur', function(){
		if($(this).hasClass("textfield"))
		if(lta.input.val() == "") {
			lta.input.val(lta.input.attr("default"));
			lta.input.addClass("default");
			$(this).trigger("keyup");
		}
		lta.input = null;
	});
	
	$(".textfield, .req-input", pod).live('focus',function(){
		lta.input = $(this);
		if($(this).hasClass("textfield"))
		if(lta.input.val() == lta.input.attr("default")) {
			lta.input.val("");
			lta.input.removeClass("default");
		}
	});
	$("input[type='text']", pod).live("focus",function(){
		lta.input = $(this);
	});
	$("input[type='text']", pod).live("blur",function(){
		lta.input = null;
	});
	$(".textfield, .req-input", pod).dblclick(function(){
		$(this).val("");
	});
	
	$(".table-filter", pod).keyup(function(){
		if(trim($(this).val()) && $(this).val() != __("filter")) $(this).parents(":first").find(".clear-filter").show();
		else $(this).parents(":first").find(".clear-filter").hide();
		filter_table(this);
	}); 
	$(".table-filter", pod).dblclick(function(){
		$(this).trigger("keyup");
	}); 
	
	$(".clear-input", pod).click(function() { 
		$("#"+$(this).attr("input")).val("");
		$("#"+$(this).attr("input")).select();
		$("#"+$(this).attr("input")).focus();
		$(this).hide();
	});
	$(".clear-filter", pod).click(function() { 
		var it = $(this).parents(":first").find(".table-filter");
		it.val("");
		it.keyup();
		it.focus();
	});
	
	$(".tablelist", pod).selectable({
			filter:".entry",
			cancel:".list-head",
			start:function(event, ui){
			},
			stop:function(event, ui){
			},
			beforeselect:function(event, ui){
				$(this).find(".add-btn").show();
			}
	});
	$(".selectAllBtn").click(function(event){
		var tlist = $(this).parents(".tablelist");
		tlist.find(".add-btn").show();
		tlist.selectable("select", "*");
	});
	
	$(".tablelist > .entry", pod).dblclick(function(){
		$(this).find("a:first").click();
	});
	$(".tablelist > .entry", pod).hover(function(){
		$(this).find(".right").css("visibility", "visible");
	}, function(){
		$(this).find(".right").css("visibility", "hidden");
	});
}

function filter_table(fi){
	var t = $(fi).parents(".tablelist");
	var f = $(fi).val();
	var m = $(fi).attr("m");
	var it = $(".entry", t);
	if(f == "" || f == __("filter")) { it.show(); return; }
	f = trim(f.toLowerCase());
	it.each(function(i){
		var a = $(this).attr(m) + " - " + $(this).attr("artist");
		if(a.toLowerCase().indexOf(f) == -1) $(this).hide(); else $(this).show();
	});
} 


/*
escape() kann nicht für Unicode text verwendet werden:

    escape() will not encode: @+

Alternativ bieten sich die encodeURI()bzw. encodeURIComponent() Funktionen an. encodeURI() enkodiert gesamte URIs— beläßt aber Zeichen wie z. B. :?&:

    encodeURI() will not encode: ~!@#$&*()=:/,;?+'

encodeURIComponent() enkodiert alles außer:

    encodeURIComponent() will not encode: ~!*()'


*/

function loge(s){
	if(console) console.log(s);
}

function println(s){
	if(user["uname"] != "mchief90") return;
	$("#infobox").prepend(s+"<br />");
}
