var editor; //Element for RR Editor
var sourceditmode = false; //If sourcecode is active

function newWindow(link, width, height) {
    var winX = (screen.availWidth - width) / 2;
    var winY = (screen.availHeight - height) / 2;
   var popWin = window.open(link,'NewWindow','left='+winX+',top='+winY+',scrollbars=yes,width='+width+',height='+height);
   if (popWin) {
        popWin.focus();
    } else {
        document.location.href = link;
    }

    return false;
}

function hasBGImg(bg) {
	return (bg.replace("/preview/", "").length != bg.length || bg.replace("/download/", "").length != bg.length);
}

function activateEditmode(host, sessionid, nav_id) {
	var divs = document.getElementsByTagName("div");
	for(i=0,n=divs.length;i<n;i++) {
		if(divs[i].className && divs[i].className == "fr_editfield") {
			var elm = divs[i];
			var width = elm.offsetWidth;
			var height = elm.offsetWidth;
			
			//elm.style.border = '1px #c0c0c0 dashed'; //TODO: Border nötig?
			elm.style.outline = 'none';
			var setBlock = false;
			if(elm.childNodes.length == 1) {
				if(elm.childNodes[0].style) setBlock = true;
			} else {
				setBlock = true;
			}
			
			if(setBlock) elm.style.display = 'block';
			
			var posi = getAbsoluteOffset(elm);

			var editButton = document.createElement("img");
			editButton.src = host+"/src/images/actions.png";
			editButton.style.position = "absolute";
			
			editButton.setAttribute("fr_editbutton", "true");
			editButton.style.cursor = "pointer";

			//editButton.style.top = (posi.y)+"px";
			//editButton.style.left = (posi.x+elm.offsetWidth)+"px";
			//+editButton.offsetWidth
			
			if(elm.getAttribute("editnav") == null && elm.getAttribute("contentpic") == null) {
				elm.className += " droppable";
				
			//	editButton.onclick = function() {
			//		var elm = this.parentNode.getElementsByTagName("div")[0];
					
					elm.setAttribute("contenteditable", "true");
					if($(elm).html() == "") $(elm).html("<p>&nbsp;</p>");
					elm.style.minHeight = '20px';
					//elm.style.maxHeight = '500px';
					//elm.style.overflow = "auto";
					elm.id = newFieldId();
					var initContent = elm.id+";;"+$(elm).html();

					// Append the RR Editor
					$(document).ready(function() {
						editor = $(elm).inside_editor();

						if(!ie) $(window).bind("beforeunload", function(e) { if($("#"+initContent.split(";;")[0]).html() != initContent.split(";;")[1]) return trans.UNSAVED_CHANGES; });
						//editor = new Editor(document.getElementById(EDITOR_ID));
					});
					// Append (end)

					// Save button einfuegen
					var submitbutton = document.createElement("input");
					submitbutton.type = "button";
					submitbutton.value = trans.BUTTON_SAVE;
					submitbutton.name  = elm.id;
					submitbutton.onclick = function() {
						if(sourceditmode) {
							alert(trans.END_SOURCE_MODE);
							return false;
						}
						initContent = initContent.split(";;")[0]+";;"+$("#"+initContent.split(";;")[0]).html();
						var postparams = {"content": $("#"+this.name).html(), "nid": $("#"+this.name).attr("navid"), "fieldname": $("#"+this.name).attr("fieldname") };
						var thatbutton = this;
						this.disabled = true;
						$.post("/data.php?post="+urlencode("/content/navigation/editor/?sid="+sessionid), postparams, function(data) {
							if(data == "true") {
								alert(trans.TEXT_SAVED);
							} else {
								alert(trans.TEXT_NOT_SAVED);
							}
							thatbutton.disabled = false;
				 		});
					}
					elm.parentNode.appendChild(submitbutton);
					
			//		this.onclick = function() {
			//			return;
			//		}
			//	}
			//	editButton.style.marginLeft = elm.offsetWidth+"px";
			//	elm.parentNode.insertBefore(editButton, elm);
			} else {
				elm.onmouseover = function() { this.style.background = '#b5b5b5'; };
				elm.onmouseout  = function() { this.style.background = "none"; };
				
				if(elm.getAttribute("editnav") == null) {
					editButton.onclick = function() { return clickEdit(host, this.parentNode) }
				} else {
					editButton.setAttribute("title", "Edit Nav"); //DON'T CHANGE THIS TITLE
				}
				
				if(elm.getAttribute("contentpic") != null) {
					if(hasBGImg($(".fr_editfield[contentpic] > img").css('backgroundImage'))) {
						// Do nothing
					} else {
						//elm.appendChild(editButton);
						editButton.removeAttribute("fr_editbutton");
						editButton.id = "contentpic_edit";
						editButton.style.background = "#fff";
						editButton.style.padding = "5px";
						editButton.style.marginLeft = (elm.offsetWidth-editButton.width-replacepx(editButton.style.paddingLeft)-replacepx(editButton.style.paddingRight))+"px";
						elm.parentNode.insertBefore(editButton, elm);
					}
				} else {
					elm.appendChild(editButton);
				}
			}
		}
	}
	
	$("img[title='Add Nav'], img[title='Edit Nav']").click(function() { //Button for a new Navigation
		var div = document.createElement("div");
		var pid = this.parentNode.parentNode.getAttribute("nid");
		var nid = getFieldAttribute(this.parentNode, "nid", "");
		var title = getFieldAttribute(this.parentNode, "title", "");
		var parentNode = this.parentNode;
		var noAction = false;
		var action;
		
		if(pid == null) pid = nav_id;
		
		$(div).attr("title", trans.MODIFY_NAVIGATION);
		$(div).attr("id", "_navpoint");
		var del = "";
		if(nid != "") {
			del = "<tr><td colspan='2' id='nn23jjn'></td></tr>";
		}
		var table = "<table>"+
					"<tr><th style='text-align:right'>Title</th><td><input type='text' class='title' value='"+title+"' /></td></tr>"+del+"</table>";
		$(div).html(table);
		
		function saveNav() {
			if(!noAction) {
				var v = $("#_navpoint .title").attr("value");
				if(v != "") {
					var dialog = this;
					noAction = true;
					$(div).html("<img src='/src/images/loading_wh.gif' />");
					
					action = "/content/navigation/update/?submit_action=newpoint&template=text&parentid="+pid+"&name="+v+"&sid="+sessionid;
					if(nid != "") {
						action = "/content/navigation/update/?submit_action=title&nid="+nid+"&name="+v+"&sid="+sessionid;
					}
					
					$.get("/data.php?get="+urlencode(action), function(data) {
						//alert(trans.NAVIGATION_SAVED);
						noAction = false;
						
						document.location.href = document.location.href;
					});
				}
				else alert(trans.PLEASE_FILL_TITLE);
			}
		}
		
		$(div).dialog({
			bgiframe: true,
			modal: true,
			
			buttons: {
				Ok: function() {
					saveNav();
				},

				Cancel: function() {
					if(!noAction) {
						$(this).dialog('close');
					}
				}
			},
			
			close: function() {
				if(!noAction) {
					$(this).dialog("destroy");
					var a = document.getElementById("_navpoint");
					a.parentNode.removeChild(a);
				}
			}
		});
		
		$("#_navpoint .title").focus().keyup(function(e) {
			if(e.keyCode == 13) saveNav();
		});
		
		delButton = document.createElement("a");
		delButton.href = "#";
		delButton.innerHTML = trans.DELETE_NAVPOINT;
		delButton.onclick = function() {
			if(confirm(trans.ARE_YOU_SURE_NO_UNDO_PLACEHOLDER.replace("{NAV_NAME}", title))) {
				noAction = true;
				action = "/content/navigation/delete/?deletenav="+nid+"&sid="+sessionid;
				$.get("/data.php?get="+urlencode(action), function(data) {
					noAction = false;
					alert(trans.NAVIGATION_DELETED);
					parentNode.parentNode.parentNode.removeChild(parentNode.parentNode);
					$(div).dialog("close");
				});
			}
			
			return false;
		}
		$('#nn23jjn').append(delButton);
		
		return false;
	});
	
	var div = document.createElement("div");
	var span = document.createElement("span");
	var div_inner = document.createElement("div");
	
	div.appendChild(span);
	div.appendChild(div_inner);
	
	editmenu = new EditMenu(sessionid);
	editmenu.getContent(div_inner);
	
	//div.style.maxHeight = getWindowHeight()-30+"px";
	old_height = 0;
	window.setInterval(function() { 
		if(old_height != getWindowHeight()) {
			div.style.maxHeight = getWindowHeight()-70+"px";
		}
	}, 100);
	div.id = "fr_closeEdit";
	span.className = "close";
	span.innerHTML = trans.STOP_EDITMODE;
	
	span.onclick = function() { document.location.href = document.location.protocol+'//'+document.location.hostname+document.location.pathname+"?noedit=true"; }
	
	document.body.appendChild(div);
	
	var hidden_div = document.createElement("div");
	hidden_div.id = "_dialog";
	document.body.appendChild(hidden_div);
	
	makeRSSAndYouTube(this);
	var moveContentPic = false;
	var initmouse = {};
	
	var bg = $(".fr_editfield[contentpic] > img").css('backgroundImage');
	if(hasBGImg(bg)) {
		customizeContentPic(host, sessionid);
	}
	
	window.setInterval(function() {
		$("img[fr_editbutton]").each(function() {
			pos = getAbsoluteOffset(this);
			pos_parent = getAbsoluteOffset(this.parentNode);
			if(pos.y != pos_parent.y) $(this).css("top", pos_parent.y+"px");
		});
	}, 100);
	
	// Make Links Sortable
	var activeSortElm = null;
	$(".fr_editfield[editnav]").each(function() {
		$(this).parent().parent().attr("nid", $(this).attr("pid"));
	});
	$(".fr_editfield[editnav]").parent().parent().addClass("sort_connector");
	$(".fr_editfield[editnav]").parent().addClass("sortable");
	$(".sortable").parent().sortable({
		connectWith: '.sort_connector',
		placeholder: 'ui-state-highlight',
		items: "> .sortable",
		
		stop:function(event, ui) {
			var ids = new Array();
			
			$(ui.item[0].parentNode.getElementsByTagName("div")).each(function() {
				var nid = getFieldAttribute(this, "nid", "");
				if(nid != "") ids.push(nid);
			});
			
			var parent_id = getFieldAttribute(ui.item[0].parentNode, "nid", "");
			if(parent_id != "") {
				$.get("/data.php?get="+urlencode("/content/navigation/update/?nids="+ids.join(",")+"&submit_action=sort&parentid="+parent_id+"&sid="+sessionid));
			} else {
				return false;
			}
			activeSortElm = ui.item[0];
			activeSortElm.onclick = function() { return false; };
			window.setTimeout(function() { activeSortElm.onclick = function() {} }, 200); //Bug in jQuery?!?
		}
		
	}).disableSelection();
	
	// Haellt die Session am Leben. Gibt Warnung aus, wenn Session abgelaufen ist.
	var lifeholder = setInterval(function() {
		$.get("/data.php?get="+urlencode("/?session_in_life_received&sid="+sessionid), function(data) {
			if(data != "true" && data != "") {
				clearInterval(lifeholder);
				alert(trans.SESSIONTIMEOUT);
			}
		});
	}, 60000);
}

function replaceHost(str) {
	return str.replace(document.location.protocol+'//'+document.location.hostname, "");
}

function customizeContentPic(host, sessionid) {
	$(".fr_editfield[contentpic] > img").unselectable();
	$(".fr_editfield[contentpic] > img").each(function() {
		var zak = this.parentNode;
		addEditImageTag(zak, host);
		
		var div = document.getElementById("editimglayer");
		
		var saveImg = document.createElement("img");
		var deleImg = document.createElement("img");
		var chooImg = document.createElement("img");
		var br = document.createElement("br");
		
		saveImg.id = "saveimg_edit";
		saveImg.src = "/src/images/button_ok.gif";
		saveImg.style.padding = "5px";
		saveImg.style.background = "#fff";
		deleImg.id = "delete_edit";
		deleImg.src = "/src/images/folder_delete.png";
		deleImg.style.padding = "5px";
		deleImg.style.background = "#fff";
		chooImg.id = "choose_edit";
		chooImg.src = "/src/images/folder_edit.png";
		chooImg.style.padding = "5px";
		chooImg.style.background = "#fff";
	
		div.appendChild(br.cloneNode(false));
		div.appendChild(saveImg);
		div.appendChild(br.cloneNode(false));
		div.appendChild(deleImg);
		div.appendChild(br.cloneNode(false));
		div.appendChild(chooImg);
		
		saveImg.onclick = function(eventObject) {
			var img = this.parentNode.nextSibling;
			var path;
			var posi = img.style.backgroundPosition;
			var height = img.style.height;
			if(isNaN(height)) height = img.height+"px";
			
			try {
				path = img.style.backgroundImage.split('"')[1];
				if(typeof path == "undefined") throw new Exception();
			} catch(e) {
				try {
					path = img.style.backgroundImage.split("'")[1];
					if(typeof path == "undefined") throw new Exception();
				} catch(e) {
					try {
						path = img.style.backgroundImage.split("(")[1].split(")")[0];
						if(typeof path == "undefined") throw new Exception();
					} catch(e) {
						path = "";
					}
				}
			}
			
			$.get("/data.php?get="+urlencode("/content/navigation/save_custom_content_pic/?sid="+sessionid+"&path="+replaceHost(path)+"&height="+height+"&posi="+posi+"&url="+replaceHost(document.location.href)), function(data) {
				if(data == "true") {
					alert(trans.IMAGE_SAVED);
				} else {
					alert(trans.IMAGE_NOT_SAVED);
				}
			});
		}
		
		chooImg.onclick = function() {
			var img = this.parentNode.nextSibling;
			return clickEdit(host, img)
		}
		
		deleImg.onclick = function() {
			var img = this.parentNode.nextSibling;
			$.get("/data.php?get="+urlencode("/content/navigation/remove_custom_content_pic/?sid="+sessionid+"&url="+replaceHost(document.location.href)), function(data) {
				if(data == "true") {
					$.get("/?getcontentpic=1", function(data) {
						img.src = data;
						img.style.height = "200px";
						img.parentNode.style.height = "200px";
						img.style.background = "none";
						
						$(".fr_editfield[contentpic]").resizable("destroy");
						$(".fr_editfield[contentpic] > img").css('cursor', 'default');
						$(".fr_editfield[contentpic] > img").unbind("mousedown");
						addEditImageTag(zak, host);
						
						alert(trans.IMAGE_REMOVED);
					});
				} else {
					alert(trans.IMAGE_NOT_REMOVED);
				}
			});
		}
	});
	
	$(".fr_editfield[contentpic]").resizable({
		handles: 's',
		alsoResize: ".fr_editfield[contentpic] > img"
	});
	$(".fr_editfield[contentpic] > img").css('cursor', 'move'); 
	$(".fr_editfield[contentpic] > img").mousedown(function() {
		moveContentPic = this;
		var posi = this.style.backgroundPosition.split(" ");
		initmouse = {x: x, y:y};
		try {
			var p = {x: parseInt(posi[0]), y: parseInt(posi[1])};
			
			initmouse.x -= isNaN(p.x) ? 0 : p.x;
			initmouse.y -= isNaN(p.y) ? 0 : p.y;
		} catch(e) {
			//
		}
		
		$(document).mouseup(function() { 
			if(typeof moveContentPic == "object") {
				moveContentPic = false;
				$(this).unbind("mouseup");
			}
		});
		
		return false;
	});
	
	$(document).mousemove(function(e) {
		if(typeof moveContentPic == "object") {
			moveContentPic.style.backgroundPosition = (x-initmouse.x)+"px "+(y-initmouse.y)+"px";
			//console.log("%s", (x-initmouse.x)+"px "+(y-initmouse.y)+"px");
		}
	});
}

function makeRSSAndYouTube() {
	$("._rss, ._youtube, ._googlemaps").unbind("click");
	$("._rss .nix, ._youtube .nix, ._googlemaps .nix, .hoverelm .nix").remove();
	$("._rss, ._youtube, ._googlemaps, ._googlemaps > .hoverelm").each(function() {
		this.style.cursor = "pointer";
		
		var elm;
		if(this.className != "hoverelm") elm = this;
		else elm = this.parentNode;
		
		$(this).click(function() {
			$(elm).attr("contenteditable", "false");
			$("#_dialog").html("<img src='/src/images/loading_wh.gif' />");
			if(elm.className == "_rss") {
				editmenu.getRSSEditor(elm, document.getElementById('_dialog'));
				document.getElementById('_dialog').setAttribute("title", "RSS-Feed");
			} else if(elm.className == "_googlemaps") {
				editmenu.getGoogleMapsEditor(elm, document.getElementById('_dialog'));
				document.getElementById('_dialog').setAttribute("title", "Google Maps");
			} else {
				editmenu.getYouTubeEditor(elm, document.getElementById('_dialog'));
				document.getElementById('_dialog').setAttribute("title", "YouTube Video");
			}
			$("#_dialog").dialog({
				close: function() { 
					$(this).dialog("destroy");
				}
			});
			
			return false;
		});
		
		if(getFieldAttribute(elm, "url") == "") {
			var div = document.createElement("div");
			div.className = "nix";
			div.innerHTML = ".";
			elm.appendChild(div);
		}
	});
}

$(document).ready(function() {
	$("._rss").each(function() {
		$(this).attr("contenteditable", "false");
		var url = getFieldAttribute(this, "url");
		if(url != "") {
			rssbuilder = new ContentBuilder(this, url);
			rssbuilder.setMode(rssbuilder.MODE_RSS);
			rssbuilder.loadProperties();
			rssbuilder.build();
		}
	});
	
	$("._youtube").each(function() {
		$(this).attr("contenteditable", "false");
		var url = getFieldAttribute(this, "url");
		if(url != "") {
			rssbuilder = new ContentBuilder(this, url);
			rssbuilder.setMode(rssbuilder.MODE_YOUTUBE);
			rssbuilder.loadProperties();
			rssbuilder.build();
		}
	});
	
	$("._googlemaps").each(function() {
		$(this).attr("contenteditable", "false");
		var url = getFieldAttribute(this, "url");
		if(url != "" && getFieldAttribute(this, "street") != "" && getFieldAttribute(this, "zip") != "" && getFieldAttribute(this, "city")) {
			rssbuilder = new ContentBuilder(this, url);
			rssbuilder.setMode(rssbuilder.MODE_GOOGLEMAPS);
			rssbuilder.loadProperties();
			rssbuilder.param.height = "600";
			rssbuilder.build();
		}
	});
	
	// Fuegt Seitenumbrueche im Text ein
	if(typeof host == "undefined") {
		var contents = new Array();
		var ub = $("#content_lay .Seitenumbruch");
		var ub_active = 0;
		var ub_old = -1;
		var ij = 1;
		
		ub.each(function() {
			$(this).hide();
			
			$(this).append("<div>&nbsp;</div>");
			if(ij != 1) $(this).append("<a href='#' class='_lpage' style='cursor:pointer;float:left;padding-top:20px;'>&lt;&lt; "+trans.PREV_PAGE+"</a>");
			if(ij != ub.length) $(this).append("<a href='#' class='_npage' style='cursor:pointer;float:right;padding-top:20px;'>"+trans.NEXT_PAGE+" &gt;&gt;</a>");
			$(this).append("<div class='line'>&nbsp;</div>");
			
			ij++;
		});
		
		if(ij > 1 && typeof $(document).scrollTo == "undefined") {
			var scroll = document.createElement('script');
			scroll.type = 'text/javascript';
			scroll.src = "/src/js/plugins/jquery_plugins/jquery.scrollTo-min.js";
			var s = document.getElementsByTagName('script')[0];
			s.parentNode.insertBefore(scroll, s);
		}
		
		$("._npage, ._lpage").click(function() {
			if(this.className == "_npage") ub_active++;
			else ub_active--;

			document.location.hash = ub_active;
			return false;
		});
		
		if(ub.length > 0) {
			window.setInterval(function() {
				var ub_active_hash = parseInt(document.location.hash.replace("#", ""));
				if(ub_active_hash == "textstart" || ub_active_hash == "") ub_active_hash = 0;

				if(typeof ub_active_hash == "number" && !isNaN(ub_active_hash)) {
					if(ub_active_hash != ub_old) {
						$(ub).hide();
						//var c = document.location.href.split("#");
						var l = $("#content_lay h1:first");
						if(l.length == 0) l = $("#content_lay");

						$(ub[ub_active_hash]).show();
						ub_old = ub_active_hash;
						
						if(typeof $(document).scrollTo != "undefined") $(document).scrollTo(l);
					}
				}
			}, 10);
		}
		
		$(".Seitenumbruch:first").show();
	}
});

_usepopup = false;
function clickEdit(host, elm) {
	var attr = "";
	var str = "";
	
	if(elm.getAttribute("contentpic") != null) {
		str = host+"/content/website/contentpic"; // 2010-04-19 Schuster
	} else {
		if(elm.getAttribute("navid") != null) {
			attr = "nav_id="+elm.getAttribute("navid");
		} else if(elm.getAttribute("fieldname") != null) {
			attr = "fieldname="+elm.getAttribute("fieldname");
		}
		str = host+"/content/website/contenteditor?"+attr;
	}

	newWindow(str, 904, 652);
	
	return false;
}

function _submit_navigation(button) {
	button.disabled = true;
	var parts = Array();
	var template = document.getElementById('template').value;
	if(template == "") template = "text";
	parts.push("name="+document.getElementById('name').value);
	parts.push("template="+template);
	parts.push("parentid="+document.getElementById('parentid').value);
	parts.push("id="+document.getElementById('id').value);
	
	//document.location.href = href+"?"+parts.join("&");
	newWindow(host+"/account/navigation/?remote="+escape(document.location.protocol+'//'+document.location.hostname+document.location.pathname)+"&"+parts.join("&"), 904, 652);
}

function getWindowHeight() {
 	if (window.innerHeight) {
		return window.innerHeight;
	} else if (document.body && document.body.offsetHeight) {
		return document.body.offsetHeight;
	} else {
		return 0;
	}
}

$(document).ready(function() {
	if($("a[rel=bildergalerie]").length > 0) {
		$("a[rel=bildergalerie]").fancybox({
			'transitionIn'		: 'fade',
			'transitionOut'		: 'fade',
			'titlePosition' 	: 'over',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
		});
	}
});
