var toppanelbgcolor;
var paneltitel = "";
var panelDrag = false;

function getTitle()
{
    return paneltitel;
}
function getDrag()
{
    return panelDrag;
}

function bindtoolpicker(){
        $("a.toolpicker,li.tab a,li.activetab a").unbind();
   $("a.toolpicker,li.tab a,li.activetab a").click(function (){
         //Loss of scope
            var thref = $(this).attr("href");
              $("#formblockcontent").slideUp("normal",function(){ 
                     $.get(thref,{},function(result){
                       $("#formblockcontent").html(result);
                       $("#formblockcontent").slideDown();
                       $("li.activetab").addClass("tab");
                       $("li.activetab").removeClass("activetab");
                       $("a[href="+thref+"]").parent().addClass("activetab");
                       $("a[href="+thref+"]").parent().removeClass("tab");
                       bindtoolpicker();
                       });
                     
                      });
               return false;
               });

}

function usertools(){
	$("img.usertool").unbind();
	$("img.usertool").click(function(event){
		$.get("../ajax/smileypicker.php",{editorname:$(this).attr("alt")},function(result){
			$("#toolbox").html(result);
			$("#toolbox").css({top: (parseInt(event.pageY,10) - parseInt($("#toolbox").height(),10) - 15) + "px",left: (parseInt(event.pageX,10) +16 )+ "px"});
			$("#toolbox").fadeIn();
            $("body").one("click",function(){$("#toolbox").fadeOut();});
	});
});}

function hideadmin()
	{
        $("div.loginpanel").slideDown("normal");
        $("#toppanelcolorpicker").hide();
        $("#previewbox").hide();
        $("#notinvisible").fadeOut();
		$("#bigpopup").fadeOut();
		//patch for linkeditor being impossible to see over the editor
		$("#notinvisible").removeClass("linkeditor");
	}
function bindhints(){
	$("div.hint,span.hint,label[alt]").unbind();
	$("div.hint,span.hint,label[alt]").mouseover(function(event){
		var htmlval = $(this).attr('alt');
		$("#hintbox").html(htmlval);
		$("#hintbox").css("top",(event.pageY +20 ) + "px");
		$("#hintbox").css("left",(event.pageX +20 ) + "px");
		$("#hintbox").queue("fx",[]);
		$("#hintbox").show();
	});
	$("div.hint,span.hint,label[alt]").mousemove(function(event){
			var htmlval = $(this).attr('alt');
			$("#hintbox").css("top",(event.pageY +20 ) + "px");
			$("#hintbox").css("left",(event.pageX +20 ) + "px");
		});
	$("div.hint,span.hint,label[alt]").mouseout(function(event){
			$("#hintbox").hide();
		});
	}

$(function()
{
	var loc = window.location + "";
	var matches = loc.match(/^http:\/\/(www\.)?([^\/]*)/i);
	currentDomain = matches[2];
	$('a[href]').each(function(){
		var ref = $(this).attr('href');
		if(ref.match(/https?:\/\//i))
		{
			var matches = ref.match(/^https?:\/\/(www\.)?([^\/]*)/i);
			remoteDomain = matches[2];
			if(remoteDomain !== currentDomain)
			{
				$(this).attr('target','_blank');
			}
		}
	});
	$("div.guidetitel").click(function(){
		var nextguide = $(this).next();
		if($(nextguide).css("display") === "none")
		{
			$(nextguide).slideDown("fast");
		}
		else
		{
			$(nextguide).slideUp("fast");
		}
		$("div.guide").not(nextguide).slideUp("fast");
	});
	
    $("#contentedit").draggable({
        handle:$("#contentedit div.contentedit_header"),
        start: function(event,ui){
            $("#bigpopup").css("background-image","none");
            $("div.popuptitel").prev().css("background-image","url(/images/admin_grafik/modultopleftdrag.png)");
            $("div.popuptitel").next().css("background-image","url(/images/admin_grafik/modultoprightdrag.png)");
            $("div.popuptitel").css("background-image","url(/images/admin_grafik/layerheaderdrag.png)");
            $("div.popuptitel").css("background-color","transparent");
            $("div.popupheaderbg").css("background-color","#555555");
            $("#popupheader").prev().css("background-color","#555555");
            $("#tabmenu a").css("background-image","url(/images/admin_grafik/adminpaneltab.png)");
            $("#tabmenu li.activetab").children("a").css("background-image","url(/images/admin_grafik/adminpaneltab_active.png)");
            
            panelDrag = true;
            },
        stop: function(event,ui)
		{
            //$("div.popuptitel").css("background-color",toppanelbgcolor);
            panelDrag = false;
            $("div.popuptitel").prev().css("background-image","url(/images/admin_grafik/modultopleft.png)");
            $("div.popuptitel").next().css("background-image","url(/images/admin_grafik/modultopright.png)");
            $("div.popuptitel").css("background-image","url(/images/admin_grafik/layerheader.png)");
            $("#bigpopup").css("background-image","url(/images/admin_grafik/bg.png)");
            $("div.popupheaderbg").css("background-color","#bababa");
            $("#popupheader").prev().css("background-color","#bababa");
            $("#tabmenu a").removeAttr("style");
            $("#tabmenu li.activetab").children("a").removeAttr("style");
        }
        });
    $("#notinvisible.draggable").draggable({
        handle:$("div.popuptitel"),
        start: function(event,ui)
		{
            $("#bigpopup").css("background-image","none");
            $("div.popuptitel").prev().css("background-image","url(/images/admin_grafik/modultopleftdrag.png)");
            $("div.popuptitel").next().css("background-image","url(/images/admin_grafik/modultoprightdrag.png)");
            $("div.popuptitel").css("background-image","url(/images/admin_grafik/layerheaderdrag.png)");
            $("div.popuptitel").css("background-color","transparent");
            $("div.popupheaderbg").css("background-color","#555555");
            $("#popupheader").prev().css("background-color","#555555");
            $("#tabmenu a").css("background-image","url(/images/admin_grafik/adminpaneltab.png)");
            $("#tabmenu li.activetab").children("a").css("background-image","url(/images/admin_grafik/adminpaneltab_active.png)");
            
            panelDrag = true;
            },
        stop: function(event,ui)
		{
            //$("div.popuptitel").css("background-color",toppanelbgcolor);
            panelDrag = false;
            $("div.popuptitel").prev().css("background-image","url(/images/admin_grafik/modultopleft.png)");
            $("div.popuptitel").next().css("background-image","url(/images/admin_grafik/modultopright.png)");
            $("div.popuptitel").css("background-image","url(/images/admin_grafik/layerheader.png)");
            $("#bigpopup").css("background-image","url(/images/admin_grafik/bg.png)");
            $("div.popupheaderbg").css("background-color","#bababa");
            $("#popupheader").prev().css("background-color","#bababa");
            $("#tabmenu a").removeAttr("style");
            $("#tabmenu li.activetab").children("a").removeAttr("style");
        }
        });
    //$("div.popuptitel").corner("keep top 15px sc:#00000cc")
    $(".speech").mouseover(function(event){
    if($("#speech").css("display") === "none"){
        $("#speech").css({
            top:event.pageY,
            left:event.pageX}).fadeIn("fast");
        }else{
        $("#speech").css({
            top:event.pageY,
            left:event.pageX});    
        }
        $("#speech p.content").text("aloha");
    });

usertools();
$(document).keyup(function(event){
    if (event.keyCode === 27) {
        $("#viewer").fadeOut();
        hideadmin();
        $("#bigpoup").unbind();
    }
});
$("#previewknap").click(function(){
        var position = $(this).position();
        var offset = $(this).offset();
        $("#previewbox").css({
        left:(offset.left - 10),
        top:(offset.top + 23)
        });
        $("#toppanelcolorpicker").hide();
   $("#previewbox").toggle();     
});
$("ul.stickout a").click(function(){
        $("#previewselect").slideToggle("slow");
        return false;
});
$("#previewselect a").click(function(){
        $("#bigpopup").fadeIn();
        $.post("../ajax/sitepreview.php",{ mode : $(this).attr("href")},
               function(result){
                window.location.reload();
               }
               );
        $("#previewselect").slideUp();
        $("#ul.stickout a").text($(this).text());
        return false;
});
$("#panelcolor").click(function(){
        $("#previewbox").hide();
        var position = $(this).position();
        var offset = $(this).offset();
        $("#toppanelcolorpicker").css({
               // top:(position.top + 23),
                left:offset.left
				//alert("hello");
        });
        $("#toppanelcolorpicker").toggle();
        return false;
        });
$("#toppanelcolorpicker div.color").click(function(){
        $("div.toppanelwrapper").css({backgroundColor:$(this).css("backgroundColor")});
        $("div.hiddenpanel").css({backgroundColor:$(this).css("backgroundColor")});
        $("div.extrapanel").css({backgroundColor:$(this).css("backgroundColor")});
        $("#previewbox").css({backgroundColor:$(this).css("backgroundColor")});
        $("li.tab a").css({backgroundColor:$(this).css("backgroundColor")});
        $("li.activetab a").css({backgroundColor:$(this).css("backgroundColor")});
		var colortone;
        if($(this).hasClass("l")){
            colortone = "l";
        }
        else{
            colortone = "d";
        }
        $.post("/ajax/changepanelcolor.php",{color:$(this).css("backgroundColor"),colortone:colortone},function(){
            window.location.reload();
            });
        $("#toppanelcolorpicker").toggle();
        return false;
        });
$("a.adminlink").click(function(){
   $("#bigpopup").fadeIn();
   //$("a.activetablink").removeClass("activetablink");
  // $("a.tablink[href=" + $(this).attr("href") + "]").addClass("activetablink");
   $.get($(this).attr("href"),{},function(response){
      $("#tabmenu").html(response.menu);
      $("#formblockcontent").html(response.content);
      $("#notinvisible").fadeIn();
      bindtoolpicker();
	  if(toppanelshown)
	  {
		toppanel();
	  }
      },"json");
   return false;
});
$("a.tablink").click(function(){
   $("#bigpopup").fadeIn();
   $("a.activetablink").removeClass("activetablink");
   $(this).addClass("activetablink");
   $.get($(this).attr("href"),{},function(response){
      $("#tabmenu").html(response.menu);
      $("#formblockcontent").html(response.content);
      $("#notinvisible").fadeIn();
      bindtoolpicker();
      },"json");
   return false;
});
$("input").blur(function(){
	if($(this).val()===""){
		$(this).val($(this).attr("name"));
	}
});
$("input").focus(function (){
	if($(this).val()===$(this).attr("name")){
		$(this).val("");
	}
});
$("#bpreview").click(function (){
				$.post("../ajax/preview.php",{ttext : $("#tedit").val()},
				function(result){
					$("input.editorinput").slideToggle();
					$("#blogpreview").html(result);
					$("#editor").slideToggle();
					$("#blogpreview").slideToggle();
				});
				return false;
			});
$("#loadani").ajaxStart(function (){
        $(this).show();
                        });
$("#loadani").ajaxStop(function (){
        $(this).hide();
        if($.browser.msie){
                $("#bigpopup").queue(function(){
                                this.style.removeAttribute("filter");
                                $(this).dequeue();
                });
                $("#notinvisible").queue(function(){
                                this.style.removeAttribute("filter");
                                $(this).dequeue();
                });
        }
        });
bindhints();
});
var locked = false;
function registerlinks(){
bindhints();
	$("a.slider").click(function () {
		$(this).parent().next("div").toggle("slow");
		return false;
	});
	}
function blogedit(tid){
	$.get("../ajax/blograw.php",{postid : tid},function (result){
		$("#tpostid").val(tid);
		$("input[name=overskrift]").val(result.overskrift);
		if(window.dontclear === undefined)
		{
			$("#tedit").val(result.indhold);
		}
		$("input.editorknap[type=submit]").val("Gem");
		$("div.blogform,div.dagbog").slideDown();
	},"json");
	return false;
}
function opretbruger(){
	$("#bigpopup").fadeIn("slow");
        $("div.loginpanel").slideUp("normal");
	$.get("/ajax/opret.php",function(data){
		$("#formcontainer").html(data);
		$("#notinvisible").fadeIn();
		bindhints();
		pageTracker._trackPageview('/user_create_step1.bogus');
		});
	}
function updateMenu(item1,item2){
	$.post("../ajax/menuswap.php",{
		menu1 : item1,
		menu2 : item2
	},function (result){
		$("ul.bwnavigation").remove();
                $("div.counter").remove();
		$("div.verticalbar").prepend(result);
		bindArrows();
	});
}
var onclickthingie = "";
function editsidetext(fromlink,ttarget){
	$(fromlink).unbind();
	$.get("../ajax/edittext.php?query=load",{
		tlink : $(fromlink).attr("id")
		},
		function(result){
			//$(fromlink).parent().wrapInner("<div class='editarea'></div>");
			$("#"+ttarget).after(result);
			$("#"+ttarget).slideUp();
			$("#tedit").slideDown();
			$("#preview").unbind();
			$("#save").unbind();
			$("#save").show();
			$("#preview").show();
			$("#save").click(function(){
				var tid = $(this).attr("alt");
				save("tedit",tid,ttarget);
				return false;
				}
			);
			$("#preview").click(function (){
				$.post("../ajax/preview.php",{ttext : $("#tedit").val()},
				function(result){
					$("#" + ttarget).html(result);
					$("#editor").slideToggle();
					$("#" + ttarget).slideToggle();
				});
				return false;
			});
                        usertools();
                        $(fromlink).html("<img src='../images/BW_Grafik/alle/inline_fortryd.png' alt='Redigér' />");
			$(fromlink).attr("onclick","");
                        $(fromlink).toggle(function(){
                                $(fromlink).html("<img src='../images/BW_Grafik/alle/inline_rediger.png' alt='Redigér' />");
                                $("#save").slideUp();
                                $("#editfoot").slideUp();
                                $("#editor").slideUp();
                                $("#" + ttarget).slideDown();
                        },function(){
                                $(fromlink).html("<img src='../images/BW_Grafik/alle/inline_fortryd.png' alt='Fortryd' />");
                                $("#save").slideDown();
                                $("#editfoot").slideDown();
                                $("#editor").slideDown();
                                $("#" + ttarget).slideUp();
                                });
		});
	return false;
}
function save(what,tid,ttarget){
	$.post("../ajax/edittext.php?query=save",{
		newtext : $("#" + what).val(),
		orgid : tid
	},function(result){
                window.location.reload();
	});
}
function insertHere(who,tstart,tend){
	if (document.selection){
		who.focus();
		var sel = document.selection.createRange();
		sel.text = tstart + sel.text + tend;
	}
	else if (who.selectionStart !== undefined){
		var tem= who.value;
		var sPos = who.selectionStart;
		var ePos = who.selectionEnd;
		who.value = tem.substring(0, sPos)+ tstart + tem.substring(sPos,ePos) + tend + tem.substring(ePos);
		who.selectionStart= who.selectionEnd=sPos + tstart.length;
	}
}
function insertImage(who,tstart,tend){
	if (document.selection){
		who.focus();
		var sel = document.selection.createRange();
		sel.text = tstart + sel.text + tend;
	}
	else if (who.selectionStart !== undefined){
		var tem= who.value;
		var sPos = who.selectionStart;
		var ePos = who.selectionEnd;
		who.value = tem.substring(0, sPos)+ tstart + tem.substring(sPos,ePos) + tend + tem.substring(ePos);
		who.selectionStart= who.selectionEnd=sPos + tstart.length;
	}
	$("#bigpopup").fadeIn("slow",function(){
		$.post("../ajax/editor/insertimage.php",{
		teditval : $("#tedit").val(),
		loc : $("#tsid").val(),
		postid : $("#tpostid").val(),
                w : 400,
                h : 300
		},function(result){
                        $("#tabmenu").html("<li class='activetab'><a href='#'>Inds&aelig;t billede</a></li>");
			$("#formblockcontent").html(result);
			$("#notinvisible").fadeIn();
		});
	});
}
var origLeft;
var origSel;
function insertLink(ttarget){
        $("#bigpopup").fadeIn("slow");
		if($.browser.msie)
		{
			origSel = document.getElementById( ttarget ).contentWindow.document.selection.createRange();
		}
        $.post("/ajax/editor/insertlink.php?dest=ext",{},function(result){
$("#tabmenu").html("<li class='activetab'><a href='../ajax/editor/insertlink.php?dest=ext'>Extern</a></li><li class='tab'><a href='../ajax/editor/insertlink.php?dest=int'>Intern</a></li><li class='tab'><a href='../ajax/editor/insertlink.php?dest=doc'>Documents</a></li>");
                $("#formblockcontent").html(result);
				$("#notinvisible").addClass("linkeditor");
				origLeft = $("#contentedit").css('left');
				$("#contentedit").css('left',-2000);
				$("#notinvisible").find("img[alt=luk]").click(function(){
					$("#notinvisible").removeClass("linkeditor");
					$("#contentedit").css('left',origLeft);
					});
                $("#notinvisible").fadeIn();
                bindtoolpicker();
                });
		return false;
}
function skiftbillede(tid,ttype,w,h){
	$("#bigpopup").fadeIn("slow",function(){
		$.post("../ajax/editor/insertimage.php",{
		ttid : tid,
		tttype : ttype,
                w : w,
                h : h
		},function(result){
                        $("#tabmenu").html("<li class='activetab'><a href='#'>Skift billede</a></li>");
			$("#formblockcontent").html(result);
			$("#notinvisible").fadeIn();
		});
	});
}
/*function getUserTool(event,page,params){
	$.get(page,params,function(result){
		$("#toolbox").html(result);
		$("#toolbox").css("top", (event.pageY - $("#toolbox").height() - 15) + "px");
		$("#toolbox").css("left", (event.pageX +16 )+ "px");
		$("#toolbox").fadeIn();
	});
}*/


function loadToAdminLayer(url){
                        $("#formcontainer").load(url,function(){
                            $("#bigpopup").fadeIn();
                            $("#notinvisible").fadeIn();
                            $("#lukopretknap").parent().attr("alt","Luk");
                            $("div.loginpanel").slideUp("normal");
                        });
                        return false;
}
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j+=1) level_padding += "    ";
	
	if(typeof(arr) === 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) === 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
/*
 Loads a wysiwyg with the proper text id
 */
function loadToContentEdit(url,params,title){
    paneltitel = title;
    $("#bigpopup").fadeIn();
    $.post(url,params,function(response)
    {
        $("#contentedit div.contentedit_center").html(response);
        $("#contentedit").fadeIn();
        var width = $("#contentedit div.contentedit_center").children("div").eq(0).width();
        if(width < 400){
            width = 400;
        }
        $("#contentedit").css("width",width+40);
        $("#contentedit div.center").css("width",(width+18));
        width = $("#bigpopup").width();
        var cwidth = $("#contentedit").width();
        $("#contentedit").css("left",(width-cwidth)/2);
    }
    );
	return false;
}
function wysiwyg(id,type,flags,saveurl)
{
    paneltitel = "Redigér";
    $("#bigpopup").fadeIn();
	var editorconf = {
	id:id,
	type:type,
	flags:flags
		  };
	if(typeof saveurl !== "undefined")
	{
		editorconf.saveurl = saveurl;
	}
    $.post("/ajax/editor/editlong.php",editorconf,function(response){
	$("#contentedit div.contentedit_center").html(response);
	$("#contentedit").fadeIn();
	var width = $("#contentedit div.contentedit_center").children("div").eq(0).width();
	$("#contentedit").css("width",width+40);
	$("#contentedit div.center").css("width",(width+18));
	width = $("#bigpopup").width();
	var cwidth = $("#contentedit").width();
	$("#contentedit").css("left",(width-cwidth)/2);
	});
    return false;
}
function forumwysiwyg(id,type,flags)
{
	if(type === "new")
	{
	    paneltitel = "Opret forumindlæg";
	}
	else
	{
	    paneltitel = "Svar på forumindlæg";
	}
    $("#bigpopup").fadeIn();
	$.post("/ajax/editor/editforum.php",{
		id:id,
		type:type,
		flags:flags
		},function(response){
			$("#contentedit div.contentedit_center").html(response);
			$("#contentedit").fadeIn();
			var width = $("#contentedit div.contentedit_center").children("div").eq(0).width();
			$("#contentedit").css("width",width+40);
			$("#contentedit div.center").css("width",(width+18));
			width = $("#bigpopup").width();
			var cwidth = $("#contentedit").width();
			$("#contentedit").css("left",(width-cwidth)/2);
		});
}

function get_selected_element()
{
	var sel;
	if($.browser.msie)
	{
		var type = document.getElementById( "editor" ).contentWindow.document.selection.type;
		if(type === "Text")
		{
			sel = document.getElementById( "editor" ).contentWindow.document.selection.createRange().parentElement();
		}
		else
		{
			sel = document.getElementById( "editor" ).contentWindow.document.selection.createRange().item(0);
		}
	}
	else if($.browser.mozilla)
	{
		var startsel = document.getElementById( "editor" ).contentWindow.getSelection();
		var range = startsel.getRangeAt(0);
		if(range.endOffset-range.startOffset === 1)
		{
			var tempwrap = document.createElement("p");
			range.surroundContents(tempwrap);
			sel = $(tempwrap).children()[0];
			$(tempwrap).replaceWith(sel);
			startsel.removeAllRanges();
			range.selectNode(sel);
			startsel.addRange(range);
		}
		else
		{
			sel = $(startsel.startContainer).parent()[0];
		}
	}
	return sel;
}

