
//var restorePoint;
//var thiseditor = window.GetRadEditor("editor1");



function DisplaySearch(searchtext)
    {
    //Show the search results window with the loading animation
    document.getElementById("spansearchresults").innerHTML = "<table style='width:100%;height:100%'><tr><td align='center'><img src='../_engine/images/loading.gif'><br><br>Searching...</td></tr></table>"
    //hide Contents
    document.getElementById("TreeView1").style.display="none";
    //hide properties window
    document.getElementById("spanproperties").style.display="none";
    document.getElementById("TreeView1").style.height="100%";
    //hide index
    document.getElementById("spanindex").style.display="none";
    document.getElementById("spanindex").innerHTML = "";
    //show the search results window
    document.getElementById("spansearchresults").style.display="";
    //Change the contents heading (if the control exists)
   	if (document.getElementById("tdcontentslabel") != null)
   	    {
   	    //document.getElementById("tdcontentslabel").innerHTML="Search Results";
   	    document.getElementById("tdcontentslabel").style.display="none";
   	    document.getElementById("tdindexlabel").style.display="none";
   	    document.getElementById("tdsearchresultslabel").style.display="";
   	    }
    //hide the contents controls
   	if (document.getElementById("tdcontentscontrols") != null)
   	    {
        document.getElementById("tdcontentscontrols").style.display="none";
   	    }
    //Show the close icon
   	if (document.getElementById("tdCloseContentsWindow") != null)
   	    {
   	    document.getElementById("tdCloseContentsWindow").style.display="";
   	    if (document.getElementById("tdeditcontents") != null) {document.getElementById("tdeditcontents").style.display="none"}
   	    }
   	if (document.getElementById("txtAdvancedSearch") != null)
   	    {
   	    //alert("advanced search textbox displayed")
   	    document.getElementById("txtAdvancedSearch").focus();
   	    }

    //If the contents window is hidden then show it now
    //if (document.getElementById("td_contents_hidden") != null)
    if (document.getElementById("td_contents_hidden") != null && document.getElementById("tdcontentscontrols") == null)
        {
        document.getElementById("td_contents_hidden").style.display="";
        document.getElementById("td_main_visible").style.display="none";
   	    document.getElementById("tdCloseContentsWindow").style.display="none";
        window_resize();
        }

    //Get search results index using AJAX
	var http = false; 
    var reqstring = "action=search";
    reqstring = reqstring + "&searchtext="+searchtext;
    reqstring = reqstring + "&projectname="+GetProjectName();
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;

    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else  {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //show the search results
                //alert("http.responseText = " + http.responseText);
                document.getElementById("spansearchresults").innerHTML = http.responseText;
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/ajaxaction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //http.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

    http.send(reqstring);
    
    }

function DisplayIndex()
	{
    //Show the index window with the loading animation
    document.getElementById("spanindex").innerHTML = "<table style='width:100%;height:100%'><tr><td align='center'><img src='../_engine/images/loading.gif'><br><br>Loading Index...</td></tr></table>"
	//hide contents, properties and search windows
    document.getElementById("TreeView1").style.display="none";
    document.getElementById("spanproperties").style.display="none";
    document.getElementById("TreeView1").style.height="100%";
    document.getElementById("spansearchresults").style.display="none";
    document.getElementById("spansearchresults").innerHTML = "";
    //show the index window
    document.getElementById("spanindex").style.display="";
    //Change the contents label (if the control exists)
   	if (document.getElementById("tdcontentslabel") != null)
   	    {
   	    //document.getElementById("tdcontentslabel").innerHTML="Index";
   	    document.getElementById("tdcontentslabel").style.display="none";
   	    document.getElementById("tdindexlabel").style.display="";
   	    document.getElementById("tdsearchresultslabel").style.display="none";
   	    }
    //hide the contents controls
   	if (document.getElementById("tdcontentscontrols") != null)
   	    {
        document.getElementById("tdcontentscontrols").style.display="none";
   	    }
    //Show the close icon
  	if (document.getElementById("tdCloseContentsWindow") != null)
   	    {
   	    document.getElementById("tdCloseContentsWindow").style.display="";
   	    //document.getElementById("tdeditcontents").style.display="none";
   	    }
	//alert("txtactiveusername = "+document.getElementById("txtactiveusername").value);

    //If the contents window is hidden then show it now
    if (document.getElementById("td_contents_hidden") != null)
        {
   		document.getElementById("td_contents_hidden").style.display="";
 	    document.getElementById("td_main_visible").style.display="none";
   	    window_resize();
        }

	
	//Get the index using AJAX
	var http = false;
    var reqstring = "action=index";
    reqstring = reqstring + "&projectname="+GetProjectName();
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else  {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //show the index content
                document.getElementById("spanindex").innerHTML = http.responseText;
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/ajaxaction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    
	
	}

function SearchKeyPress(searchtext,e)
	{
    var key;
	if(window.event)
		{
		key = window.event.keyCode;     //IE
		}
	else
		{
		key = e.which;     //firefox
		}

	if(key == 13)
		{
		DisplaySearch(searchtext)
		return false;
		}
	else
		{
		return true;
		}
	}

function DisplayContents()
	{
	//hide the index window
    document.getElementById("spanindex").innerHTML = "";
    document.getElementById("spanindex").style.display="none";
    //hide the search window
    document.getElementById("spansearchresults").innerHTML = "";
    document.getElementById("spansearchresults").style.display="none";
    //show the contents window
    document.getElementById("TreeView1").style.display="";
    if (document.getElementById("tdcontentscontrols") != null) 
        {
        document.getElementById("tdcontentscontrols").style.display="";
        }
    //Change the contents label (if the control exists)
   	if (document.getElementById("tdcontentslabel") != null)
   	    {
   	    //document.getElementById("tdcontentslabel").innerHTML="Contents";
   	    document.getElementById("tdcontentslabel").style.display="";
   	    document.getElementById("tdindexlabel").style.display="none";
   	    document.getElementById("tdsearchresultslabel").style.display="none";
   	    document.getElementById("tdCloseContentsWindow").style.display="none";
   	    }
	}


function ShowTools(projectname,formname,skin)
    {
    //alert("form name = "+formname);
    var formurl="";
    //Determine which tools form will be displayed
    if (formname == "skineditor")
        {
        formurl = "editor.aspx?calledfrom=project&skin="+skin;
        document.getElementById("tblDialogWindow").style.width="100%"
        document.getElementById("tblDialogWindow").style.height="100%"
        //Show the expand icon
        document.getElementById("imgexpandform").style.display = "none";
        document.getElementById("imgretractform").style.display = "";
        }
    else
        {
        formurl = "../_engine/tools.aspx?projectname="+projectname
        document.getElementById("tblDialogWindow").style.width="700px"
        document.getElementById("tblDialogWindow").style.height="540px"
        //Show the expand icon
        document.getElementById("imgexpandform").style.display = "";
        document.getElementById("imgretractform").style.display = "none";
        }
        
    //window.open("tools.aspx", "frame_page")
    //document.getElementById("frame_page").src="../_engine/tools.aspx?projectname="+projectname
    //document.getElementById("tddialog").innerHTML = "<iframe src='../_engine/tools.aspx?projectname="+projectname+"' style='width:700px;height:500px' frameborder=0 allowTransparency=true></iframe>"
    //document.getElementById("tddialog").innerHTML = "<iframe id='frame_tools' src='../_engine/tools.aspx?projectname="+projectname+"' style='width:100%;height:100%' frameborder=0></iframe>"
    document.getElementById("tddialog").innerHTML = "<iframe id='frame_tools' src='" + formurl + "' style='width:100%;height:100%' frameborder=0></iframe>"
    document.getElementById("tbldialog").style.display = ""
    document.getElementById("divtransparency").style.display = ""
    document.getElementById("spanheading").innerHTML = "Tools"
    document.getElementById("imgcloseform").style.display = ""
    //wopen("../_engine/tools.aspx?projectname="+projectname,"popup",700,500);

    }

function ShowPublish(projectname)
    {
    //document.getElementById("tddialog").innerHTML = "<table style='width:100%;height:100%'><tr><td align=center><img src='../_engine/images/loading.gif'></td></tr></table>"
    document.getElementById("tddialog").innerHTML = "<iframe id='frame_tools' src='../_engine/publish.aspx?projectname="+projectname+"' style='width:100%;height:100%' frameborder=0></iframe>"
    document.getElementById("tblDialogWindow").style.width="600px"
    document.getElementById("tblDialogWindow").style.height="475px"
    document.getElementById("spanheading").innerHTML = "Publish"
    document.getElementById("imgcloseform").style.display = ""
    document.getElementById("tbldialog").style.display = ""
    document.getElementById("divtransparency").style.display = ""
    
    //window.open("publish.aspx", "frame_page")
    //document.getElementById("frame_page").src="../_engine/publish.aspx?projectname="+projectname
    //wopen("../_engine/publish.aspx?projectname="+projectname,"popup",700,500);
    }

function wopen(url, name, w, h)
{
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=yes, resizable=yes');
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
}


function Timer()
    {
    //alert("timer");
    ReportActivePage();
    //Call this function every 30 seconds
	timerID = setTimeout("Timer()", 30000);
    }



function ReportActivePage()
    {
    //alert("reportactivepage");
    //alert("Project = " + GetProjectName())
    //alert("editor display = " + document.getElementById("diveditor").style.display);
    var reqstring = "";
    //If the contents or a page is being edited, report it to the server to prevent other authors from being able to edit it.
    //determine if contents is being edited
    if (document.getElementById("tdcontentscontrols") != null)
        {
	    reqstring = reqstring + "&activecontents=true"; 
        }
    
    //determine if page is being edited
    if (document.getElementById("txteditid").value != "" && document.getElementById("diveditor").style.display == "")
        {
        //alert("txteditid = "+document.getElementById("txteditid").value);
        reqstring = reqstring + "&activepageid="+document.getElementById("txteditid").value;
        }
        
    if (reqstring == "")
        {
        //neither the contents or page are being edited, just exit
        return;
        }


    reqstring = "action=reportactivepage" + reqstring;
    reqstring = reqstring + "&projectname="+GetProjectName();
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
    //alert("reqstring = " +reqstring);

	var http = false;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 

    //This function allows us to trap any errors
    http.onreadystatechange = function() { ReportAjaxError(http); };
    http.open("POST","../_engine/AjaxAction.aspx",true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }



function changeskin(skin)
	{
    var projectname = GetProjectName();
	//if [Edit skin] was selected then load the skin editor form
	var sSelectedIndex = document.getElementById("LstSkins").options.selectedIndex
	var sSelectedValue = document.getElementById("LstSkins").options[sSelectedIndex].value;
	if (sSelectedValue.toLowerCase() == "[edit skin]")
		{
		//---- [EDIT SKIN] selected ---
		var sSkinParm = "?skin="+skin;
		var sURL = "editor.aspx" + sSkinParm;
		//window.open(sURL, "_blank");
		//Show the tools form with the skin editor displayed.
		ShowTools(projectname,"skineditor",skin);
		//Set the selected item back to the skin
		document.getElementById("LstSkins").value = skin;
		}

	else
		{
		//---- Skin Selected ----
        //call SetSesisonVar.aspx to set the session variable via AJAX
	    var http = false;
	    //var reqstring = "varname="+projectname+"_skin&varvalue="+sSelectedValue;
	    var reqstring = "action=changeskin";
	    reqstring = reqstring + "&projectname="+projectname;
        reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
        reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
	    reqstring = reqstring + "&skin="+sSelectedValue;
        if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
        http.onreadystatechange=function() 
            {
            if(http.readyState == 4) 
                {
                if (http.status == 200) 
                    {
                    //after the session variable has been set, reload the page. 
                    //Note: the page is reloaded, not submitted so that the page is not added to history in Firefox2 and IE7+
                    window.location.href="default.aspx"
                    }
                else
                    {
                    alert("Error: "+http.status+http.responseText);
                    }
                }
            }
        http.open("POST", "../_engine/AjaxAction.aspx", true);
        http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        http.send(reqstring);
		
		}
	}
	


function UpdateSaveColor()
    {
    //if the save button is loaded then change the color
    //alert("txtcontentschanged = " + document.getElementById('txtcontentschanged').value);
    //alert("txtpagechanged = " + document.getElementById('txtpagechanged').value);
    if (document.getElementById('imgsave') != null)
        {
        if (document.getElementById('txtcontentschanged').value == "true" || document.getElementById('txtpagechanged').value == "true")
            {
  		    document.getElementById('imgsave').src='../_engine/images/save_red.gif';
            }
        else
            {
		    document.getElementById('imgsave').src='../_engine/images/save.gif';
            }
        }
    }



function window_resize()
    {
    //alert("window resize = " + document.getElementById("div_contents").offsetHeight);
    //display and reposition contents
	document.getElementById("divcontents").style.height = document.getElementById("div_contents").offsetHeight;
	document.getElementById("divcontents").style.width = document.getElementById("div_contents").offsetWidth;
	document.getElementById("divcontents").style.top = document.getElementById("div_contents").offsetTop;
	document.getElementById("divcontents").style.left = document.getElementById("div_contents").offsetLeft;
    document.getElementById('divcontents').style.display = ""
    //Adjust the height of the treeview window
  	document.getElementById("TreeView1").style.width = document.getElementById("div_contents").offsetWidth;
    if (document.getElementById("spanproperties").style.display=="")
        {
      	document.getElementById("TreeView1").style.height = document.getElementById("div_contents").offsetHeight * 0.25;
      	document.getElementById("spanproperties").style.height = document.getElementById("div_contents").offsetHeight * 0.75;
        }
    else
        {
      	document.getElementById("TreeView1").style.height = document.getElementById("div_contents").offsetHeight;
      	}

    //hide the loading animation
    document.getElementById('div_contents').style.backgroundImage = ""
    //reposition editor window
    //alert("frame_page offsetheight = " + document.getElementById("frame_page").offsetHeight);
    //document.getElementById('diveditor').style.display = ""
    
//    document.getElementById("diveditor").style.height = document.getElementById("frame_page").offsetHeight;
//    document.getElementById("diveditor").style.width = document.getElementById("frame_page").offsetWidth;
//    document.getElementById("diveditor").style.top = document.getElementById("frame_page").offsetTop;
//    document.getElementById("diveditor").style.left = document.getElementById("frame_page").offsetLeft;
    document.getElementById("diveditor").style.height = document.getElementById("divpage").offsetHeight;
    document.getElementById("diveditor").style.width = document.getElementById("divpage").offsetWidth;
    document.getElementById("diveditor").style.top = document.getElementById("divpage").offsetTop;
    document.getElementById("diveditor").style.left = document.getElementById("divpage").offsetLeft;
    //if the editor exists then resize it
    if (document.getElementById("editor1") != null) 
        {
        window.GetRadEditor("editor1").SetSize("100%", "100%");
        }
    //update the save button color (in case we are coming from a postback)
    //UpdateSaveColor();
    }



function CloseDialog()
    {
    document.getElementById("tddialog").innerHTML = "";
    document.getElementById("tbldialog").style.display = "none";
    document.getElementById("divtransparency").style.display = "none";
    //Hide the expand and retract icons
    document.getElementById("imgexpandform").style.display = "none";
    document.getElementById("imgretractform").style.display = "none";
    //Ensure that the close button is visible
    document.getElementById("imgcloseform").style.display = "";
    //if frame_page exists then make it visible
    if (document.getElementById("frame_page") != null)
        {
        document.getElementById("frame_page").style.display="";
        }
    

    }

function ExpandDialog()
    {
    document.getElementById("tblDialogWindow").style.width = "100%";
    document.getElementById("tblDialogWindow").style.height = "100%";
    document.getElementById("imgexpandform").style.display = "none";
    document.getElementById("imgretractform").style.display = "";
    }

function RetractDialog()
    {
    document.getElementById("tblDialogWindow").style.width = "700px";
    document.getElementById("tblDialogWindow").style.height = "540px";
    document.getElementById("imgexpandform").style.display = "";
    document.getElementById("imgretractform").style.display = "none";
    }


function CloseLogin()
    {
    document.getElementById("txtusername").value = "";
    document.getElementById("txtpassword").value = "";
    document.getElementById("tblLogin").style.display = "none";
    //document.getElementById("txtloginaction").value = "";
    document.getElementById("divtransparency").style.display = "none";
    }

function CloseContentsWindow()
    {
    //alert("close contents window")
    if (document.getElementById("spanindex").style.display == "")
        {
        //-- CLOSE INDEX --
        //alert("close index")
        document.getElementById("spanindex").innerHTML = "";
        document.getElementById("spanindex").style.display="none";
        document.getElementById("TreeView1").style.display="";
        if (document.getElementById("tdcontentscontrols") != null) 
            {
            document.getElementById("tdcontentscontrols").style.display="";
            }
        else
            {
       	    document.getElementById("tdeditcontents").style.display="";
       	    document.getElementById("tdCloseContentsWindow").style.display="none";
            }
            
   	    if (document.getElementById("tdcontentslabel") != null)
   	        {
   	        //document.getElementById("tdcontentslabel").innerHTML="Contents";
      	    document.getElementById("tdcontentslabel").style.display="";
    	    document.getElementById("tdindexlabel").style.display="none";
    	    document.getElementById("tdsearchresultslabel").style.display="none";
   	        }
        }

    else if (document.getElementById("spansearchresults").style.display == "")
        {
        //-- CLOSE SEARCH --
        //alert("close search")
        document.getElementById("spansearchresults").innerHTML = "";
        document.getElementById("spansearchresults").style.display="none";
        document.getElementById("TreeView1").style.display="";
        if (document.getElementById("tdcontentscontrols") != null) 
            {
            document.getElementById("tdcontentscontrols").style.display="";
            }
        else
            {
       	    document.getElementById("tdeditcontents").style.display="";
       	    document.getElementById("tdCloseContentsWindow").style.display="none";
            }

   	    if (document.getElementById("tdcontentslabel") != null)
   	        {
   	        //document.getElementById("tdcontentslabel").innerHTML="Contents";
       	    document.getElementById("tdcontentslabel").style.display="";
    	    document.getElementById("tdindexlabel").style.display="none";
    	    document.getElementById("tdsearchresultslabel").style.display="none";
   	        }
        }

    else if (document.getElementById("TreeView1").style.display == "")
        {
        //-- EXIT EDIT MODE -- if the contents window is displayed then set the session variable _contentsmode=live and reload the page.
       //alert("close contents")
        //determine if a page is being edited.
        //NeedToSave();
       if (NeedToSave() == true)
            {
            Save(true);
            } 

//        if (document.getElementById("txtpagechanged").value == "true" && document.getElementById("txteditid").value != "")
//            {
//            var editid = document.getElementById("txteditid").value;
//	        var node=window.TreeView1.FindNodeById(editid);
//            if (node!=null)
//                {
//                var editname = node.Text;
//                if (confirm("The page '" + editname + "' has been modified. Do you wish to save changes?") == true)
//                    {
//                    Save(true);
//                    }
//		        }
//            }

        //determine if contents is being edited.
        if (document.getElementById("txtcontentschanged").value == "true")
            {
            if (confirm("The contents has been modified. Do you wish to save changes?") == true)
                {
                SaveContents();
                return;
                }
            }


        //get the projectname
        var projectname = GetProjectName();
        //call SetSesisonVar.aspx to set the session variable via AJAX
	    var http = false;
	    //var reqstring = "varname="+projectname+"_contentsmode&varvalue=live";
	    var reqstring = "action=contentslive";
	    reqstring = reqstring + "&projectname="+projectname;
        reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
        reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;

        if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
        http.onreadystatechange=function() 
            {
            if(http.readyState == 4) 
                {
                if (http.status == 200) 
                    {
                    //after the session variable has been set, reload the page. 
                    //Note: the page is reloaded, not submitted so that the page is not added to history in Firefox2 and IE7+
                    //alert("reloading page")
                    window.location.href="default.aspx"
                    }
                else
                    {
                    alert("Error: "+http.status+http.responseText);
                    }
                }
            }
        http.open("POST", "../_engine/AjaxAction.aspx", true);
        http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        http.send(reqstring);
        }
    }

function loadform(formname)
    {
    window.location.href = formname + "?projectname="+GetProjectName();
    }



function showoptions()
	{
	//if the options form is already displayed then hide it
	if (document.getElementById("tbloptions").style.display=="")
		{
		document.getElementById("tbloptions").style.display="none";
		}
	else
		{
		document.getElementById("tbloptions").style.display="";
		document.getElementById("tbloptions").focus();
		//position the options list below the options button
		document.getElementById("tbloptions").style.top=document.getElementById("imgoptions").offsetTop+document.getElementById("imgoptions").offsetHeight;
		document.getElementById("tbloptions").style.left=document.getElementById("imgoptions").offsetLeft+document.getElementById("imgoptions").offsetWidth-198;
		}
	}

function browse()
	{
	//Determine if the contents or page is being edited
    //if (document.getElementById("tdcontentscontrols") != null || document.getElementById("txteditid").value != "")
    if (document.getElementById("txtpagechanged").value == "true" && document.getElementById("txteditid").value != "")
        {
		alert("This function is not available while the contents or page is being edited.")
        }
	else
		{
		document.getElementById("td_contents_hidden").style.display="";
 	    document.getElementById("td_main_visible").style.display="none";
 	    window_resize()
 	    DisplayContents();
		}


	
//	if (window.frame_contents.document.Form1.txtmode.value.toLowerCase() == "edit")
//		{
//		alert("This function is not available in edit mode")
//		}
//	else
//		{
//		document.getElementById("td_contents_hidden").style.display="";
//		document.getElementById("td_main_visible").style.display="none";
//		}
	}


function showpageurl()
	{
	//determine if this is an internal or external page
	if (document.getElementById("txtexternalurl").value != "")
	    {
	    //external page
	    showpageurl_external()
	    }
	else
	    {
	    //internal page
	    showpageurl_internal()
	    }
	
	return;
	
//	alert("external url = " + document.getElementById("txtexternalurl").value)
//	//if there is a frame named "frame_page" then get the URL from there, otherwise get the url for this page.
//	if (document.getElementById("frame_page") == null)
//		{
//		//FLAT - get URL from this page
//		var sPageURL=String(location.href);
//		//Remove &dummy=1234
//		if (sPageURL.toLowerCase().indexOf("&dummy=") != -1)
//			{
//    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&dummy="));
//    		}

//		//alert("sPageURL = "+sPageURL)
//		var sPageName = sPageURL.substr(sPageURL.lastIndexOf("/")+1)
//		var sRelativeURL = "help/" + sPageName;
//		}
//	else
//		{
//		//FRAMES - Get URL from frame_page frame
//		var sPageURL=String(window.frame_page.location.href);
//		//if 'page.aspx' is not found then assume that this is an external page.
//		if (sPageURL.toLowerCase().indexOf("page.aspx") == -1)
//		    {
//		    //This is an external page
//		    alert("this is an external page")
//		    }
//		alert("sPageURL = "+sPageURL)
//		//Remove &nocache=1234
//		if (sPageURL.toLowerCase().indexOf("&nocache=") != -1)
//			{
//    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&nocache="));
//    		}
//		//Remove &SearchHighlight=abc
//		if (sPageURL.toLowerCase().indexOf("&SearchHighlight==") != -1)
//			{
//    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&SearchHighlight=="));
//    		}
//		//alert("sPageURL = "+sPageURL)
//		var sPageID = sPageURL.substr(sPageURL.lastIndexOf("?pageid=")+8)
//		//alert("sPageID = "+sPageID)
//		//Remove everything from page.aspx?...
//		if (sPageURL.toLowerCase().indexOf("page.aspx?") != -1)
//			{
//			sPageURL=sPageURL.substr(0,sPageURL.lastIndexOf("page.aspx?"))
//			}
//		sPageURL = sPageURL + "default.aspx?pageid="+sPageID
//		//var sPageURL =  document.URL + "?pageid=" + sPageName;
//		//alert("sPageURL = "+sPageURL)
//		var sRelativeURL = "help/default.aspx?pageid=" + sPageID;
//		}

//    document.getElementById("tddialog").innerHTML = "<table style='width:100%;height:100%;background-color:#DDDDDD' cellpadding='9'><tr><td>Page URL:<br><input style='width:100%;padding:3px;height:24px' value='" + sPageURL + "'><br><br>Relative URL: <font color=#737372>(assuming help system is in a sub folder named 'help')</font><br><input style='width:100%;padding:3px;height:24px' value='" + sRelativeURL + "'></td></tr></table>"
//    document.getElementById("tblDialogWindow").style.width="575px"
//    document.getElementById("spanheading").innerHTML = "Page URL"
//    document.getElementById("tblDialogWindow").style.height="208px"
//    document.getElementById("tbldialog").style.display = ""
//    document.getElementById("divtransparency").style.display = ""
	
	}

function showpageurl_internal()
    {
    //alert("internal page");
    //	alert("external url = " + document.getElementById("txtexternalurl").value)
	//if there is a frame named "frame_page" then get the URL from there, otherwise get the url for this page.
	if (document.getElementById("frame_page") == null)
		{
		//FLAT - get URL from this page
		var sPageURL=String(location.href);
		//Remove &dummy=1234
		if (sPageURL.toLowerCase().indexOf("&dummy=") != -1)
			{
    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&dummy="));
    		}

		//alert("sPageURL = "+sPageURL)
		var sPageName = sPageURL.substr(sPageURL.lastIndexOf("/")+1)
		var sRelativeURL = "help/" + sPageName;
		}
	else
		{
		//FRAMES - Get URL from frame_page frame
		var sPageURL=String(window.frame_page.location.href);
		//Remove &nocache=1234
		if (sPageURL.toLowerCase().indexOf("&nocache=") != -1)
			{
    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&nocache="));
    		}
		//Remove &SearchHighlight=abc
		if (sPageURL.toLowerCase().indexOf("&SearchHighlight==") != -1)
			{
    		sPageURL = sPageURL.substr(0,sPageURL.lastIndexOf("&SearchHighlight=="));
    		}
		//alert("sPageURL = "+sPageURL)
		var sPageID = sPageURL.substr(sPageURL.lastIndexOf("?pageid=")+8)
		//alert("sPageID = "+sPageID)
		//Remove everything from page.aspx?...
		if (sPageURL.toLowerCase().indexOf("page.aspx?") != -1)
			{
			sPageURL=sPageURL.substr(0,sPageURL.lastIndexOf("page.aspx?"))
			}
		sPageURL = sPageURL + "default.aspx?pageid="+sPageID
		//var sPageURL =  document.URL + "?pageid=" + sPageName;
		//alert("sPageURL = "+sPageURL)
		var sRelativeURL = "help/default.aspx?pageid=" + sPageID;
		}

    document.getElementById("tddialog").innerHTML = "<table style='width:100%;height:100%;background-color:#DDDDDD' cellpadding='9'><tr><td>Page URL:<br><input style='width:100%;padding:3px;height:24px' value='" + sPageURL + "'><br><br>Relative URL: <font color=#737372>(assuming help system is in a sub folder named 'help')</font><br><input style='width:100%;padding:3px;height:24px' value='" + sRelativeURL + "'></td></tr></table>"
    document.getElementById("tblDialogWindow").style.width="575px"
    document.getElementById("spanheading").innerHTML = "Page URL"
    document.getElementById("tblDialogWindow").style.height="208px"
    document.getElementById("tbldialog").style.display = ""
    document.getElementById("divtransparency").style.display = ""
	
    
    }
    
function showpageurl_external()
    {
    var sPageURL=document.getElementById("txtexternalurl").value;
   	//alert("external url = " + sPageURL)
    //alert("sPageURL = " + sPageURL.toLowerCase().substr(sPageURL.length-4, 4))
    //If this is a PDF then hide the iframe. otherwise the link dialog will not be visible
    if (sPageURL.toLowerCase().substr(sPageURL.length-4, 4) == ".pdf")
        {
        document.getElementById("frame_page").style.display="none";
        }

    document.getElementById("tddialog").innerHTML = "<table style='width:100%;height:100%;background-color:#DDDDDD' cellpadding='9'><tr><td>Page URL:<br><input style='width:100%;padding:3px;height:24px' value='" + sPageURL + "'><br><br></td></tr></table>"
    document.getElementById("tblDialogWindow").style.width="500px"
    document.getElementById("spanheading").innerHTML = "Page URL"
    document.getElementById("tblDialogWindow").style.height="150px"
    document.getElementById("tbldialog").style.display = ""
    document.getElementById("divtransparency").style.display = ""
    
    }
	
function addtofav()
	{
	//get the project name
	var projectname = location.href
	projectname = projectname.substring(0, projectname.lastIndexOf("/"))
	//projectname = projectname.substring(0, projectname.lastIndexOf("default.aspx") - 1)
	projectname = projectname.substring(projectname.lastIndexOf("/")+1)
	//get the page name and page id
	var node=window.TreeView1.SelectedNode;
	if (node!=null)
	    {
	    var pagename=" - " + node.Text;
	    var pageid=node.get_id();
	    }

	//get the project URL (without parameters)
	//var projecturl = location.href.substring(0, location.href.lastIndexOf("default.aspx")+12)
	var projecturl = location.href.substring(0, location.href.lastIndexOf("/")+1) + "default.aspx";
	projecturl = projecturl + "?pageid="+pageid;
	var sTitle=projectname + pagename;
	window.external.AddFavorite(projecturl,sTitle);
	}
	
function GetProjectName()
    {
    var projectname = window.location.href;
    //alert("projectname = "+projectname)
    //var ipos = projectname.lastIndexOf("default.aspx");
    var ipos = projectname.lastIndexOf("/");
    projectname = projectname.substring(0,ipos);
    //alert("projectname = "+projectname)
    ipos = projectname.lastIndexOf("/");
    projectname = projectname.substring(ipos+1);
    //convert any space characters
    projectname = projectname.replace(/%20/g, " ");
    //alert("projectname = "+projectname)
    return projectname
    }
    


 //--------------------------------------------------------------------------------------- EDITOR FUNCTIONS ----------------------------
 function OnClientLoad(editor)
	{
	//editor.AttachEventHandler ("RADEVENT_SEL_CHANGED", pagechanged);
	editor.AttachEventHandler ("RADEVENT_SEL_CHANGED", EditorSelectionChanged);
    editor.AttachEventHandler ("onkeydown", pagechanged); 
	editor.AttachEventHandler ("onkeyup", pagechanged); 
	//editor.AttachEventHandler ("onclick", PageItemClicked);
	ShowToolbar(editor,"minimal");
	
	//thiseditor = editor; //returns a reference to the editor
    ////create a restore point here when the editor loses focus
    //thiseditor.AttachEventHandler("blur", function() {restorePoint = thiseditor.CreateRestorePoint()});
	}

function EditorSelectionChanged()
    {
    pagechanged();
   	//Display properties for the selected item (page, dataset find, dataset detail)
	if (document.getElementById("txteditid").value != "" && document.getElementById("diveditor").style.display=="")
        {
        PageItemClicked();
        }
    }

function pagechanged()
	{
	//alert("diveditor display = " + document.getElementById("diveditor").style.display);
	//only change the save status if the editor window is visible.
	//if (document.getElementById("diveditor").style.display != "none")
	//alert("neweditorhtml = "+document.getElementById("NewEditorHTML").value);
	//alert("txteditid = "+document.getElementById("txteditid").value)
	//if (document.getElementById("txteditid").value != "")
	if (document.getElementById("txteditid").value != "" && document.getElementById("diveditor").style.display=="" && document.getElementById("txtpagechanged").value != "true")
	    {
	    if (document.getElementById("NewEditorHTML").value != window.GetRadEditor("editor1").GetHtml())
	        {
	        //alert("page changed")
	        //alert("NewEditorHTML = " + document.getElementById("NewEditorHTML").value)
	        //alert("editor1 = " + document.getElementById("NewEditorHTML").value)
	        //alert("editor visible = " + document.getElementById("diveditor").style.display)
            document.getElementById("txtpagechanged").value = "true";
            UpdateSaveColor()  
            }
        }
	}

function ShowToolbar(editor,toolbar)
    {
    //alert(editor.GetToolByName("DocumentManager").GetIcon().style.display);
    if (toolbar == "full")
        {
        var disp="";
        editor.GetToolByName("Less").GetIcon().style.display="";   
        editor.GetToolByName("More").GetIcon().style.display="none";   
        }
    else
        {
        var disp="none";
        editor.GetToolByName("Less").GetIcon().style.display="none";   
        editor.GetToolByName("More").GetIcon().style.display="";   
        }    
        
        editor.GetToolByName("Print").GetIcon().style.display=disp;   
        editor.GetToolByName("SpellCheck").GetIcon().style.display =disp;   
        editor.GetToolByName("FindAndReplace").GetIcon().style.display =disp;   
        editor.GetToolByName("GlobalSearchAndReplace").GetIcon().style.display =disp;   
        editor.GetToolByName("Cut").GetIcon().style.display =disp;   
        editor.GetToolByName("Copy").GetIcon().style.display =disp;   
        editor.GetToolByName("Paste").GetIcon().style.display =disp;   
        editor.GetToolByName("PasteFromWord").GetIcon().style.display =disp;   
        editor.GetToolByName("PasteFromWordNoFontsNoSizes").GetIcon().style.display =disp;   
        editor.GetToolByName("PastePlainText").GetIcon().style.display =disp;   
        editor.GetToolByName("PasteAsHtml").GetIcon().style.display =disp;   
        editor.GetToolByName("Undo").GetIcon().style.display =disp;   
        editor.GetToolByName("Redo").GetIcon().style.display =disp;   
        editor.GetToolByName("LinkManager").GetIcon().style.display =disp;   
        editor.GetToolByName("Unlink").GetIcon().style.display =disp;   
        //editor.GetToolByName("InsertTable").GetIcon().style.display =disp;   
        //editor.GetToolByName("ImageManager").GetIcon().style.display =disp;   
        editor.GetToolByName("AbsolutePosition").GetIcon().style.display =disp;   
        editor.GetToolByName("FlashManager").GetIcon().style.display =disp;   
        editor.GetToolByName("MediaManager").GetIcon().style.display =disp;   
        editor.GetToolByName("DocumentManager").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertFormElement").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertSymbol").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertVariable").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertCondition").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertParagraph").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertHorizontalRule").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertDate").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertTime").GetIcon().style.display =disp; 
        //editor.GetToolByName("InsertPageObject").GetIcon().style.display ="none"; 
        editor.GetToolByName("StickyNote").GetIcon().style.display =disp;   
        editor.GetToolByName("FormatStripper").GetIcon().style.display =disp;   
        editor.GetToolByName("ToggleTableBorder").GetIcon().style.display =disp;   
        editor.GetToolByName("Indent").GetIcon().style.display =disp;   
        editor.GetToolByName("Outdent").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertOrderedList").GetIcon().style.display =disp;   
        editor.GetToolByName("InsertUnorderedList").GetIcon().style.display =disp;   
        editor.GetToolByName("Superscript").GetIcon().style.display =disp;   
        editor.GetToolByName("Subscript").GetIcon().style.display =disp;   
        editor.GetToolByName("StrikeThrough").GetIcon().style.display =disp;   
        editor.GetToolByName("ApplyClass").GetIcon().style.display =disp;   
        editor.GetToolByName("FormatBlock").GetIcon().style.display =disp;   
        //editor.GetToolByName("FontName").GetIcon().style.display =disp;   
        //editor.GetToolByName("FontSize").GetIcon().style.display =disp;   
        //editor.GetToolByName("Bold").GetIcon().style.display =disp;   
        editor.GetToolByName("Italic").GetIcon().style.display =disp;   
        //editor.GetToolByName("Underline").GetIcon().style.display =disp;   
        editor.GetToolByName("JustifyLeft").GetIcon().style.display =disp;   
        editor.GetToolByName("JustifyCenter").GetIcon().style.display =disp;   
        editor.GetToolByName("JustifyRight").GetIcon().style.display =disp;   
        editor.GetToolByName("JustifyFull").GetIcon().style.display =disp;   
        //editor.GetToolByName("ForeColor").GetIcon().style.display =disp;   
        editor.GetToolByName("BackColor").GetIcon().style.display =disp;   
        //If this is firefox then hide the sticky note icon. it doesn't work well in Firefox
        if (navigator.appName != "Microsoft Internet Explorer")
            {
            editor.GetToolByName("StickyNote").GetIcon().style.display ="none";   
            }
    }


    
    
function InsertCondition(commandName, editor)
	{
	
		var args = editor.GetDialogParameters(commandName);
		var argStr = "";
		for (var item in args)
		{
			argStr += "[" + item + "=" + args[item] + "] ";
		}

		//Get the name of the current project
		var projectname = GetProjectName();
		//alert("projectname = " + projectname);

		theEditor = editor;
		editor.ShowDialog(
			"../_engine/InsertCondition.aspx?projectname="+projectname
			, null//argument
			, 290
			, 400
			, callBackFunctionPtr
			, null
			, "Insert Condition");
	};

function GlobalSearchAndReplace(editor)
    {
    if (document.getElementById("txtpagechanged").value == "true" && document.getElementById("txteditid").value != "")
        {
        alert("The page must be saved before using this function.");
        return;
        }
    
	//Get the name of the current project
	var projectname = GetProjectName();

	theEditor = editor;
	editor.ShowDialog(
		"../_engine/GlobalReplace.aspx?projectname="+projectname
		, null//argument
		, 350
		, 250
		, GlobalSearchAndReplace_callback
		, null
		, "Global Search and Replace");
    }

function GlobalSearchAndReplace_callback(returnValue)
    {
    //alert("GlobalSearchAndReplace_callback");
	if (returnValue)
		{
			alert(returnValue);
			//loadpage(TreeView1.SelectedNode.ID);
			LoadPage_editor(TreeView1.SelectedNode.ID);
		}

    }

function InsertVariable(commandName, editor)
	{
		var args = editor.GetDialogParameters(commandName);
		var argStr = "";
		for (var item in args)
		{
			argStr += "[" + item + "=" + args[item] + "] ";
		}

		//Get the name of the current project
		var projectname = GetProjectName();

		theEditor = editor;
		editor.ShowDialog(
			"../_engine/InsertVariable.aspx?projectname="+projectname
			, null//argument
			, 350
			, 250
			, callBackFunctionPtr
			, null
			, "Insert Variable");
	}

function callBackFunctionPtr(returnValue)
	{
	    //alert("callBackFunctionPtr")
	    //alert("returnValue = "+returnValue);
		//alert("This function is called when the dialog is closed");
		if (returnValue)
		{
			//theEditor.PasteHtml("<a href=\"" + returnValue.url + "\">" + returnValue.text + "</a>");
			//theEditor.PasteHtml(returnValue);
			//theEditor.PasteHtml(returnValue.url);
			theEditor.PasteHtml(returnValue);
		}
	}

	function InsertStickyNote(editor)
		{
	
		//var e = GetRadEditor("editor1")
		//Get a unique id for the sticky note tag
		var sUniqueID="_note"+new Date().getTime()
        //var sHTML = "<span tabindex='1' style='border-right:1px solid #676F7A; border-bottom:1px solid #676F7A;display:none; padding-right: 10px; padding-left: 10px; background-image:url(images/stickynote_back.jpg); padding-bottom: 10px; width: 120px; height:20px; padding-top: 10px; '>"
        var sHTML = "<span tabindex='1' style='border-right:1px solid #676F7A; border-bottom:1px solid #676F7A;display:none; padding-right: 10px; padding-left: 10px; background-image:url(../_engine/images/stickynote_back.jpg); padding-bottom: 10px; width: 120px; height:20px; padding-top: 10px; '>"
        sHTML = sHTML + "<img src='../_engine/images/lightbulb.gif'>&nbsp;"
        sHTML = sHTML + "<font id='"+sUniqueID+"' tabindex='2'>&nbsp;</font></span>"
		editor.PasteHtml(sHTML);
		//Fire the absolutePosition command to ensure that the tag can be dragged.
		//e.Fire("AbsolutePosition",null);
		//set the focus to the text area inside the sticky note
		editor.ContentWindow.document.getElementById(sUniqueID).focus();
		}

//	function InsertDataSet_Find(editor)
//		{
//        //Insert dataset find panel. <div style="float:left"> is used to support firefox.
//        var s = '';
//        s = s + '<table id="tbldataset_find" class="dataset_find" style="width:100%;" cellpadding=0 cellspacing=0>';
//        s = s + '<tr><td id="tddataset_find_fields" title="Click to view find form properties" style="border-top:0px solid white;border-left:0px solid white;"><br><br>Name:&nbsp;<input id="find_name" name="find_name" style="width:200px" onmouseover="this.title=this.id"><br><br><br></td></tr>';
//        s = s + '<tr id="trdataset_find_header" class="dataset_find_header"><td style="border-left:0px solid white;"><div style="float:left; WIDTH: 200px; HEIGHT: 18px">Name</div></td></tr>';
//        s = s + '<tr id="trdataset_find_detail" class="dataset_find_detail"><td style="border-left:0px solid white;"><div style="float:left; WIDTH: 200px; HEIGHT: 18px">[Name]</div></td></tr>';
//        s = s + '<tr id="trdataset_find_footer" class="dataset_find_footer"><td style="border-left:0px solid white;">&nbsp;</td></tr>';
//        s = s + '</table>';
//		editor.PasteHtml(s);
//		}


function InsertPageObject(commandName, editor)
	{
	
		var args = editor.GetDialogParameters(commandName);
		var argStr = "";
		for (var item in args)
		{
			argStr += "[" + item + "=" + args[item] + "] ";
		}

		//Get the name of the current project
		var projectname = GetProjectName();

		theEditor = editor;
		editor.ShowDialog(
			"../_engine/InsertPageObject.aspx?projectname="+projectname
			, null//argument
			, 350
			, 280
			, callBackFunctionPtr
			, null
			, "Insert Page Object");
	};

	
//	function InsertDataSet(editor)
//		{
//	    var http = false;
//	    var reqstring = "action=datasettemplate";
//	    reqstring = reqstring + "&datasettable="+TreeView1.SelectedNode.get_id();
//        if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
//        http.onreadystatechange=function() 
//            {
//            if(http.readyState == 4) 
//                {
//                if (http.status == 200) 
//                    {
//                    //Insert the template into the page 
//                    editor.PasteHtml(http.responseText);
//                    }
//                else
//                    {
//                    alert("Error: "+http.status+http.responseText);
//                    }
//                }
//            }
//        http.open("POST", "../_engine/AjaxAction.aspx", true);
//        http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//        http.send(reqstring);        
//		}




//------------------------------------------------------------------------------------------------------- LOGIN FUNCTIONS ---------------------------
function Login(AdminHasPassword)
    {
    //alert("admin has password = "+AdminHasPassword);
    //alert("url =" + window.location.href);
    //If the username is not blank, validate the username and password
    var username=document.getElementById("txtusername").value
    var password=document.getElementById("txtpassword").value

    //Set the active username field for future reference
    //document.getElementById("txtactiveusername").value = username;
    //document.getElementById("txtactivepassword").value = password;
    //alert("txtactiveusername = "+document.getElementById("txtactiveusername").value);


    //if admin does not have a password, display 'admin' as the username
    //alert("username = "+username);
    //if (username == "" && document.getElementById("txtAdminNoPassword").value == "true")
    if (username == "" && AdminHasPassword == "false")
        {
        document.getElementById("txtusername").value = "Admin";
        //document.getElementById("tdloginmessage").innerHTML = "<table style='width:100%' cellspacing=3 cellpadding=9><tr><td style='background-color:#DDDDDD;border-top:solid 1px #CCCCCC;'>Note: To switch to edit mode, login as 'Admin' with no password. This message will not be displayed after a password is assigned.</td></tr></table>"
        document.getElementById("tdloginmessage").innerHTML = "<table style='width:100%' cellspacing=3 cellpadding=9><tr><td style='background-color:#DDDDDD;border-top:solid 1px #CCCCCC;'><img src='../_engine/images/warning_icon.gif' align='left' hspace='8' vspace='4'>To switch to edit mode, login as 'Admin' with no password. This message will not be displayed after a password is assigned.</td></tr></table>"
        }

        
    if (username == "")
        {
        //if the username is blank then display the login form
        document.getElementById("tblLogin").style.display = "";
        document.getElementById("divtransparency").style.display = "";
        document.getElementById("txtusername").focus();
        return;
        }
        
	var http = false;
	//var reqstring = "txtaction=login&username="+username+"&password="+password+"&editpageaction="+editpage;
	var reqstring = "txtaction=login&username="+username+"&password="+password;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //if login was successful then unload the login form. otherwise redisplay it
                if (http.responseText.indexOf("_valid_username_") == -1)
                    {
                    //document.getElementById("tdloginmessage").innerHTML = "The username or password is not valid.";
                    //document.getElementById("tdicon").innerHTML = "<img src='../_engine/images/error.gif' alt='error'/>"
                    document.getElementById("tdloginmessage").innerHTML = "<table cellpadding=6><tr><td><img src='../_engine/images/error.gif' alt='error'/></td><td>The username or password is not valid.</td></tr></table>";
                    //If there was an error then make sure that the login prompt is visible.
                    document.getElementById("tblLogin").style.display = "";
                    document.getElementById("divtransparency").style.display = "";
                    document.getElementById("txtusername").focus();
                    //If the username is not valid then clear the txtactiveusername field
                    document.getElementById("txtactiveusername").value = "";
                    }
                else
                    {
                    //alert("login is valid")
                    //Postback to cause us to switch to edit mode
                    //__doPostBack("","");
                    //Note: the page is reloaded instead of postback so that the editor gets loaded.
               		window.location.href="default.aspx"
                    }
                } 
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "default.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }


function project_logout()
    {
    //alert("project_logout")
    //determine if the contents or pages need to be saved
    if (document.getElementById("txtcontentschanged").value == "true" || document.getElementById("txtpagechanged").value == "true")
        {
        if (confirm("The contents or page requires saving. Do you wish to continue and lose changes?") == false) {return;}
        }

    //document.getElementById("txtaction").value = "logout";
    //Postback to cause us to switch to live mode
    //__doPostBack("","");
    
    //get the projectname
    var projectname = GetProjectName();
    //Get add page HTML from AddPage.aspx using AJAX
	var http = false;
	//var reqstring = "varname="+projectname+"_username&varvalue=public";
	var reqstring = "action=logout";
	reqstring = reqstring + "&projectname="+projectname;
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;

    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //after the session variable has been set, reload the page. 
                //Note: the page is reloaded, not submitted so that the page is not added to history in Firefox2 and IE7+
                window.location.href="default.aspx"
                }
            else
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    
    }




function LoginKeyPress(e)
	{
    var key;
	//if(window.event)
	if(e)
		{
		//key = window.event.keyCode;     //IE
		key = e.keyCode;     //IE
		}
	else
		{
		key = e.which;     //firefox
		}

	if(key == 13)
		{
		Login();
		return false;
		}
	else
		{
		return true;
		}
	}


//-------------------------------------------------------------------------------------------- PAGE FUNCTIONS ------------------------
function loadpage(pageid,sfile)
	{
	//if (sfile == null) {alert("sfile is null")}
    //alert("neweditorhtml = " + document.getElementById("NewEditorHTML").value);
    //determine if a page is already being edited.
    //NeedToSave();
    if (NeedToSave() == true)
        {
        Save(false);
        return;
        } 

    //Ensure that the editor window is hidden
	document.getElementById("diveditor").style.display = "none";
    //if the properites window is loaded then load properties
    if (document.getElementById("spanproperties").style.display == "")
        {
        //if contents is in edit mode then display properties, otherwise make sure that properties are hidden.
        if (document.getElementById("imgsave") != null)
            {
            DisplayProperties("Page");
            }
        else
            {
            CloseProperties();
            }
        }
//    //If the page frame is hidden then show it now. Only do this in live mode. because the contents will always be visible in edit mode.
//    if (document.getElementById("td_contents_hidden") != null && document.getElementById("tdcontentscontrols") == null)
//        {
//   		document.getElementById("td_contents_hidden").style.display="none";
// 	    if (document.getElementById("td_main_visible") != null) {document.getElementById("td_main_visible").style.display=""}
//   	    window_resize();
//        }

	document.getElementById("txtexternalurl").value="";
    //Load Internal or external page
	if (sfile != null && sfile != "undefined")
		{
        //If the page frame is hidden then show it now. Only do this in live mode. because the contents will always be visible in edit mode.
        if (document.getElementById("td_contents_hidden") != null && document.getElementById("tdcontentscontrols") == null)
            {
   		    document.getElementById("td_contents_hidden").style.display="none";
 	        if (document.getElementById("td_main_visible") != null) {document.getElementById("td_main_visible").style.display=""}
   	        window_resize();
            }
		
		
		//alert("sfile = "+sfile);
		//-- EXTERNAL --
		//hide the 'edit page' icon
		if (document.getElementById("imgedit") != null) {document.getElementById("imgedit").style.display = "none";}
		//load the URL into the page frame
	    //if the frame_page tag does not exist then the format is FLAT. load the page into this frame (not frame_page)
        if (document.getElementById("frame_page") == null)
            {
            //-- FLAT --
            window.location.href = sfile
            //window.open(sfile);
            }
        else
            {
            //-- FRAMES --
    		document.getElementById("frame_page").src=sfile;
    		document.getElementById("txtexternalurl").value=sfile;
            }
		}
	else
		{
		//get search text
		var searchtext = getSearchText()
		var searchparm = "";
		if (searchtext != "" && searchtext != null)
		    {
		    //searchparm = "&search=" + searchtext;
		    searchparm = "&SearchHighlight=" + searchtext;
		    }
    	var d = new Date()
	    var nocache = "&nocache="+d.getHours()+d.getMinutes()+d.getSeconds();
    	//show the 'edit page' icon
		if (document.getElementById("imgedit") != null) {document.getElementById("imgedit").style.display = "";}
	    //Load the page into the page frame
		//document.getElementById("frame_page").src="default.aspx?pageid="+pageid+nocache+searchparm;
		    //if the frame_page tag does not exist then the format is FLAT. load the page into this frame (not frame_page)
        if (document.getElementById("frame_page") == null)
            {
            //-- FLAT --
            //window.location.href = "default.aspx?pageid="+pageid+nocache+searchparm;
            window.location.href = "default.aspx?pageid="+pageid+searchparm;
            }
        else
            {
            //-- FRAMES --
            //load the page into the page frame.
            document.getElementById("frame_page").src = "page.aspx?pageid="+pageid+nocache+searchparm;
            //If the page frame is hidden then show it now. Only do this in live mode. because the contents will always be visible in edit mode.
            if (document.getElementById("td_contents_hidden") != null && document.getElementById("tdcontentscontrols") == null)
                {
   		        document.getElementById("td_contents_hidden").style.display="none";
 	            if (document.getElementById("td_main_visible") != null) {document.getElementById("td_main_visible").style.display=""}
   	            window_resize();
                }
//            //alert("showing page window");
// 	        if (document.getElementById("td_main_visible") != null) {document.getElementById("td_main_visible").style.display=""}
//            document.getElementById("td_contents_hidden").style.display="none";
//   	        window_resize();
            }
		}
    }


//function ReloadSessionandPage(sframe, url)
//    {
//    //alert("username = " + document.getElementById("txtactiveusername").value)
//    //Reload session variables and then reload the page
//	var http = false;
//    var reqstring = "action=LoadSession";
//    reqstring = reqstring + "&projectname="+GetProjectName();
//    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
//    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
//   	var d = new Date()
//    reqstring = reqstring + "&dummy="+d.getHours()+d.getMinutes()+d.getSeconds();

//    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else  {http = new XMLHttpRequest();} 
//    http.onreadystatechange=function() 
//        {
//        if(http.readyState == 4) 
//            {
//            if (http.status == 200) 
//                {
//                //load the url into the frame
//                document.getElementById(sframe).src = url;
//                }
//            else 
//                {
//                alert("Error: "+http.status+http.responseText);
//                }
//            }
//        }
//    http.open("POST", "../_engine/ajaxaction.aspx", true);
//    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//    http.send(reqstring);
//    }

function HighlightPage(pageid)
    {
    window.TreeView1.beginUpdate();
   	var node=window.TreeView1.FindNodeById(pageid);
   	//alert("node = " + node);
   	if (node != null)
   	    {
        window.TreeView1.SelectedNode = node; 
        node.expandAncestors()
        }
    TreeView1.endUpdate();

    //also ensure that the editor is hidden (in case the user clicked the back or forward buttons)
    if (document.getElementById("diveditor").style.display == "")
        {
        //alert("browser back or forward clicked - hide editor");
        document.getElementById("txteditid").value = ""
        document.getElementById("txtpagechanged").value = ""
  	    document.getElementById("diveditor").style.display = "none";
  	    UpdateSaveColor();
  	    }
    }

function NeedToSave()
    {
    if (document.getElementById("txtpagechanged").value == "true" && document.getElementById("txteditid").value != "")
        {
        var editid = document.getElementById("txteditid").value;
        //alert("editid = "+editid)
	    var node=window.TreeView1.FindNodeById(editid);
        if (node!=null)
            {
            var editname = node.Text;
            if (confirm("The page '" + editname + "' has been modified. Do you wish to save changes?") == true)
                {
                //Save(true);
                return true;
                }
            else
                {
                //if the user chose not to save then clear the edit id
                document.getElementById("txteditid").value = ""
                document.getElementById("txtpagechanged").value = ""
                //document.getElementById("NewEditorHTML").value = "";
                //window.GetRadEditor("editor1").Document.body.innerHTML = "";
                UpdateSaveColor()  
                }
		    }
        }
    }
    
//function page(pageid)
//    {
//    //alert("page " + pageid);
//    //this will select the page and cause loadpage to fire.
//    TreeView1.selectNodeById(pageid);
//    }
	
function pagelink(pageid)
    {
    //alert("pageid = "+pageid)
    //this will select the page and cause loadpage to fire.
    TreeView1.selectNodeById(pageid);
    }
	
	

function EditPage()
    {
	//Get the pageID from the currently selected tree node
	var node=window.TreeView1.SelectedNode;
	if (node==null)
	    {
	    alert("Error: page not selected in contents.")
	    return;
	    }
	else
	    {
	    sPageID = node.get_id();
	    }
	
	//alert("sub 9 = " + sPageID.toLowerCase().substring(0, 9));
	
	//Determine if this is a new page.
	if (sPageID.toLowerCase().substring(0, 9) == "template_")
	    {
	    alert("The contents must be saved before this page can be edited.")
	    return;
	    }
	
	//Determine if the page is already being edited.
	if (document.getElementById("diveditor").style.display == "")
	    {
	    alert("This page is already in edit mode.")
	    return;
	    }
	
    //determine if the page is locked
	var reqstring = "action=lockstatus";
	reqstring = reqstring + "&pageid="+sPageID;
    reqstring = reqstring + "&projectname="+GetProjectName();

    var http = false;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 

    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status != 200) 
                {
                //if there was an error, display it in a popup window
                alert("Error: "+http.status+http.responseText);
                }
            else
                {
                //if the page is locked by another user, inform the user
                //alert("lock status = "+http.responseText);
                if (http.responseText.indexOf("<lock_message>") != -1)
                    {
                    var msg = http.responseText
                    msg = msg.substring(msg.indexOf("<lock_message>")+14, msg.indexOf("</lock_message>"))
                    alert(msg);
                    }
                else
                    {
                    //Load the current page into the editor
                    LoadPage_editor(sPageID);

                    }
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
	}


	
	


function LoadPage_editor(pageid)
    {
    //-- LOAD PAGE VIA AJAX --
    var d = new Date()
    var ParmNoCache = "?nocache=" + d.getHours()+d.getMinutes()+d.getSeconds();
    //alert("parmnocache = " + ParmNoCache);
    var ParmPageID = "&pageid=" + pageid;
    //alert("parmpageid = " + pageid);
    var ParmFormat = "&pageformat=edit"; 
    //Get page HTML using AJAX
    var http = false;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.open("GET", "default.aspx"+ParmNoCache+ParmPageID+ParmFormat, true);
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status != 200) 
                {
                //if there was an error, display it in a popup window
                alert("Error: "+http.status+http.responseText);
                }
            else
                {
                //load the page into the editor
                //alert("loading editor content: " + http.responseText);
                window.GetRadEditor("editor1").SetMode(1);
                //undo the last 100 commands. This is done to prevent users from pressing ctrl-z and load previous content.
                //attempt to undo the last 100 commands. The javascript error "could not complete the operation due to error 800a025e" may occur if text was previously selected with the mouse.
                //try {window.GetRadEditor("editor1").Undo(100);}    catch(err) {alert("error 800a025e occurred due to previously selected text. Click OK to reload the page.");LoadPage_editor(pageid);}
                try {window.GetRadEditor("editor1").Undo(100);}    catch(err) {LoadPage_editor(pageid);}
                window.GetRadEditor("editor1").Document.body.innerHTML = http.responseText;
                //if this is safari then also load the HTML via sethtml to workaround a bug
                //alert("browser = " + navigator.appName);
                if (navigator.appName == "Netscape")
                    {
                    //alert("loading safari content");
                    document.getElementById("diveditor").style.display = "";
                    window.GetRadEditor("editor1").SetHtml(http.responseText);
                    }
                
//                //If this is Firefox then switch to html view and then back to normal view to workaround a 'delete' bug
//                if(navigator.appName != "Microsoft Internet Explorer") 
//                    {
//                    window.GetRadEditor("editor1").SetMode(2)
//                    window.GetRadEditor("editor1").SetMode(1)
//                  	//window.GetRadEditor("editor1").ContentWindow.focus();
//                    }
                //set the txteditid field for future reference
                document.getElementById("txteditid").value = pageid;
                //after loading the page, display the editor window
                document.getElementById("diveditor").style.display = "";
                //alert("editor html = " + window.GetRadEditor("editor1").GetHtml());
                //return;

                document.getElementById("NewEditorHTML").value = window.GetRadEditor("editor1").GetHtml();
                //ensure that the editor window is set to 100%. This is done to workaround a bug in Firefox.
                window_resize();
                //Note: We don't need to call ReportActivePage here becase this function is called from the server when the page content was retreived via ajax
                //ReportActivePage();
                //If the page contains a 'dataset detail' panel then automatically display those properties.
                if (GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail") != null)
                    {
                    PageItemClicked();
                    }
                }
            }
        }
    http.send(null);
    }

function ImportPage()
    {
    if (document.getElementById("txtpagechanged").value == "true" && document.getElementById("txteditid").value != "")
        {
        alert("The page must be saved before using this function.");
        return;
        }

    if (document.getElementById("txtcontentschanged").value == "true")
        {
        alert("The contents must be saved before using this function.");
        return;
        }


    //alert("step1");
    if (confirm("Import Pages?") == false) 
        {
        return;
        }

    document.getElementById("tddialog").innerHTML = "<table style='width:100%;height:100%;background-color:white;'><tr><td style='font-size:14pt' align='center'>Importing Pages...</td></tr><tr><td align='center' valign='top'><img src='../_engine/images/loading.gif'></td></tr></table>";
    //document.getElementById("tddialog").innerHTML = "<div style='width:100%;height:100%;background-color:white;font-size:14pt'><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Importing Pages...</div>";
    document.getElementById("tblDialogWindow").style.width = "250px"
    document.getElementById("tblDialogWindow").style.height = "150px"
    document.getElementById("spanheading").innerHTML = ""
    document.getElementById("tbldialog").style.display = "";
    document.getElementById("divtransparency").style.display = "";
    document.getElementById("imgcloseform").style.display = "none";
    


    var projectname = GetProjectName();
    //Import pages found in the import folder using AJAX
	var http = false;
    var reqstring = "action=importpages";
	reqstring = reqstring + "&projectname="+projectname;
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            //alert("status = " + http.status);
            if (http.status == 200) 
                {
                //document.getElementById("txtaction").value = "savecontents"
                //__doPostBack("","");
                //alert("step2");
                window.location.href="default.aspx"
                }
            else if (http.status == 500) 
                {
                alert("Error 500. This error usually occurs if the html document is locked open by an application such as MS Word.")
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);


    }

function ShowAddForm()
    {
    //alert("show add form")
    //determine if a page is already being edited.
    //NeedToSave();
    if (NeedToSave() == true)
    {
    Save(true);
    } 

    
    projectname = GetProjectName();
    
    //Get add page HTML from AddPage.aspx using AJAX
	var http = false;
	var reqstring = "projectname="+projectname;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                
                document.getElementById("spanheading").innerHTML = "Add Page";
                document.getElementById("tblDialogWindow").style.width = "400px"
                document.getElementById("tblDialogWindow").style.height = "160px"
                document.getElementById("tddialog").innerHTML = http.responseText;
                document.getElementById("tbldialog").style.display = "";
                document.getElementById("imgcloseform").style.display = ""
                document.getElementById("divtransparency").style.display = "";
                document.getElementById("txtaddname").focus();
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/addpage.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }


//function ShowAddForm(projectname)
//    {
//    //alert("project = " + projectname)
//    //determine if a page is already being edited (and has changed).
//    if (document.getElementById("txteditid").value != "" && document.getElementById("txtpagechanged").value == "true")
//        {
//        var editid = document.getElementById("txteditid").value;
//	    var node=window.TreeView1.FindNodeById(editid);
//        if (node!=null)
//            {
//            var editname = node.Text;
//            if (confirm("The page '" + editname + "' is being edited. Do you wish to continue and lose changes?") == false) 
//                {
//                return;
//                }
//		    else
//		        {
//                //Remove the red dot beside the node
//                node.set_cssClass("TreeNode");
//                node.set_selectedCssClass("SelectedTreeNode");
//		        document.getElementById("txteditid").value = "";
//		        }
//		    }
//        }

//    
//    //Get add page HTML from AddPage.aspx using AJAX
//	var http = false;
//	var reqstring = "projectname="+projectname;
//    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
//    http.onreadystatechange=function() 
//        {
//        if(http.readyState == 4) 
//            {
//            if (http.status == 200) 
//                {
//                document.getElementById("tddialog").innerHTML = http.responseText;
//                document.getElementById("tbldialog").style.display = "";
//                document.getElementById("divtransparency").style.display = "";
//                document.getElementById("txtaddname").focus();
//                }
//            else 
//                {
//                alert("Error: "+http.status+http.responseText);
//                }
//            }
//        }
//    http.open("POST", "../_engine/addpage.aspx", true);
//    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//    http.send(reqstring);
//    //http.send(null);
//    
//    
//    }

function AddPage()
    {
    //alert("addpage")
  	//change the save button to red
    document.getElementById('txtcontentschanged').value = "true";
    //UpdateSaveColor()
    //Note: a node should always be selected
    //alert("selected node="+window.TreeView1.SelectedNode)
   	var node=window.TreeView1.SelectedNode;
    if (node!=null)
        {
        //alert("addname = "+document.getElementById("txtaddname").value)
        var nodename = document.getElementById("txtaddname").value
        //Validate the node name
        sMsg = ValidateName(nodename, "page name")
        if (sMsg != "")
            {
            alert(sMsg);
            return;
            }
        
        //encode the nodename to convert characters such as < and >
        //nodename = escape(nodename);
        //alert("node name = " + nodename)

        //alert("selected template index = "+document.getElementById("lstPageTemplates").selectedIndex)
        var template = document.getElementById("lstPageTemplates").options[document.getElementById("lstPageTemplates").selectedIndex].value;
        var pageicon = document.getElementById("lstPageIcon").options[document.getElementById("lstPageIcon").selectedIndex].value;

        //Assign a temporary id
   		var sUniqueID=new Date().getTime()
   		if (document.getElementById("trMergeProject").style.display == "")
   		    {
   		    //alert("merge project list visible");
   		    //Merge Project
            var nodeid = "external~!~"+sUniqueID
            var sfile = "../_engine/mergeproject.htm"
            //var sCommand = "loadpage('"+nodeid+"','../_engine/mergepage.htm')"
            //nodename = "[project:" + document.getElementById("lstMergeProjects").options[document.getElementById("lstMergeProjects").selectedIndex].value + "]";
   		    }
   		else if (document.getElementById("trExternalFile").style.display == "")
   		    {
   		    //External File
            //var sExternalFile = document.getElementById("txtExternalFile").value;
            var sfile = document.getElementById("txtExternalFile").value;
            var nodeid = "external~!~"+sUniqueID
            //var sCommand = "loadpage('"+nodeid+"','"+sExternalFile+"')"
   		    }
        else if (document.getElementById("trWebsite").style.display == "")
            {
            //Website
            //var nodeid = "external~!~"+sUniqueID
            //var sWebsite = document.getElementById("txtWebsite").value;
            var sfile = document.getElementById("txtWebsite").value;
            var nodeid = "external~!~"+sUniqueID
            //var sCommand = "loadpage('"+nodeid+"','"+sWebsite+"')"
            }
        else
            {
            //Normal Page Template
            var nodeid = template+"~!~"+sUniqueID
            var sCommand = 'loadpage("'+nodeid+'")'
            }

        //replace any space characters in sfile. If we don't do this, then the treeview will bomb on the server.
        if (sfile != null)
            {
            sfile = sfile.replace(/%20/g,' ');
           //validate external file name
            sMsg = ValidateName(sfile, "external filename")
            if (sMsg != "")
                {
                alert(sMsg);
                return;
                }
            }
        
        //add below the selected node
        TreeView1.beginUpdate();
        var newNode = new ComponentArt.Web.UI.TreeViewNode(); 
        newNode.set_text(nodename);
        newNode.set_id(nodeid)
        //if a page icon was selected then apply it now
        if (pageicon.toLowerCase() != "[auto]")
            {
            newNode.set_imageUrl("images/pageicon_"+pageicon+".gif");
            newNode.set_expandedImageUrl("images/pageicon_"+pageicon+".gif");
            }
        //set ClientSideCommand
        //newNode.set_clientSideCommand(sCommand); 
        newNode.set_clientSideCommand("loadpage('"+nodeid+"','"+sfile+"')"); 

        //insert the page as a sibling or a child
        //alert("chkAddasChild = " + document.getElementById("chkAddasChild"))
        if (document.getElementById("chkAddasChild").checked == true)
            {
            node.get_nodes().insert(newNode, node.get_index()+1);
            }
        else
            {
            node.get_parentNode().get_nodes().insert(newNode, node.get_index()+1);
            }
        TreeView1.SelectedNode = newNode;
        TreeView1.endUpdate();
        //hide the dialog
        document.getElementById("tddialog").innerHTML = "";
        document.getElementById("tbldialog").style.display = "none";
        document.getElementById("divtransparency").style.display = "none";
        //SEt the changed flag
        document.getElementById('txtcontentschanged').value = "true";
        UpdateSaveColor()

        //Display the page
        loadpage(nodeid,sfile)
        
//        if (sfile == null)
//            {
//            loadpage(nodeid)
//            }
//        else
//            {
//            loadpage(nodeid,sfile)
//            }
//       if (sExternalFile != "")
//            {
//            //external File - display in live mode
//            loadpage(nodeid,sExternalFile)
//            }
//        else if (sWebsite != "")
//            {
//            //external website - display in live mode
//            loadpage(nodeid,sWebsite)
//            }
//        else
//            {
//            //internal page - load into editor
//            LoadPage_editor(nodeid);
//            }

        }
    }

function ValidateName(nodename, sType)
    {
    //validates Page Name, Page ID, Keywords, Field Name, Table Name
        //Type: 
        var sMsg="";
        if (nodename.indexOf("<") != -1) {sMsg = "The " + sType + " cannot contain the < character."}
        if (nodename.indexOf(">") != -1) {sMsg = "The " + sType + " cannot contain the > character."}
        if (nodename.indexOf("\"") != -1) {sMsg = "The " + sType + " cannot contain double quotes."}
        if (nodename.indexOf("\\") != -1) {sMsg = "The " + sType + " cannot contain the backslash character."}
        //if (nodename.indexOf("/") != -1) {sMsg = "The " + sType + " cannot contain the forwardslash character."}
        if (nodename.indexOf("+") != -1) {sMsg = "The " + sType + " cannot contain the + character."}
        if (nodename.indexOf("%") != -1) {sMsg = "The " + sType + " cannot contain the % character."}
        if (nodename.indexOf("#") != -1) {sMsg = "The " + sType + " cannot contain the # character."}
        //if (nodename.indexOf(",") != -1) {sMsg = "The " + sType + " cannot contain the , character."}
        if (nodename.substr(0,1) == " ") {sMsg = "The " + sType + " cannot begin with a space."}
        //Do not allow comma (,) in the name (except page name)
        if (sType != "page name" && nodename.indexOf(",") != -1) {sMsg = "The " + sType + " cannot contain the , character."}
        //Do not allow ? in the name (except page name, and keyword)
        if (sType != "page name" && sType != "keyword" && nodename.indexOf("?") != -1) {sMsg = "The " + sType + " cannot contain the ? character."}
        //Do not allow & in the name (except page name, and keyword)
        if (sType != "page name" && sType != "keyword" && nodename.indexOf("&") != -1) {sMsg = "The " + sType + " cannot contain the ampersand character."}

        //ensure that the page name is not blank
        //if (sType == "page name" && nodename.replace(/ /g, "") == "")  {sMsg = "The " + sType + " cannot be blank."}
        if (sType != "keyword" && nodename.replace(/ /g, "") == "")  {sMsg = "The " + sType + " cannot be blank."}
        //Do not allow forward slash in page id. It is required in page name for embedded projects.
        if (sType == "page id" && nodename.indexOf("/") != -1)  {sMsg = "The " + sType + " cannot contain the forwardslash character."}
        //Ensure that the field name is not longer than 64 characters
        if (sType == "field")
            {
            if (nodename.length > 64) {sMsg = "The fieldname cannot be longer than 64 characters."}
            if (nodename.indexOf("'") != -1) {sMsg = "The " + sType + " cannot contain the single quote character."}
            }

        return sMsg;
    }

function PageTemplateChange()
    {
   	var sSelectedIndex = document.getElementById("lstPageTemplates").options.selectedIndex;
   	var sSelectedValue = document.getElementById("lstPageTemplates").options[sSelectedIndex].value;
    //alert("selected value = " + sSelectedValue);
    if (sSelectedValue == "External File")
        {
        //Show the 'external file' textbox
        document.getElementById("trExternalFile").style.display = "";
        document.getElementById("trWebsite").style.display = "none";
        document.getElementById("trMergeProject").style.display = "none";
        document.getElementById("trPageName").style.visibility = "";
        }
    else if (sSelectedValue == "Website")
        {
        //Show the 'website' textbox
        document.getElementById("trExternalFile").style.display = "none";
        document.getElementById("trWebsite").style.display = "";
        document.getElementById("trMergeProject").style.display = "none";
        document.getElementById("trPageName").style.visibility = "";
        }
    else if (sSelectedValue == "Merge Project")
        {
        //Show the 'project' list
        document.getElementById("trExternalFile").style.display = "none";
        document.getElementById("trWebsite").style.display = "none";
        document.getElementById("trMergeProject").style.display = "";
        document.getElementById("trPageName").style.visibility = "hidden";
        }
    else
        {
        //Regular template selected
        document.getElementById("trExternalFile").style.display = "none";
        document.getElementById("trWebsite").style.display = "none";
        document.getElementById("trMergeProject").style.display = "none";
        document.getElementById("trPageName").style.visibility = "";
        }
    }

function MergeProjectSelected()
    {
    //When a merge project is selected, change the page name to [project:1234]
    document.getElementById("txtaddname").value = "[project:" + document.getElementById("lstMergeProjects").options[document.getElementById("lstMergeProjects").selectedIndex].value + "]";
    }

function ShowAddPageOptions()
    {
    //document.getElementById("trFileName").style.display = "";
    //document.getElementById("trPageTemplate").style.display = "";
    document.getElementById("trPageIcon").style.display = "";
    document.getElementById("trAddasChild").style.display = "";
    document.getElementById("tdShowOptions").style.display = "none";
    document.getElementById("tdHideOptions").style.display = "";
    document.getElementById("tblDialogWindow").style.height = "260px"
    }
    
function HideAddPageOptions()
    {
    //document.getElementById("trFileName").style.display = "none";
    //document.getElementById("trPageTemplate").style.display = "none";
    document.getElementById("trPageIcon").style.display = "none";
    document.getElementById("trAddasChild").style.display = "none";
    document.getElementById("tdShowOptions").style.display = "";
    document.getElementById("tdHideOptions").style.display = "none";
    document.getElementById("tblDialogWindow").style.height = "160px"
    //document.getElementById("trExternalFile").style.display = "none";
    //document.getElementById("trWebsite").style.display = "none";
    //document.getElementById("trMergeProject").style.display = "none";
    //document.getElementById("trPageName").style.visibility = "";

    }

function AddPageKeyPress(searchtext,e)
	{
    var key;
	if(window.event) 
		{
		key = window.event.keyCode;     //IE
		}
	else
		{
		key = e.which;     //firefox
		}

	if(key == 13)
		{
		AddPage();
		return false;
		}
	else
		{
		return true;
		}
	}

function delete_AddPage()
    {
  	//change the save button to red
    document.getElementById('txtcontentschanged').value = "true";
    //UpdateSaveColor()

    //set the action to 'AddPage' and submit
    document.getElementById("txtaction").value = "addpage";
    __doPostBack("","");
    }

function DeleteSelectedPage()
    {
    //verify that a node is selected
    var node=TreeView1.SelectedNode;
    if (node==null)
        {
        alert("Please select a page to delete.")
        return;
        }

    //confirm that the page should be deleted
    sPageName = node.Text;
    if (confirm("Delete page '" + sPageName + "'?") == false)
        {
        return;
        }

    //Make sure that txtpagechanged is false so that the 'do you want to save' prompt does not appear.
    document.getElementById('txtpagechanged').value = "";
	    
   	//change the save button to red
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()

    //Hide the page and set the 'value' attribute to 'delete'
    node.setProperty("Visible", false);
    //node.set_rowCssClass("HiddenRow");
    //node.Visible = false;
    node.visible = false;
    node.set_value("delete")
    //select the first visible node
    var rootNodes = TreeView1.FindNodeById("rootnode").get_nodes();
    for (var i = 0; i < rootNodes.get_length(); i++)
        {
        //alert("page id = " + rootNodes.getNode(i).get_id());
        if (rootNodes.getNode(i).get_value() != "delete" && rootNodes.getNode(i).get_id() != "rootnode")
            {
            //alert("loading page with id = " + rootNodes.getNode(i).get_id());
            TreeView1.selectNodeById(rootNodes.getNode(i).get_id());
            break;
            }
        }


    }
    







function ReportAjaxError(http)
    {
    if (http.readyState == 4) 
        {
        if (http.status != 200) 
            {
            //switch the page to live mode.
            //document.getElementById("txteditid").value = ""
            //document.getElementById("txtpagechanged").value = "";
            //document.getElementById("txtcontentschanged").value = "";
            //loadpage(TreeView1.SelectedNode.ID);
            alert("Error: "+http.status+http.responseText);
            }
        }
    }

    
function Save(bQuickSave)
	{
  
    //Determine if the page needs to be saved
    if (document.getElementById("txtpagechanged").value == "true")
        {
        var editid = document.getElementById("txteditid").value;
        //alert("editid = "+editid)
        var editnode=window.TreeView1.FindNodeById(editid);
        if (editnode!=null)
            {
            //alert("node is valid");
            //-- SAVE PAGE --
            //Show the save message and disable the browser window so that the user cannot do anything until save is complete.
            //document.getElementById("tddialog").innerHTML = "<div style='width:200px;height:100px;border:3px solid black;background-color:white;font-size:12pt'><br><br>Saving...</div>";
            document.getElementById("tddialog").innerHTML = "<div style='width:100%;height:100%;background-color:white;font-size:20pt'><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Saving...</div>";
            document.getElementById("tblDialogWindow").style.width = "250px"
            document.getElementById("tblDialogWindow").style.height = "150px"
            document.getElementById("spanheading").innerHTML = ""
            document.getElementById("tbldialog").style.display = "";
            document.getElementById("divtransparency").style.display = "";

            //if there is a page being edited and it has been changed, save the page
	        var reqstring = "txtaction=savepage";
            //Add the page id to reqstring
            reqstring = reqstring + "&pageid=" + editid
            reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
            reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;

            //Add the page html to reqstring
   	        var editor = window.GetRadEditor("editor1");
   	        //pagehtml = escape(editor.GetHtml());
   	        pagehtml = editor.GetHtml();
   	        //pagehtml = unescape(pagehtml);
   	        pagehtml = encodeURIComponent(pagehtml);
   	        //alert("pagehtml = " + pagehtml);
   	        
   	        
            //pagehtml = pagehtml.replace(/</gi, "&#60;");
   	        //pagehtml = pagehtml.replace(/>/gi, "&#62;");
   	        
	        reqstring = reqstring + "&pagehtml=" + pagehtml;
           
	        var http = false;
            if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else   {http = new XMLHttpRequest();} 

            //This function allows us to trap any errors
            http.onreadystatechange = function() 
                {
                if (http.readyState == 4) 
                    {
                    if (http.status != 200) 
                        {
                        alert("Error: "+http.status+http.responseText);
                        }
                    else
                        {
                        //After saving the page, clear the txtpagechanged field
                        document.getElementById("txtpagechanged").value = ""
                        UpdateSaveColor()
                        document.getElementById("tddialog").innerHTML = "";
                        document.getElementById("tbldialog").style.display = "none";
                        document.getElementById("divtransparency").style.display = "none";
                        //After saving, update the NewEditorHTML field so we know when new changes are made.
                        document.getElementById("NewEditorHTML").value = window.GetRadEditor("editor1").GetHtml();
                        
                        //After saving, write datasource for tbldataset_detail (if exists)
                        if (GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail") != null)
                            {
                            if (GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource") == null)
                                {
                                //only write the datasource attribute if it does not already exist.
                                GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").setAttribute("datasource",TreeView1.SelectedNode.ID,0);
                                }
                            }

                        //reload the page in live mode, unless this is a quicksave
                        if (bQuickSave != true)
                            {
                            document.getElementById("txteditid").value = "";
                            document.getElementById("diveditor").style.display = "none";
                            //set the focus to the search textbox to prevent the flashing cursor in the page window
                            try {document.getElementById("txtsearch").focus()}  catch(err){}
//                            if (document.getElementById("txtsearch") != null)
//                                {
//                                document.getElementById("txtsearch").focus();
//                                }
                            loadpage(TreeView1.SelectedNode.ID);
                            //if the contents has changed, save it now. This will cause a postback
                            //note: SaveContents() is called here to ensure that the page is saved first. if this call was placed at the bottom of the function, the postback may occur before the page is saved.
                            SaveContents();
                            }
                        }
                    }
                }

	        http.open("POST","default.aspx",true);
            http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //http.setRequestHeader("Content-Type", "text/xml");
            
            http.send(reqstring);
            }
	    }
	else
	    {
	    //The page does not need to be saved. Just save the contents. This will cause a postback
        if (bQuickSave != true)
            {
            SaveContents();
            }
	    }
    }


function SaveContents()
    {
    //alert("savecontents");
    //if the contents needs to be saved, set the action to 'savecontents' and postback
    if (document.getElementById("txtcontentschanged").value == "true")
        {
        //before postback, clear txteditid so that a blank editor is not loaded if the user clicks the browser back button.
        document.getElementById("txteditid").value = "";
        document.getElementById("txtcontentschanged").value = "";
        
        //alert("selected node = " + window.TreeView1.SelectedNode.ID);

        
        //-- SAVE CONTENTS --
        document.getElementById("txtaction").value = "savecontents"
        __doPostBack("","");
        }
    }

function nodeMove(sourceNode, targetNode)
	{
	//alert("nodemove");
	//change the save button to red
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()
	return true; 
	}

function nodeCopy(sourceNode)
	{
	//alert("nodecopy")
	//Do not allow nodeCopy to happen because this will cause a postback, and also will create a node that is not compatible with helpconsole.
	//Treeview1.set_cancel(true); 
	return false; 
	}

function nodeRename(sourceNode, newName)
	{ 
	//alert("nodeRename");
    //Validate the node name
    var sMsg = ValidateName(newName, "page name")
    if (sMsg != "")
        {
        alert(sMsg);
        return;
        }

	//change the save button to red
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()
	return true; 
	}


function printpage()
	{
	//Determine if the page is in a frame or div tag
	if (document.getElementById("frame_page") == null)
	    {
	    //-- PRINT DIV TAG --
	    printpage_flat()
	    }
	else
	    {
	    //-- PRINT FRAME --
	    printpage_frame()
	    }

	}

function printpage_flat()
    {
	var printIframe = document.createElement("IFRAME");
	document.body.appendChild(printIframe);
	var printDocument = printIframe.contentWindow.document;
	printDocument.designMode = "on";
	printDocument.open();
	var currentLocation = document.location.href;
	currentLocation = currentLocation.substring(0, currentLocation.lastIndexOf("/") + 1);
	var htmlcontent = document.getElementById("divpage")
	printDocument.write("<html><head></head><body>" + htmlcontent.innerHTML + "</body></html>");
	printDocument.close();
	//If Firefox insert a prompt to compensate for a bug in Firefox
    if(navigator.appName != "Microsoft Internet Explorer") 
        {
        alert("Print Page?");
        } 
	
	try
		{
		if (document.all)
			{
			var oLink = printDocument.createElement("link");
			oLink.setAttribute("href", currentLocation + "pagestyles.css", 0);
			oLink.setAttribute("type", "text/css");
			oLink.setAttribute("rel", "stylesheet", 0);
			printDocument.getElementsByTagName("head")[0].appendChild(oLink);
			printDocument.execCommand("Print");
			}
		else
			{
			printDocument.body.innerHTML = "<link rel='stylesheet' type='text/css' href='" + currentLocation + "pagestyles.css'></link>" + printDocument.body.innerHTML;
			printIframe.contentWindow.print();
			}
		}
	catch(ex)
		{
		}
	document.body.removeChild(printIframe);
    }

function printpage_frame()
    {
	//if we are in live mode, print the content of the iframe
	try
        {
        window.frames["frame_page"].focus(); 
	    window.frames["frame_page"].print();
        }
    catch(err)
        {
        txt="This appears to be an external page.\n\nTo print this page, right click the page and select 'print'.";
        alert(txt);
        }
    }




function EditContents()
    {
    //get the projectname
    var projectname = GetProjectName();
    //Get add page HTML from AddPage.aspx using AJAX
	var http = false;
	var reqstring = "action=editcontents";
	reqstring = reqstring + "&projectname="+projectname;
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;

    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                if (http.responseText.indexOf("<lock_message>") != -1)
                    {
                    //Display message if the contents is locked
                    var msg = http.responseText
                    msg = msg.substring(msg.indexOf("<lock_message>")+14, msg.indexOf("</lock_message>"))
                    alert(msg);
                    }
                else
                    {
                    //after the session variable has been set, reload the page. 
                    //Note: the page is reloaded, not submitted so that the page is not added to history in Firefox2 and IE7+
                    //alert("reloading page")
                    window.location.href="default.aspx"
                    }
                }
            else
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }
    
    

function linkpage(commandName, editor)
    {
    var projectname = GetProjectName()
    
    //editor.PasteHtml("hello");
    //return;
   	//var restorePoint = window.GetRadEditor("editor1").CreateRestorePoint(); //returns an object that represents a restore point.

	//editor.ShowDialog("../_engine/linkpage.aspx?projectname="+projectname, null, 300, 200, linkpageCallback, null, "Link Page");
	window.GetRadEditor("editor1").ShowDialog("../_engine/linkpage.aspx?projectname="+projectname, null, 350, 400, linkpageCallback, null, "Link Page");
    }

function linkpageCallback(returnValue)
{

    //restorePoint.Select(); //Selects the restore point in case you need to restore the cursor to its original location.


	//alert("This function is called when the dialog is closed");
	if (returnValue)
	    {
	    //window.GetRadEditor("editor1").PasteHtml("<a href=\"" + returnValue.url + "\">" + returnValue.text + "</a>");
	    //alert("selection = " + window.GetRadEditor("editor1").GetSelection().GetText());
	    //var selectedElement = window.GetRadEditor("editor1").GetSelection().GetParentElement();  

	    //alert("parent element tag = " + window.GetRadEditor("editor1").GetSelection().GetParentElement().tagName)
	    //alert("selected element = " + window.GetRadEditor("editor1").GetSelectionHtml())
	    var selectedElement = window.GetRadEditor("editor1").GetSelectionHtml();
	    //var selectedElement = thiseditor.GetSelectionHtml();
        //var text = window.GetRadEditor("editor1").GetSelection().GetText();
        if (selectedElement == "")
            {
            selectedElement = returnValue.text;
            }
        
        if (returnValue.target == "")
            {
            var sLink = "<a href=\"" + returnValue.url + "\">" + selectedElement + "</a>";
            }
        else
            {
            var sLink = "<a href=\"" + returnValue.url + "\" target=\"" + returnValue.target + "\">" + selectedElement + "</a>";
            }
    
        window.GetRadEditor("editor1").PasteHtml(sLink);
        //thiseditor.PasteHtml(sLink);
    	}
    }
    

//-------------------------------------------------------------------------------------------- PROPERTIES FUNCTIONS -----------------
function PageItemClicked()
    {
    //Determine what was clicked.
	var editor = GetRadEditor("editor1")
    //If the page does not include 'dataset find', 'dataset detail' or 'dataset summary' then exit.
    if (editor.ContentWindow.document.getElementById("tbldataset_detail") == null && editor.ContentWindow.document.getElementById("tbldataset_find") == null && editor.ContentWindow.document.getElementById("tbldataset_summary") == null)
        {
        return;
        }
	var oSelElem = editor.GetSelection().GetParentElement();
	//alert("Null? = "+RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE"));
	//alert("oSelElem = "+oSelElem.tagName);
	//alert("tag id = " + oSelElem.id);
	//alert("tag name = " + oSelElem.getAttribute("id"));
	//get the field type
	var sTagName = oSelElem.tagName.toLowerCase();
	if (RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
	    {
        var oSelParent = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
	    }
	else
	    {
	    var oSelParent = oSelElem;
	    }
	if (sTagName=="input" || sTagName=="select" || sTagName=="textarea")  
		{
		//--FIELD--
        DisplayProperties("Dataset Field",oSelElem);
		}

    else if(oSelParent.id.toLowerCase()=="tbldataset_summary")
        {
        //--DATASET SUMMARY--
        DisplayProperties("Dataset Summary",oSelParent,"true");
        }

//	else if (sTagName=="span")  
//		{
//		//--FIELD LABEL--
//        DisplayProperties("Dataset Label",oSelElem);
//		}

    else if(oSelParent.id.toLowerCase()=="tbldataset_find")
	//else if (sTagName=="td" && oSelElem.id=="tddataset_find_fields")  
		{
        //--DATASET FIND--
        DisplayProperties("Dataset Find",oSelParent);
		}

    else if(oSelParent.id.toLowerCase()=="tbldataset_detail")
        {
        //--DATASET DETAIL--
        DisplayProperties("Dataset Detail",oSelParent);
        }

    else
        {
        //if the page contains 'data detail' then automatically display those properties
        if (editor.ContentWindow.document.getElementById("tbldataset_detail") != null)
            {
            oSelParent = editor.ContentWindow.document.getElementById("tbldataset_detail");
            DisplayProperties("Dataset Detail",oSelParent);
            }

        
//        var oSelParent = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"BODY")
//        //--PAGE--  Only display properties if the properties window is already displayed.
//        if (document.getElementById("spanproperties").style.display=="")
//            {
//            DisplayProperties("Page", oSelParent);
//            }
        }

    }


function DisplayProperties(sType,oSelElem,force)
    {
    //alert("oSelElem = "+oSelElem);
    //If the properties are already displayed, don't bother reloading the properties window, just load property values
    if (document.getElementById("spanproperties").innerHTML.indexOf(sType + " Properties")!=-1 && force !="true")
        {
        if (sType == "Page")
            {
	        LoadPageProperties();
	        }
	    else
	        {
	        LoadDatasetProperties(sType,oSelElem);
	        }

        return;
        }
    //Get the project name
	var projectname = GetProjectName();
    //if this is a dataset, or summary then get the datasource
    if (sType == "Dataset Summary")
        {
        sDataSource =  oSelElem.getAttribute("datasource");
        }
    else if (sType == "Dataset Find")
        {
        var sDataSource =  GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_find").getAttribute("sqlquery");
        //if sqlquery is blank then get the datasource from the detail panel
        if (sDataSource == "") 
            {
            if (GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail") != null)
                {
                sDataSource = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource")
                }
            else
                {
                alert("Please enter an SQL Statement in the 'SQL Query' property.")
                }
            }
        }
    else if (sType == "Dataset Detail")
        {
        var sDataSource =  GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource");
        }
        
        
//    else if (sType == "Dataset Find" || sType == "Dataset Detail")
//        {
//        var sDataSource =  GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource");
//        }


  	//if sDataSource is blank then set it to the page id.
    if (sDataSource == null || sDataSource == "")
        {
        sDataSource = TreeView1.SelectedNode.get_id();
        }

 
    //display the loading... icon
    document.getElementById("spanproperties").innerHTML = "<table style='width:100%;height:100%'><tr><td align=center><img src='../_engine/images/loading.gif'></td></tr></table>"
    document.getElementById("spanproperties").style.display="";
    //document.getElementById("TreeView1").style.height="35%";
    //Fire the windows_resize function so that the treeview height is adjusted
    window_resize();
    //Get properties page HTML from properties.aspx using AJAX
	var http = false;
	var reqstring = "projectname="+projectname;
    reqstring = reqstring + "&username="+document.getElementById("txtactiveusername").value;
    reqstring = reqstring + "&password="+document.getElementById("txtactivepassword").value;
    reqstring = reqstring + "&type="+sType;
    reqstring = reqstring + "&datasource="+sDataSource;	

    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //alert("http.responsetext = " + http.responseText)
                document.getElementById("spanproperties").innerHTML = http.responseText;

	            //display properties for the selected page.
	            if (sType == "Page")
	                {
	                LoadPageProperties();
	                }
	            else
	                {
//editor = GetRadEditor("editor1")
//oSelElem = editor.GetSelection().GetParentElement();
//alert("oSelElem = " + oSelElem);

	                LoadDatasetProperties(sType,oSelElem);
	                }
	                
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
        //alert("page = " + sPropertiesPage);
    if (sType == "Page")
        {
        http.open("POST", "../_engine/properties_page.aspx", true);
        }
    else
        {
        http.open("POST", "../_engine/properties_dataset.aspx", true);
        }
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }


function LoadPageProperties()
    {
    //if the properties window is visible then display properties
  	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
        //display keywords from the node
        //var ItemName = "keywords";
        //var nodeValue = node.get_value();
        //if (nodeValue == "undefined" || nodeValue == null) {nodeValue = ""}
        //var ipos=nodeValue.indexOf(ItemName+"{")
        //var ipos_end=nodeValue.indexOf("}",ipos+1)
        //var keywords=nodeValue.substring(ipos+ItemName.length+1, ipos_end)
        //var keywords = nodeValue;
        var keywords = getValueItem(node,"keywords");
        keywords = keywords.replace(/,/gi, String.fromCharCode(13,10));
        //alert("txtkeywords = " + document.getElementById("txtkeywords"))
        document.getElementById("txtkeywords").value = keywords;
        //display hidden/locked skins
        //CheckVisibleSkins(node);
        CheckHiddenLockedSkins(node);
        document.getElementById("prop_pagename").value = node.get_text(); 
        
        //Display page id
        var pageid = node.get_id();
        var renameid = getValueItem(node,"renameid");
        //alert("renameid = " + renameid);
        //alert("pageid = " + pageid);
        if (renameid != "")
            {
            document.getElementById("prop_pageid").value = pageid + "  (renamed to " + renameid + ")";
            }
        else 
            {      
            document.getElementById("prop_pageid").value = pageid;
            }
        //disable the pageid textbox if the pageid has been renamed, starts with template or is external
        if (renameid != "" || pageid.substr(0,9).toLowerCase() == "template_" || pageid.substr(0,11) == "external~!~")
            {
            document.getElementById("prop_pageid").disabled = true
            }
        else
            {
            document.getElementById("prop_pageid").disabled = false
            } 
        //display the current status
        document.getElementById("lstStatus").options[0].selected=true;
		for (i=0; i<document.getElementById("lstStatus").length; i++)
    		{
    		if (node.get_cssClass().toLowerCase() == "treenode_status_"+document.getElementById("lstStatus").options[i].text.toLowerCase())
    		    {
			    document.getElementById("lstStatus").options[i].selected=true;
			    }
			}
        //Display the page icon
        document.getElementById("lstPageIcon").options[0].selected=true;
		for (i=0; i<document.getElementById("lstPageIcon").length; i++)
    		{
    		if (node.get_imageUrl() != null)
    		    {
    		    if (node.get_imageUrl().toLowerCase() == "images/pageicon_"+document.getElementById("lstPageIcon").options[i].text.toLowerCase()+".gif")
    		        {
			        document.getElementById("lstPageIcon").options[i].selected=true;
			        }
			    }
			}
        }
    }

function LoadDatasetProperties(sType,oSelElem)
    {
    //alert("redirect URL = " + oSelElem.getAttribute("redirecturl"));
    //Get the selected item
	//var editor = GetRadEditor("editor1")
	//var oSelElem = editor.GetSelection().GetParentElement();
	if (sType == "Dataset Find")
	    {
	    //--DATASET FIND--
      	var detailtag = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_find");
	    if (detailtag.getAttribute("sortfield") != null) {document.getElementById("prop_SortField").value = detailtag.getAttribute("sortfield")}
	    if (detailtag.getAttribute("sqlquery") != null) {document.getElementById("prop_SQLQuery").value = detailtag.getAttribute("sqlquery")}
	    //Show All
        if (detailtag.getAttribute("showall") != null && detailtag.getAttribute("showall") == "true") 
            {
            document.getElementById("prop_chkShowAll").checked = true;
            }
        else
            {
            document.getElementById("prop_chkShowAll").checked = false;
            }
	    }
	else if (sType == "Dataset Detail")
	    {
	    //--DATASET DETAIL--
	    if (oSelElem.getAttribute("redirecturl") != null)  {document.getElementById("prop_RedirectURL").value = oSelElem.getAttribute("redirecturl")}
	    }
	else if (sType == "Dataset Summary")
	    {
	    //--DATASET SUMMARY--
	    //alert("allow add = " + oSelElem.getAttribute("allowadd"));
        //ALLOW ADD property
        if (oSelElem.getAttribute("allowadd") == "true")
            {
            document.getElementById("prop_chkAllowAdd").checked = true;
            }
        else
            {
            document.getElementById("prop_chkAllowAdd").checked = false;
            }

        //Get DataSource property 
        if (oSelElem.getAttribute("datasource") != null)
            {
		    for (i=0; i<document.getElementById("prop_lstDataSource").length; i++)
    		    {
    		    if (oSelElem.getAttribute("datasource").toLowerCase() == document.getElementById("prop_lstDataSource").options[i].text.toLowerCase())
    		        {
			        document.getElementById("prop_lstDataSource").options[i].selected=true;
			        }
			    }
			}
			
        //Get OpenPage property
        if (oSelElem.getAttribute("openpage") != null)
            {
		    for (i=0; i<document.getElementById("prop_lstOpenPage").length; i++)
    		    {
    		    if (oSelElem.getAttribute("openpage").toLowerCase() == document.getElementById("prop_lstOpenPage").options[i].text.toLowerCase())
    		        {
			        document.getElementById("prop_lstOpenPage").options[i].selected=true;
			        }
			    }
            }
        else
            {
            //if the openpage property was not found then select the first entry in the list and add 'openpage' attribute.
            if (document.getElementById("prop_lstOpenPage").length > 1) 
                {
                document.getElementById("prop_lstOpenPage").options[1].selected=true;
                oSelElem.setAttribute("openpage",document.getElementById("prop_lstOpenPage").options[1].text,0);
                }
            }
            
	    }
	else if (sType == "Dataset Field")
	    {
	    //alert("field locked = " + oSelElem.getAttribute("fieldlocked"));
	    //--DATASET FIELD--
	    var sFieldType = GetFieldType(oSelElem)
        document.getElementById("tdprop_fieldtype").innerHTML = sFieldType; 
        document.getElementById("tdprop_fieldname").innerHTML = oSelElem.getAttribute("id"); 
        if (oSelElem.getAttribute("defaultvalue") != null) {document.getElementById("prop_defaultvalue").value = oSelElem.getAttribute("defaultvalue")}

        //Required
        if (oSelElem.getAttribute("fieldrequired") != null && oSelElem.getAttribute("fieldrequired") == "true") 
            {
            document.getElementById("prop_chkRequired").checked = true;
            }
        else
            {
            document.getElementById("prop_chkRequired").checked = false;
            }
        
        //Disabled
        if (oSelElem.getAttribute("fieldlocked") != null && oSelElem.getAttribute("fieldlocked") == "true")
            {
            document.getElementById("prop_chkDisabled").checked = true;
            }
        else
            {
            document.getElementById("prop_chkDisabled").checked = false;
            }

        document.getElementById("prop_width").value = oSelElem.style.width; 
        document.getElementById("prop_height").value = oSelElem.style.height;
	    }

	else if (sType == "Dataset Label")
	    {
	    //--DATASET LABEL--
        document.getElementById("tdprop_fieldtype").innerHTML = "Field Label"; 
        document.getElementById("tdprop_fieldname").innerHTML = "Field Label"; 
        document.getElementById("prop_defaultvalue").value = oSelElem.innerHTML;
        document.getElementById("prop_width").value = oSelElem.style.width; 
        document.getElementById("prop_height").value = oSelElem.style.height; 
	    }

    }


function GetFieldType(oSelElem)
    {
	//get the field type
	var sFieldType = "";
	if (oSelElem.tagName.toLowerCase() == "input")
		{
		if (oSelElem.getAttribute("type").toLowerCase() == "text" || oSelElem.getAttribute("type").toLowerCase() == "hidden" || oSelElem.getAttribute("type") == null)
			{
			//-- TEXTBOX --
			return "Text";
			}

		else if (oSelElem.getAttribute("type").toLowerCase() == "number")
			{
			//-- NUMBER --
			return "Number";
			}

		else if (oSelElem.getAttribute("type").toLowerCase() == "date")
			{
			//-- DATE --
			return "Date";
			}
			
		else if (oSelElem.getAttribute("type").toLowerCase() == "checkbox")
			{
			//-- CHECKBOX --
			return "Checkbox";
			}
		}	
		
    else if (oSelElem.tagName.toLowerCase() == "select")
		{
		//-- SELECT --
		return "List";
		}

    else if (oSelElem.tagName.toLowerCase() == "textarea")
		{
    	//-- MEMO --
		return "Memo";
		}

    else if (oSelElem.tagName.toLowerCase() == "div")
		{
    	//-- LABEL --
		return "Label";
		}
	}


function getValueItem(node,ItemName)
    {
    var nodeValue = node.get_value();
    if (nodeValue == "undefined" || nodeValue == null) {nodeValue = ""}
    //alert("nodeValue = "+nodeValue)
    var ipos=nodeValue.indexOf(ItemName+"{")
    if (ipos != -1)
        {
        var ipos_end=nodeValue.indexOf("}",ipos+1)
        var ValueItem=nodeValue.substring(ipos+ItemName.length+1, ipos_end)
        //return ValueItem.toLowerCase();
        return ValueItem;
        }
    else
        {
        return ("");
        }
    }

function setValueItem(node,ItemName,ItemValue)
    {
    var nodeValue = node.get_value();
    if (nodeValue == "undefined" || nodeValue == null) {nodeValue = ""}
    //alert("nodeValue = " + nodeValue);
    //if this item already exists then remove it now
    var ipos=nodeValue.indexOf(ItemName+"{")
    if (ipos != -1)
        {
        var ipos_end=nodeValue.indexOf("}",ipos+1)
        nodeValue = nodeValue.substring(0,ipos)+nodeValue.substring(ipos_end+1)
        }
    //alert("nodeValue = " + nodeValue);
    node.set_value(nodeValue+ItemName+"{"+ItemValue+"}")
    //alert("node value = " + node.get_value());
    }

function keywordchange()
    {
    //alert("keyword change");
	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
        var keywords = document.getElementById("txtkeywords").value
        
        //Validate keywords
        var sMsg = ValidateName(keywords, "keyword")
        if (sMsg != "")
            {
            alert(sMsg);
            LoadPageProperties();
            return;
            }
        
        keywords = keywords.replace(/\r\n/gi, ",")  	 //Replace linefeed chars with ~ because linefeeds get messed up
	    keywords = keywords.replace(/\n/gi, ",")    //Do another search and replace for just \n (for netscape and firefox)
	    //keywords = "keywords{"+keywords+"}"
		//node.set_value(keywords); 
		//alert("keywords = " + keywords);
		setValueItem(node,"keywords",keywords)
		//document.getElementById("txtkeywords").focus();
        document.getElementById('txtcontentschanged').value = "true";
        UpdateSaveColor()
        }
    }
    
function CloseProperties()
	{
	//Hide the properties window
	document.getElementById("spanproperties").style.display="none";
	document.getElementById("spanproperties").innerHTML = "";
	//document.getElementById("TreeView1").style.height="100%";
	window_resize();
	}
	
function SetProp_pagename()
    {
    var newName = document.getElementById("prop_pagename").value;
    
    //Validate the node name
    var sMsg = ValidateName(newName, "page name")
    if (sMsg != "")
        {
        alert(sMsg);
        LoadPageProperties();
        return;
        }

	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
		//node.set_text(document.getElementById("prop_pagename").value);
		node.set_text(newName);
        document.getElementById('txtcontentschanged').value = "true";
        UpdateSaveColor()
		}
	}


function SetProp_pageid()
    {
    var newid=document.getElementById("prop_pageid").value;

    //Validate the node ID
    var sMsg = ValidateName(newid, "page id")
    if (sMsg != "")
        {
        alert(sMsg);
        LoadPageProperties();
        return;
        }
    
    //alert("SetProp_pageid");
	var node=TreeView1.SelectedNode;
	if (node == null)
	    {
	    alert("Error: page not selected.");
	    return;
	    }

    var oldid=node.get_id();

    //determine if the new page id already exists
    if (TreeView1.FindNodeById(newid) != null)
        {
        alert("A page with the ID '" + newid + "' already exists.");
        return;
        }
	    
    //Don't change the actual page id until the contents is saved. record the new page id in the 'value' attribute
	setValueItem(node,"renameid",newid)
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()
	}

function SetProp_Status()
    {
    //alert("set status")
	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
	    var pagestatus = document.getElementById("lstStatus").options[document.getElementById("lstStatus").selectedIndex].text;
	    node.set_cssClass("TreeNode_status_"+pagestatus);
        document.getElementById('txtcontentschanged').value = "true";
        UpdateSaveColor()
		}
	}

function SetProp_PageIcon()
    {
	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
	    var pageicon = document.getElementById("lstPageIcon").options[document.getElementById("lstPageIcon").selectedIndex].text;
	    if (pageicon.toLowerCase() != "[auto]" && pageicon != "")
	        {
	        node.set_imageUrl("images/pageicon_"+pageicon+".gif"); 
	        node.set_expandedImageUrl("images/pageicon_"+pageicon+".gif"); 
            }
        else
            {
	        node.set_imageUrl(null); 
	        node.set_expandedImageUrl(null); 
            }
        document.getElementById('txtcontentschanged').value = "true";
        UpdateSaveColor()
		}
    
    }

function SetProp_skinhide()
	{
	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
	    var valuestring="";
	    var field = document.Form1.skinhide;
		//Check to see if this is a checkbox array. If there is only one skin then it is not.
		if (isCheckboxArray() == true)
			{
			for (i = 0; i < field.length; i++)
				{
				if (field[i].checked == true)
					{
					valuestring = valuestring + field[i].value + ","
					}
				}
			}
		else
			{
			if (field.checked == true)
				{
				valuestring = valuestring + field.value + ","
				}
			}
	    
		//setValueItem(node,"hiddenskins",valuestring)
		setValueItem(node,"skinhide",valuestring)
		}
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()
	}

function SetProp_skinlock()
	{
	var node=TreeView1.SelectedNode;
	if (node != null)
	    {
	    var valuestring="";
	    var field = document.Form1.skinlock;
		//Check to see if this is a checkbox array. If there is only one skin then it is not.
		if (isCheckboxArray() == true)
			{
			for (i = 0; i < field.length; i++)
				{
				if (field[i].checked == true)
					{
					valuestring = valuestring + field[i].value + ","
					}
				}
			}
		else
			{
			if (field.checked == true)
				{
				valuestring = valuestring + field.value + ","
				}
			}
	    
		setValueItem(node,"skinlock",valuestring)
		}
    document.getElementById('txtcontentschanged').value = "true";
    UpdateSaveColor()
	}

//function SetProp_VisibleSkins()
//	{
//	
//	var node=TreeView1.SelectedNode;
//	if (node != null)
//	    {
//	    var valuestring="";
//	    var field = document.Form1.skinsvisible;
//		//Check to see if this is a checkbox array. If there is only one skin then it is not.
//		if (isCheckboxArray() == true)
//			{
//			for (i = 0; i < field.length; i++)
//				{
//				if (field[i].checked == false)
//					{
//					valuestring = valuestring + field[i].value + ","
//					}
//				}
//			}
//		else
//			{
//			if (field.checked == false)
//				{
//				valuestring = valuestring + field.value + ","
//				}
//			}
//	    
//		setValueItem(node,"hiddenskins",valuestring)
//		}
//    document.getElementById('txtcontentschanged').value = "true";
//    UpdateSaveColor()
//	}


function SetProp_DataSource(sType, svalue)
	{
	//change the pagechanged flag
    document.getElementById('txtpagechanged').value = "true";
    UpdateSaveColor()

	var editor = GetRadEditor("editor1")
  	editor.SetFocus();  
	if (sType.toLowerCase()=="detail")
	    {
	    //DATASET
        oSelElem = editor.ContentWindow.document.getElementById("tbldataset_detail");
	    oSelElem.setAttribute("datasource",svalue,0);
        DisplayProperties("Dataset Detail",oSelElem,"true");
	    }
	else
	    {
	    //SUMMARY
	    var oSelElem = editor.GetSelection().GetParentElement();
        if(RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
            {
            var oSelParent = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
            if(oSelParent.id.toLowerCase()=="tbldataset_summary")
                {
                //--SQL --
           	    if (svalue.toLowerCase()=="(sql query)")
    	            {
    	            var SQLQuery = prompt("SQL Query:");
                    if (SQLQuery != null && SQLQuery != "")
                        {
                   	    oSelParent.setAttribute("datasource",SQLQuery,0);
                        }
	                }
	            else
	                {
               	    oSelParent.setAttribute("datasource",svalue,0);
                    }
                DisplayProperties("Dataset Summary",oSelParent,"true");
                }
	        }
	    else
	        {
	        alert("Dataset Object Not Selected.")
	        }
	    }
	}

//function SetProp_OpenPage(svalue)
//	{
//	var editor = GetRadEditor("editor1")
//	var oSelElem = editor.GetSelection().GetParentElement();
//    if(RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
//        {
//        var oSelParent = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
//        if(oSelParent.id.toLowerCase()=="tbldataset_summary")
//            {
//            //--DATASET SUMMARY--
//           	oSelParent.setAttribute("openpage",svalue,0);
//            }
//	    }
//	else
//	    {
//	    alert("Dataset Object Not Selected. Please re-reselect and try again.")
//	    }

//	//change the pagechanged flag
//    document.getElementById('txtpagechanged').value = "true";
//    UpdateSaveColor()
//	}

//function SetFieldProp(sfieldname,sfieldtype,propname,svalue)
//	{
//	var editor = GetRadEditor("editor1")
//	editor.ContentWindow.document.getElementById(sfieldname).value=svalue;
//	editor.ContentWindow.document.getElementById(sfieldname).setAttribute(propname,svalue,0);
//	//change the pagechanged flag
//    document.getElementById('txtpagechanged').value = "true";
//    UpdateSaveColor()
//	}

function SetDatasetDetailProp(PropName,svalue)
    {
   	var editor = GetRadEditor("editor1")
    editor.ContentWindow.document.getElementById("tbldataset_detail").setAttribute(PropName,svalue,0);
    }

function SetDatasetFindProp(PropName,svalue)
    {
   	var editor = GetRadEditor("editor1")
    editor.ContentWindow.document.getElementById("tbldataset_find").setAttribute(PropName,svalue,0);
    }

function SetDatasetSummaryProp(PropName,svalue)
    {
    //alert("svalue = "+svalue)
    var editor = GetRadEditor("editor1")
   	editor.SetFocus();  
	var oSelElem = editor.GetSelection().GetParentElement();
	//alert(RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE"));
    if(RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
        {
        var oSelParent = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
        if(oSelParent.id.toLowerCase()=="tbldataset_summary")
            {
            //--DATASET SUMMARY, or DETAIL--
           	oSelParent.setAttribute(PropName,svalue,0);
            }
        
	    }
	else
	    {
	    alert("Dataset Object Not Selected. Please re-reselect and try again.")
	    }

	//change the pagechanged flag
    document.getElementById('txtpagechanged').value = "true";
    UpdateSaveColor()
    }

function SetFieldProp(PropName,sFieldName,sFieldType,sValue)
    {
    //alert("value = " + sValue);
   	var editor = GetRadEditor("editor1")
   	if (PropName == "defaultvalue")
   	    {
   	    //sValue=sValue.replace(/</g,"{");
        //sValue=sValue.replace(/>/g,"}");
   	    //sValue=sValue.replace(/</g,"&lt;");
        //sValue=sValue.replace(/>/g,"&gt;");
   	    editor.ContentWindow.document.getElementById(sFieldName).value=sValue;
        editor.ContentWindow.document.getElementById(sFieldName).setAttribute("defaultvalue",sValue,0);
   	    }
   	//else if (PropName == "hiddenfield") {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("hiddenfield",sValue,0)}
   	else if (PropName == "width")  	    {editor.ContentWindow.document.getElementById(sFieldName).style.width=sValue}
   	else if (PropName == "height")      {editor.ContentWindow.document.getElementById(sFieldName).style.height=sValue;}
   	else if (PropName == "disabled")    {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("fieldlocked",sValue.toString(),0)}
   	else if (PropName == "required")    {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("fieldrequired",sValue.toString(),0)}
   	else if (PropName == "showall")     {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("showall",sValue.toString(),0)}
   	//else if (PropName == "disabled")    {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("fieldlocked","true",0)}
   	//else if (PropName == "required")    {editor.ContentWindow.document.getElementById(sFieldName).setAttribute("fieldrequired","true",0)}
   	//else if (PropName == "disabled")    {editor.ContentWindow.document.getElementById(sFieldName).disabled=sValue;}
   	    
	//change the pagechanged flag
    document.getElementById('txtpagechanged').value = "true";
    UpdateSaveColor()
    }

//function SetFieldProp(PropName,sFieldName,sFieldType,sValue)
//    {
//    alert("PropName = " + PropName);
//    alert("sFieldName = " + sFieldName);
//    alert("sFieldType = " + sFieldType);
//    alert("sValue = " + sValue);
//   	var editor = GetRadEditor("editor1")
//  	editor.SetFocus();  
//	var oSelElem = editor.GetSelection().GetParentElement();
//	//alert(RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"input"))
//	var sTagName = oSelElem.tagName.toLowerCase();
//	alert("tagname = " + sTagName);

//    if (PropName == "defaultvalue")
//        {
//        if (sTagName=="span")
//            {
//            //Set Label Value
//            oSelElem.innerHTML=sValue;
//            }
//        else if (sTagName=="input")
//            {
//            oSelElem.value=sValue;
//            oSelElem.setAttribute("defaultvalue",sValue,0);
//            }
//        //editor.ContentWindow.document.getElementById(sFieldName).value=sValue;
//        //editor.ContentWindow.document.getElementById(sFieldName).setAttribute("defaultvalue",sValue,0);
//        }
//    else if (PropName == "width")  	    
//        {
//        oSelElem.style.width=sValue;
//        //editor.ContentWindow.document.getElementById(sFieldName).style.width=sValue
//        }
//    else if (PropName == "height")      
//        {
//        oSelElem.style.height=sValue;
//        //editor.ContentWindow.document.getElementById(sFieldName).style.height=sValue;
//        }
//   	    
//	//change the pagechanged flag
//    document.getElementById('txtpagechanged').value = "true";
//    UpdateSaveColor()
//    }

function isCheckboxArray()
	{
	//if (document.Form1.skinsvisible.length)
	if (document.Form1.skinhide.length)
		{
		return true;
		}
	}

function CheckHiddenLockedSkins(node)
    {
    //alert("check hidden locked skins")
	//if the list doesn't exist then exit (lite & standard edition)
	if (document.Form1.skinhide == null) {return;}
	
	var skinname = "";
	var iSkinCount = 1
	var SkinHideList = document.Form1.skinhide;
	var SkinLockList = document.Form1.skinlock;
	//determine how many skins are listed. The function 'isCheckboxArray' is called because an error will occur if there is only one checkbox in the array.
	if (isCheckboxArray() == true)
		{
		iSkinCount = document.Form1.skinhide.length;
		}
	else
		{
		iSkinCount = 1
		}
	//Initially uncheck all skins
	if (iSkinCount > 1)
		{
		for (i = 0; i < iSkinCount; i++)
			{
			SkinHideList[i].checked = false;
			SkinLockList[i].checked = false;
			}
		}
	else
		{
		SkinHideList.checked = false;
		SkinLockList.checked = false;
		}
	//get the hidden skin list from the node value
    var hiddenskins = getValueItem(node,"skinhide");
    hiddenskins = hiddenskins.toLowerCase();
    var lockedskins = getValueItem(node,"skinlock");
    lockedskins = lockedskins.toLowerCase();
	//Check skins that are hidden
	if (iSkinCount > 1)
		{
		for (i = 0; i < iSkinCount; i++)
			{
			skinname = SkinHideList[i].value + ","
			//Hidden for Skin
			if (hiddenskins.indexOf(skinname.toLowerCase())==-1)
				{
				SkinHideList[i].checked = false;
				}
			else
				{
				SkinHideList[i].checked = true;
				}
			//Locked for Skin
			if (lockedskins.indexOf(skinname.toLowerCase())==-1)
				{
				SkinLockList[i].checked = false;
				}
			else
				{
				SkinLockList[i].checked = true;
				}
			}
		}
	else
		{
		skinname = SkinHideList.value + ","
    	//Hidden for Skin
		if (hiddenskins.indexOf(skinname.toLowerCase())==-1)
			{
			SkinHideList.checked = false;
			}
		else
			{
			SkinHideList.checked = true;
			}
    	//Locked for Skin
		if (lockedskins.indexOf(skinname.toLowerCase())==-1)
			{
			SkinLockList.checked = false;
			}
		else
			{
			SkinLockList.checked = true;
			}
		}
    }

//function CheckVisibleSkins(node)
//			{
//			//if the list doesn't exist then exit (lite & standard edition)
//			if (document.Form1.skinsvisible == null)
//			    {
//			    return;
//			    }
//			var skinname = "";
//			var iSkinCount = 1
//			var SkinChkList = document.Form1.skinsvisible;
//			//determine how many skins are listed. The function 'isCheckboxArray' is called because an error will occur if there is only one checkbox in the array.
//			if (isCheckboxArray() == true)
//				{
//				iSkinCount = document.Form1.skinsvisible.length;
//				}
//			else
//				{
//				iSkinCount = 1
//				}
//			//Initially check all skins
//			if (iSkinCount > 1)
//				{
//				for (i = 0; i < iSkinCount; i++)
//					{
//					SkinChkList[i].checked = true;
//					}
//				}
//			else
//				{
//				SkinChkList.checked = true;
//				}
//			//get the hidden skin list from the node value
//            var hiddenskins = getValueItem(node,"hiddenskins");
//            //alert("hiddenskins = " + hiddenskins)
//            hiddenskins = hiddenskins.toLowerCase();
//			//Uncheck skins that are hidden
//			if (iSkinCount > 1)
//				{
//				for (i = 0; i < iSkinCount; i++)
//					{
//					skinname = SkinChkList[i].value + ","
//					if (hiddenskins.indexOf(skinname.toLowerCase())==-1)
//						{
//						SkinChkList[i].checked = true;
//						}
//					else
//						{
//						SkinChkList[i].checked = false;
//						}
//					}
//				}
//			else
//				{
//				skinname = SkinChkList.value + ","
//				if (hiddenskins.indexOf(skinname.toLowerCase())==-1)
//					{

//					SkinChkList.checked = true;
//					}
//				else
//					{
//					SkinChkList.checked = false;
//					}
//				}
//			}		

function DeleteField(sDatasetTable,sFieldName)
    {
    //Ask the user if they are sure.
    if (confirm("Delete the field '"+sFieldName+"'?") == false)
		{
		return;
		}

  	var http = false;
	var reqstring = "projectname="+GetProjectName();
	reqstring = reqstring + "&action=deletefield";
	reqstring = reqstring + "&datasettable="+sDatasetTable;
    reqstring = reqstring + "&fieldname="+sFieldName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //After the field has been deleted, refresh the field list.
           	    var oSelElem = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail");
                DisplayProperties("Dataset Detail",oSelElem,"true");
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);		

    }
    
function RenameField(sDatasetTable,sOldFieldName)
    {
	//Prompt for the new fieldname
	var sNewFieldName = prompt("Please enter a new name for the field.",sOldFieldName);
    //Validate the fieldname
    var sMsg = ValidateName(sNewFieldName, "field")
    if (sMsg != "")
        {
        alert(sMsg);
        return false;
        }
//	
//	//Validate the fieldname
//	if (ValidField(sNewFieldName) == false)
//	    {
//	    return false;
//	    }

  	var http = false;
	var reqstring = "projectname="+GetProjectName();
	reqstring = reqstring + "&action=renamefield";
	reqstring = reqstring + "&datasettable="+sDatasetTable;
    reqstring = reqstring + "&oldfieldname="+sOldFieldName;
    reqstring = reqstring + "&newfieldname="+sNewFieldName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //After the field has been deleted, refresh the field list.
           	    var oSelElem = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail");
                DisplayProperties("Dataset Detail",oSelElem,"true");
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);		

    }

function RenameTable(sOldTableName)
    {
	//Prompt for the new table name
	var sNewTableName = prompt("Please enter a new name for the dataset table.",sOldTableName);
    //Validate the Table name
    var sMsg = ValidateName(sNewTableName, "dataset table")
    if (sMsg != "")
        {
        alert(sMsg);
        return false;
        }
  	var http = false;
	var reqstring = "projectname="+GetProjectName();
	reqstring = reqstring + "&action=renametable";
	reqstring = reqstring + "&datasettable="+sOldTableName;
    reqstring = reqstring + "&newtablename="+sNewTableName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //After the table has been renamed, refresh the Table list.
           	    var oSelElem = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail");
        	    oSelElem.setAttribute("datasource",sNewTableName,0);
                DisplayProperties("Dataset Detail",oSelElem,"true");
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);		

    }

function DeleteTable(sTableName)
    {
    //Ask the user if they are sure.
    if (confirm("Delete the dataset table '"+sTableName+"'?") == false)
		{
		return;
		}

  	var http = false;
	var reqstring = "projectname="+GetProjectName();
	reqstring = reqstring + "&action=deletetable";
	reqstring = reqstring + "&datasettable="+sTableName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //After the table has been deleted, refresh the Table list.
           	    var oSelElem = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail");
          	    oSelElem.setAttribute("datasource","",0);
                DisplayProperties("Dataset Detail",oSelElem,"true");
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);		

    }


function InsertExistingField(sFieldName,sFieldType,stype)
    {
    //--DATASET SUMMARY--
    if (stype == "summary")
        {
        window.GetRadEditor("editor1").PasteHtml('<span class="SummaryField">[open:'+sFieldName+']</span>');
        }
    else
        {
        //--DATASET FIND or DETAIL--
        var sFindPrefix="";
        if (stype == "find")  
            {
            //sFindPrefix = "find_"
            var sFieldHTML='<span class="fieldlabel">'+sFieldName+'</span><input id="find_'+sFieldName+'" class="fieldbox" name="find_'+sFieldName+'" type=text>';
            }
        else if (sFieldName.toLowerCase() == "security group")  
            {
            var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><select id="'+sFieldName+'" name="'+sFieldName+'" class="fieldbox"></select>'
            }

        else
            {
            if (sFieldType == "DBTYPE_WVARCHAR")
                {
                //TEXT
                var sFieldHTML='<span class="fieldlabel">'+sFieldName+'</span><input id="'+sFieldName+'" class="fieldbox" name="'+sFieldName+'" type=text>';
                }
            else if (sFieldType == "DBTYPE_DATE")
                {
                //DATE
                var sFieldHTML='<span class="fieldlabel">'+sFieldName+'</span><input id="'+sFieldName+'" class="fieldbox" name="'+sFieldName+'" type=date>';
                }
            else if (sFieldType == "DBTYPE_R8")
                {
                //NUMBER
                var sFieldHTML='<span class="fieldlabel">'+sFieldName+'</span><input id="'+sFieldName+'" class="fieldbox" name="'+sFieldName+'" type=number>';
                }
            else if (sFieldType == "DBTYPE_BOOL")
                {
                //CHECKBOX
                var sFieldHTML='<span class="fieldlabel">'+sFieldName+'</span><input id="'+sFieldName+'" class="fieldcheckbox" type="checkbox" name="'+sFieldName+'" >';
                }
            else if (sFieldType == "DBTYPE_WLONGVARCHAR")
                {
                //MEMO
                var sFieldHTML='<span class="fieldlabel" style="height:44px">'+sFieldName+'</span><textarea id="'+sFieldName+'" class="fieldmemo" name="'+sFieldName+'"></textarea>';
                }
            }
            

        //Insert the HTML
        //window.GetRadEditor("editor1").PasteHtml('<div class="fieldlabel">'+sFieldName+':</div>'+sFieldHTML+'<br>');
        //If the 'dataset detail' panel is selected then paste to the current cursor position, otherwise insert at the bottom.
        //var james = window.GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource");
       	var editor = GetRadEditor("editor1")
       	editor.SetFocus();  
        var oSelElem = editor.GetSelection().GetParentElement();
//        if (RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
//            {
//            var oSelElem = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
//            }

        if (oSelElem.id.toLowerCase()=="tddataset_detail_fields" || oSelElem.id.toLowerCase()=="tddataset_find_fields")
            {
            //window.GetRadEditor("editor1").PasteHtml('<span class="fieldlabel">'+sFieldName+':</span>'+sFieldHTML+'<br>');
            window.GetRadEditor("editor1").PasteHtml(sFieldHTML+'<br>');
            }
        else if (stype == "detail")
            {
           	var cellHTML = editor.ContentWindow.document.getElementById("tddataset_detail_fields").innerHTML;
            cellHTML = cellHTML + sFieldHTML+'<br>';
            editor.ContentWindow.document.getElementById("tddataset_detail_fields").innerHTML = cellHTML; 
            }
        else if (stype == "find")
            {
           	var cellHTML = editor.ContentWindow.document.getElementById("tddataset_find_fields").innerHTML;
            cellHTML = cellHTML + sFieldHTML+'<br>';
            editor.ContentWindow.document.getElementById("tddataset_find_fields").innerHTML = cellHTML; 
            }

        

        //If we are adding a field to the find form then also add the field to the heading row and the detail row.
        if (stype == "find")
            {
            //alert("heading row innerHTML = " + window.GetRadEditor("editor1").ContentWindow.document.getElementById("trdataset_find_header").cells[0].innerHTML)
            window.GetRadEditor("editor1").ContentWindow.document.getElementById("trdataset_find_header").cells[0].innerHTML = window.GetRadEditor("editor1").ContentWindow.document.getElementById("trdataset_find_header").cells[0].innerHTML + '<span class="FindHeaderLabel">'+sFieldName+'</span>';
            window.GetRadEditor("editor1").ContentWindow.document.getElementById("trdataset_find_detail").cells[0].innerHTML = window.GetRadEditor("editor1").ContentWindow.document.getElementById("trdataset_find_detail").cells[0].innerHTML + '<span class="FindDetailField">[open:'+sFieldName+']</span>';
            
            }
        }
    }


function AddField(stype)
	{

	//Prompt for the fieldname
	var sFieldName = prompt('Please enter a name for the field.',stype+'1');
	//Validate the fieldname
    var sMsg = ValidateName(sFieldName, "field")
    if (sMsg != "")
        {
        alert(sMsg);
        return false;
        }
//	if (ValidField(sFieldName) == false)
//	    {
//	    return false;
//	    }
		
	var sDatasetTable = window.GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail").getAttribute("datasource");	
	//alert("sDatasetTable = " + sDatasetTable);
    //Add the field using AJAX. If an error occurs report it to the user and do not add the field.
	var http = false;
	var reqstring = "projectname="+GetProjectName();
	reqstring = reqstring + "&action=addfield";
	reqstring = reqstring + "&datasettable="+sDatasetTable;
    reqstring = reqstring + "&fieldtype="+stype;
    reqstring = reqstring + "&fieldname="+sFieldName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
  	            if (stype == "text")            {var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><input id="'+sFieldName+'" name="'+sFieldName+'" class="fieldbox" type=text>'}
	            else if (stype == "checkbox")   {var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><input id="'+sFieldName+'" name="'+sFieldName+'" class="fieldcheckbox" type="checkbox">'}
	            else if (stype == "date")       {var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><input id="'+sFieldName+'" name="'+sFieldName+'" class="fieldbox" type=date>'}
	            else if (stype == "number")     {var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><input id="'+sFieldName+'" name="'+sFieldName+'" class="fieldbox" type=number>'}
	            else if (stype == "memo")       {var sFieldHTML = '<span class="fieldlabel" style="height:44px">'+sFieldName+':</span><textarea id="'+sFieldName+'" name="'+sFieldName+'" class="fieldmemo"></textarea>'}
	            else if (stype == "list")       {var sFieldHTML = '<span class="fieldlabel">'+sFieldName+':</span><select id="'+sFieldName+'" name="'+sFieldName+'" class="fieldbox"></select>'}
	            //If the 'dataset detail' panel is selected then paste to the current cursor position, otherwise insert at the bottom.
               	var editor = GetRadEditor("editor1")
	            var oSelElem = editor.GetSelection().GetParentElement();
                if (RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")!=null)
                    {
                    var oSelElem = RadEditorNamespace.Utils.GetElementParentByTag(oSelElem,"TABLE")
                    }

	            if (oSelElem.id.toLowerCase()=="tbldataset_detail")
	                {
                    //window.GetRadEditor("editor1").PasteHtml('<span class="fieldlabel">'+sFieldName+':</span>'+sFieldHTML+'<br>');
                    window.GetRadEditor("editor1").PasteHtml(sFieldHTML+'<br>');
	                }
	            else
	                {
                   	var cellHTML = editor.ContentWindow.document.getElementById("tddataset_detail_fields").innerHTML;
                    cellHTML = cellHTML + '<span class="fieldlabel">'+sFieldName+':</span>'+sFieldHTML+'<br>';
                    editor.ContentWindow.document.getElementById("tddataset_detail_fields").innerHTML = cellHTML; 
	                }
	            //refresh the field list
           	    var oSelElem = GetRadEditor("editor1").ContentWindow.document.getElementById("tbldataset_detail");
                DisplayProperties("Dataset Detail",oSelElem,"true");

               }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/AjaxAction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);		
	}

			
//------------------------------------------------------------------------------------------------ STARTUP FUNCTIONS ----------------------------
function Evaluate(sTemplateName)
    {
    
	//Get the edition to evaluate
	//var edition=document.getElementById("lstEvalEdition").value
    var edition=document.getElementById("lstEvalEdition").options[document.getElementById("lstEvalEdition").selectedIndex].text;

    //alert("evaluate " + edition)

	//Get the index using AJAX
	var http = false;
    var reqstring = "action=evaluate";
    reqstring = reqstring + "&projectname="+GetProjectName();
    reqstring = reqstring + "&edition="+edition;
    reqstring = reqstring + "&templatename="+sTemplateName;
    
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else  {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                 //__doPostBack("","");
                 window.location.href="default.aspx"


//                //show the edition that was selected
//                if (document.getElementById("spaneditionvar") != null) {document.getElementById("spaneditionvar").innerHTML = edition}
//                //Close the activation key prompt
//                CloseDialog();
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/ajaxaction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
    }

function Activate(sTemplateName)
    {
   
	//Get the key
    var key=document.getElementById("txtActivationKey").value;

    //alert("key = " + key)

	//Get the index using AJAX
	var http = false;
    var reqstring = "action=activate&key="+key;
    reqstring = reqstring + "&projectname="+GetProjectName();
    reqstring = reqstring + "&templatename="+sTemplateName;
    if(navigator.appName == "Microsoft Internet Explorer") {http = new ActiveXObject("Microsoft.XMLHTTP");} else  {http = new XMLHttpRequest();} 
    http.onreadystatechange=function() 
        {
        if(http.readyState == 4) 
            {
            if (http.status == 200) 
                {
                //Determine if the key is valid
                var sresponse=http.responseText;
                if (sresponse.toLowerCase().indexOf("key is valid") != -1)
                    {
                    //Show the edition
                    //alert(sresponse.substring(0,sresponse.indexOf("~")));
                    sEdition = sresponse.substring(sresponse.indexOf("~")+1,sresponse.lastIndexOf("~"));
                    if (document.getElementById("spaneditionvar") != null) {document.getElementById("spaneditionvar").innerHTML = sEdition}

                    //Close the activation key prompt
                    CloseDialog();
                        
                    alert(sEdition + " Successfully Activated.") 
                    }
                else
                    {
                    alert("The key entered is not valid.") 
                    }
                }
            else 
                {
                alert("Error: "+http.status+http.responseText);
                }
            }
        }
    http.open("POST", "../_engine/ajaxaction.aspx", true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.send(reqstring);
}



