var definitioncategorylist = new Array();
definitioncategorylist = {"shortstring":"Short String",
						"html":"HTML",
						"longstring":"Long String",
						"number":"Number",
						"yesno":"YES / NO",
						"date":"Date",
						"dropdown":"Dropdown",
						"controllerdropdown":"Controller Dropdown",
						"pagedropdown":"Page Dropdown",
						"file":"File",
						"image":"Image",
						"list":"List",
						"folder":"Folder",
						"dbtable":"Table",
						"dbdropdown":"DB Dropdown",
						"userdropdown":"User Dropdown"};

var radeditorlist = new Array();

function myhash(iframeid_, valueid_)
{
	this.iframeid = iframeid_;
	this.valueid = valueid_;
}

function registerradeditor(iframeid, valueid)
{
	radeditorlist.push(new myhash(iframeid, valueid));
	setradeditorvalue(iframeid, valueid);
}
function gethtml()
{
	for (var i=0; i < radeditorlist.length; i++)
		getradeditorvalue(radeditorlist[i].iframeid, radeditorlist[i].valueid);
	if (typeof SaveMCEEditors == "function")
		SaveMCEEditors();
	if (typeof DestroyMCEEditors == "function")
		DestroyMCEEditors();
	return true;
}

function getradeditorvalue(iframeid, valueid)
{
	if ($(valueid) != null) {
		var editoriframe = $(iframeid).contentWindow;
		var editor = editoriframe.GetRadEditor("editor1");

		// get the text
		var content = "";
		if (editor.badeditor)
			content = editoriframe.document.getElementById('badeditor').value;
		else
			content = editor.GetHtml();

		$(valueid).value = cleanHTML(content);
	}
	//else
	//	alert("Could not find textarea for content value; id was " + valueid);
}
// cleanHTML(content)
// this was pulled out of getradeditorvalue so that it could be used for
// tinymce, as well as the radeditor
function cleanHTML(content)
{
	// UNprotect object, script and param tags from the MSIE editor destroying them
	content = content.replace(/<(\/*)[Xx](object)/gi, "<$1$2");			//*/
	content = content.replace(/<(\/*)[Xx](param)/gi, "<$1$2");			//*/
	content = content.replace(/<(\/*)[Xx](link)/gi, "<$1$2");			//*/
	content = content.replace(/<(\/*)[Xx](title)/gi, "<$1$2");			//*/
	content = content.replace(/<(\/*)[Xx](form)/gi, "<$1$2");			//*/

	// note sitehost() is of the form 'http://xyz' (dunno why) ... figure out absolute and slash-ended virtual directory under it
	// tilde gets autoconverted to virtdir name when it's read
	var virtdir = "~/";

	// convert in-attribute %7E into ~
	content = content.replace(new RegExp('(=["\']*)%7e%7e', "gi"), 	unescape('$1%7e%7e'));
	content = content.replace(new RegExp('(=["\']*)%7e', 	"gi"), 	unescape('$1%7e'));
	// convert in-page anchor (#) urls into correct behavior
	content = content.replace(new RegExp('(=["\']*)'+sitehost()+virtdir+'RadControls/content.aspx.*(#)', "gi"), '$1$2');
	// convert tilde (~) urls or relative urls into correct behavior
	content = content.replace(new RegExp('(=["\']*)'+sitehost()+virtdir+unescape('RadControls/([^"\'])'), "gi"), '$1$2');
	// convert remaining absolute urls into absolute paths with tilde
	content = content.replace(new RegExp('(=["\']*)'+sitehost()+virtdir, "gi"), unescape('$1%7e/'));
	// convert absolute paths on this site into absolute paths with tilde
	content = content.replace(new RegExp('(=["\']*)'+virtdir, "gi"), unescape('$1%7e/'));

	return content;
}
function setradeditorvalue(iframeid, valueid)
{
	if ($(valueid) != null) {
		var editoriframeobj = $(iframeid);
		var editoriframe = $(iframeid).contentWindow;
		var editor = editoriframe.GetRadEditor("editor1");
		var newval = $(valueid).value;

		// change the default indent character from 3 dots to a tab
		editoriframe.o2t = "\t"; // indent string
		editoriframe.l2s = "\t"; // char to remove when un-indenting

		// detect layout-type tags, and switch to a more conservative mode
		if (newval.match(/<(\/*)(html)/i) || newval.match(/<(\/*)(body)/i) || newval.match(/<(\/*)(style)/i) || newval.match(/<(\/*)(script)/i)) {
			//$(iframeid).document.getElementById('gooddiv').style.display = "none";	//*/
			editoriframe.document.getElementById('gooddiv').style.display = "none";		//*/
			editoriframe.document.getElementById('baddiv').style.display = "";			//*/
			editoriframe.document.getElementById('badeditor').value = newval;			//*/

			editor.badeditor = true;
		}
		else {
			editoriframe.document.getElementById('baddiv').style.display = "none";
			editoriframe.document.getElementById('gooddiv').style.display = "";
			// convert absolute paths in the content into tilde paths
			try
			{	newval = newval.replace(new RegExp('(=["\']*)'+unescape('%7e/'), "gi"), '$1~/');
			}catch(e){}

			editor.SetHtml(newval);
			editor.badeditor = false;
			editor.isfullscreen = false;

			// hook in our event handler so we can watch for the fullscreen command
			editor.OnClientCommandExecuting = function(editor, commandName, oTool) {
				if (commandName == "ToggleScreenMode" && (oTool || XWebMenu.User.Ie)) {

					if (editor.isfullscreen) {
						editor.isfullscreen = false;
						editoriframeobj.style.zIndex = editoriframeobj.oldzIndex;
						editoriframeobj.style.position = editoriframeobj.oldposition;
						editoriframeobj.style.top = editoriframeobj.oldtop;
						editoriframeobj.style.left = editoriframeobj.oldleft;
						editoriframeobj.style.width = editoriframeobj.oldwidth;
						editoriframeobj.style.height = editoriframeobj.oldheight;
					}
					else {
						editor.isfullscreen = true;
						editoriframeobj.oldzIndex = editoriframeobj.style.zIndex;
						editoriframeobj.style.zIndex = 10000;

						editoriframeobj.oldposition = editoriframeobj.style.position;
						editoriframeobj.style.position = "absolute";

						editoriframeobj.oldtop = editoriframeobj.style.top;
						editoriframeobj.style.top = 0;

						editoriframeobj.oldleft = editoriframeobj.style.left;
						editoriframeobj.style.left = 0;

						editoriframeobj.oldwidth = editoriframeobj.style.width;
						editoriframeobj.style.width = document.body.clientWidth;

						editoriframeobj.oldheight = editoriframeobj.style.height;
						editoriframeobj.style.height = document.body.clientHeight;
					}
				}
				else {
					//alert('got event: EDITOR:\n' + props(editor) + '\nEND EDITOR\ncommandname=' + commandName + "\nTOOL:\n" + props(oTool) + "\nEND TOOL");
				}
				return true;
			}
		}


	}
	//else
	//	alert("Could not find textarea for content value; id was " + valueid);

}


function props(e)
{
  var ns = ["Methods", "Fields", "Unreachables"];
  var as = [[], [], []]; // array of (empty) arrays of arrays!
  var p, j, i; // loop variables, several used multiple times

  var protoLevels = 0;

  for (p = e; p; p = p.__proto__)
  {
    for (i=0; i<ns.length; ++i)
      as[i][protoLevels] = [];
    ++protoLevels;
  }

  for(var a in e)
  {
    // Shortcoming: doesn't check that VALUES are the same in object and prototype.

    var protoLevel = -1;
    try
    {
      for (p = e; p && (a in p); p = p.__proto__)
        ++protoLevel;
    }
    catch(er) { protoLevel = 0; } // "in" operator throws when param to props() is a string

    var type = 1;
    try
    {
      if ((typeof e[a]) == "function")
        type = 0;
    }
    catch (er) { type = 2; }

    as[type][protoLevel].push(a);
  }

  function times(s, n) { return n ? s + times(s, n-1) : ""; }

  var output = "";
  for (j=0; j<protoLevels; ++j)
    for (i=0;i<ns.length;++i)
      if (as[i][j].length)
        output += ns[i] + times(" of prototype", j) + " -- " + as[i][j].join(", ") + "\n";
  return output;
}



function addcontexttimed(type, objid, objid2, isOldSS)
{
	var context = new XWebMenu.Context();
	var obj = $(objid);
	var img = $("image-" + objid);

	var attach = true;

	var parentvaluetype = "";
	if (type != null && type.match(/config_/))
	{
		parentvaluetype = type.replace(/config_/, "");
		type = "config";
	}
	if (type != null && type.match(/definition_/))
	{
		parentvaluetype = type.replace(/definition_/, "");
		type = "definition";
	}

	if (type == "sitemap" || type == "sitemapwithsubpage")
	{
		if (isOldSS)
		{
			var s=obj.getAttribute('url');
			context.Add("View", "location.href='/aspadministration/browse.asp?p=" + s.substring(1,s.length-1).replace(/\//gi,":") + "';",0,0);
		}else
		{
			context.Add("View", "location.href='~/" + obj.getAttribute('url').substring(1) + "';",0,0);
		}

		// in general, page-edit links go to page/[verb], which does an internal render of page/[verb]int/index on the right side
		var url = "~/administration/page/edit/" + obj.getAttribute('url');
		var editpageurl = url;
		if (obj.getAttribute('defaultaction') != null && obj.getAttribute('defaultaction') != "") {
			editpageurl = "~/administration/page/" + obj.getAttribute('defaultaction') + "/" + obj.getAttribute('url');
		}
		context.Add("Edit this Page", "location.href='" + editpageurl + "';",0,0);

		url = "~/administration/page/addpage/" + obj.getAttribute('url');
		var ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true});";
		if (isOldSS)
		{	var s=obj.getAttribute('url').replace("/aspadministration/browse.asp?p=","");
			ajax="run_old_ss_new('"+s+"')";
		}
		context.Add("Add Subpage", ajax,0,0);

		url = "~/administration/page/removepage/" + obj.getAttribute('url');
		ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true,evalScripts:true});";
		context.Add("Remove this Page", ajax,0,0);

		url = "~/administration/page/copypage/" + obj.getAttribute('url');
		ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true});";
		context.Add("Copy this Section", ajax,0,0);

		url = "~/administration/page/inheritpage/" + obj.getAttribute('url');
		ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true});";
		context.Add("Inherit from this Page", ajax,0,0);

		url = "~/administration/page/history/" + obj.getAttribute('url');
		context.Add("Page History", "location.href='" + url + "';",0,0);

		url = "~/administration/page/publish/" + obj.getAttribute('url');
		context.Add("Publishing and Workflow", "location.href='" + url + "';",0,0);

		url = "~/administration/page/security/" + obj.getAttribute('url');
		context.Add("Page Security", "location.href='" + url + "';",0,0);

		// new reordering calls
		url = "~/administration/page/movepage/up," + obj.getAttribute('url');
		//var ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true});";
		context.Add("Move Up", "location.href='" + url + "';",0,0);

		url = "~/administration/page/movepage/down," + obj.getAttribute('url');
		//var ajax = "new Ajax.Updater('subpage', '" + url + "', {asynchronous:true});";
		context.Add("Move Down", "location.href='" + url + "';",0,0);
		
		// color flagging
		context.Add("Flag", 0, 0, "flagSubMenu");
		context.flagSubMenu.Add("None", "setflagcolor('none', '" + obj.getAttribute('url') + "', '" + img.id + "' );", "~/administration/layouts/tree/page.gif", 0);
		context.flagSubMenu.Add("Red", "setflagcolor('red', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_red.gif", 0);
		context.flagSubMenu.Add("Blue", "setflagcolor('blue', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_blue.gif", 0);
		context.flagSubMenu.Add("Yellow", "setflagcolor('yellow', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_yellow.gif", 0);
		context.flagSubMenu.Add("Green", "setflagcolor('green', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_green.gif", 0);
		context.flagSubMenu.Add("Orange", "setflagcolor('orange', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_orange.gif", 0);
		context.flagSubMenu.Add("Purple", "setflagcolor('purple', '" + obj.getAttribute('url') + "', '" + img.id + "' );","~/administration/layouts/tree/page_purple.gif", 0);
	}
	else if (type == "usermap-user")
	{
		context.Add("Search","location.href='"+obj.getAttribute('url')+"';",0,0);
	}
	else if (type == "usermap-domain")
	{
		context.Add("Search","location.href='"+obj.getAttribute('url')+"';",0,0);
	}
	else if (type == "usermap-role")
	{
		context.Add("Search","location.href='"+obj.getAttribute('url')+"';",0,0);
	}
	else if (type == "definition")
	{
		context.Add("Edit", obj.onclick.toString() + ";anonymous()",0,0);
	}
	else if (type == "config")
	{
		context.Add("Edit", obj.onclick.toString() + ";anonymous()",0,0);
		if (parentvaluetype == "list")
		{
			context.Add("Move", 0, 0, "moveSubMenu");
			context.moveSubMenu.Add("Up", obj.getAttribute("moveup").toString(), 0, 0);
			context.moveSubMenu.Add("Down", obj.getAttribute("movedown").toString(), 0, 0);
			context.moveSubMenu.Add("To Beginning", obj.getAttribute("movetobeginning").toString(), 0, 0);
			context.moveSubMenu.Add("To End", obj.getAttribute("movetoend").toString(), 0, 0);
			context.Add("Clone", obj.getAttribute("clone").toString(), 0, 0);
			context.Add("Remove", obj.getAttribute("remove").toString(), 0, 0);
		}
	}
	else if (type == "configcategory")
	{
		//context.Add("Toggle", obj.onclick.toString() + ";anonymous()", 0,0);
		attach = false;
	}
	else if (type == "definitioncategory")
	{
		var url = "~/administration/page/editor/editdefinition/?valuetype=[type]&controllerpath=" + location.href.replace(fullsiteroot(), "").replace(/administration\/page\/\/?editdefinition\/?(\/)/, "$1").replace(/\?.*/,"") + "&category=" + obj.getAttribute('displayname');
		var ajax = "new Ajax.Updater('divedit', '" + url + "', {asynchronous:true,evalScripts:true});";
		//context.Add("Toggle", obj.onclick.toString() + ";anonymous()",0,0);
		context.Add("New",0,0,"contextnew");
		for(var keytype in definitioncategorylist) {
			context.contextnew.Add(definitioncategorylist[keytype], ajax.replace(/\[type\]/,keytype), 0, 0);
		}
	}
	else
	{
		attach = false;
	}

	if (attach)
	{
		context.Attach(obj);
		context.Attach($(objid2));
	}
}

var _queue = new Array();
function add_to_queue(command)
{
	_queue[_queue.length] = command;
}

function execute_and_clear_queue()
{
	var i = 0;
	for (i = 0; i < _queue.length; i++)
		eval(_queue[i]);

	_queue = new Array();
	setTimeout("execute_and_clear_queue()", 1000);
}

// call this function ... it will call the others
function addcontext(type, objid, objid2, isOldSS)
{
	// MSIE needs a longer retry
	if (XWebMenu.User.Moz)
		setTimeout("addcontexttimed('" + type + "', '" + objid + "', '" + objid2 + "', "+isOldSS+")", 100);
	else
		setTimeout("addcontexttimed('" + type + "', '" + objid + "', '" + objid2 + "', "+isOldSS+")", 800);
}

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue) + ";path=/;expires="+expire.toGMTString();
}

var cookieutils = {
	set:function(c_name,value)
	{
		var now = new Date();
		var expires = new Date(now.getFullYear()+1, now.getMonth(), now.getDate());
		document.cookie = c_name + "=" + escape(value) + ";path=/;domain=" + document.domain + ";expires=" + escape(expires.toGMTString()) + ";";



	},
	get:function(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return null;
	},
	remove:function(c_name) {this.set(c_name,"",-1);}
}




function setflagcolor(color, url, img, panel){
	if(!panel){
		var params = 'imageid=' + img + "&color=" + color + "&url=" + url;
	}else{
		var params = 'imageid=' + img + "&color=" + color + "&url=" + url + "&page=panel";
	}
	var myAjax = new Ajax.Request( "~/administration/page/setcolorflag/",
									{ method: 'post',
									parameters: params,
									onComplete: setflagcolorresponse }
								);
}

function setflagcolorresponse(originalRequest){
	var text = String(originalRequest.responseText);
	var response = text.replace(/^(.|\n\r)*?##(.*?)##(.|\n|\r)*$/m, "$2");
	if(! (response.match('success'))){
		alert(originalRequest.responseText);
		return;
	}
	// eval the text which will be like: "var colorobj = {success: true, color: somecolor, imageid: someid}"
	eval(response);
	var image = $(colorobj['imageid']);
	if(image){
		if(colorobj['panel']){
			var color = colorobj['color'];
			if(color == "")
				color = "no";
			image.src =  (String(image.src).replace(/[^\/]*$/, color + "_flag.gif") );
		}else{
			image.src = "/administration/layouts/tree/page" + colorobj['color'] + ".gif";
		}
	}else{
		alert('Error: could not find image: ' + colorobj['imgid']);
	}
}


