/**
  * This file contains variouos methods used in sitemap portlet
  * Author: Grzegorz Makosa, Grzegorz Widziszowski
  *
  * Tested browser compability: IE 6, FF 1.5
  *
**/  


/** Removes the portlet
**/

function removePortlet( aDraggable )
{
    var div = document.getElementById( aDraggable );
    var parent = div.parentNode;
    
    parent.removeChild( div );
}

/** gets the definition id from the string
**/
function extractDefId( aStr )
{
    var i = aStr.indexOf('_');    
    var bStr = aStr.substring(i+1, aStr.length);
    i = bStr.indexOf('_');
    return bStr.substring( 0, i );
}

/** gets the instance id from the string
**/
function extractInstId( aStr )
{
    var i = aStr.indexOf('_');    
    var bStr = aStr.substring(i+1, aStr.length);
    i = bStr.indexOf('_');
    return bStr.substring( i+1, bStr.length );
}

/** get the type of the object from the string
**/
function extractType( aStr)
{
    var i = aStr.indexOf('_');
    return aStr.substring(0,i);
}

/** creates the xml with layout of portlets
**/
function storeLayout( )
{    
    var message = '<placeholders>';
    var placeholders = document.getElementsByTagAndClassName('table', 'placeholder');
    for ( var i = 0; i < placeholders.length; i++ ) {
        message += '<placeholder id="' + placeholders[ i ].id + '">';
        message +=getSubPortlets(placeholders[i]);
        message += '</placeholder>';
    }
    message += '</placeholders>';
    return  message;
    
}

/** gets the portlets contained in the node
**/
function getSubPortlets(node)
{
    var message = "";
    if (node) {
        var childNodes = node.childNodes;
        if (childNodes) {
            for( var i=0;i<childNodes.length;i++) {
                var chNode = childNodes[i];
                if (chNode.className=="placeable") {
                    var instId =extractInstId( chNode.id ); 
                    var themeid = windowThemas[instId];
                    if (! themeid) {
                      themeid = "-1";
                     }
                    message += '<placeable type="'+ extractType( chNode.id ) +'" definitionid="' + extractDefId( chNode.id ) + '" instanceid="' + instId + '" title="'+windowTitles[instId]+'" themeid="'+themeid+'" description="'+windowDescrs[instId]+'"/>';
                } else {
                    message += getSubPortlets(chNode);
                  }
            }
        }
    }
    return message;
}

/** replaces all occurences of a pattern  with new string 
**/
function xreplace(checkMe,toberep,repwith)
{
    temp = checkMe;
    a = temp.indexOf(toberep);
    while (a != -1) {
        temp = temp.substring(0 , a) + repwith + temp.substring((a + toberep.length));
        a = temp.indexOf(toberep);
    }
	return temp;
}

/** gets the first parent element with supplied class name
**/
function getParentElementByClassName( element , className)
{
    while ((element) && (element.className!=className)) {
        element = element.parentNode;
    }
    return element;
}


/** removes the edit button from portlet element
**/
function removeEditButton(element)
{
    var editButton = findChildById(element,"editPortletButton");
    if (editButton.href.indexOf("portlet.editUrl")!=-1) {
        editButton.parentNode.removeChild(editButton);
        var tip = document.getElementById("Tip");
        tip.innerHTML = "Tip: You have to save the page to access new portlet's edit mode.";
    }
    
}

/** gets the first child element with supplied id
**/
function findChildById(parent, id)
{
    if (parent.id==id) {
    	return parent;
    }
    for (var i=0;i<parent.childNodes.length;i++) {
        var elem = findChildById(parent.childNodes.item(i),id);
        if (elem!=null) {
            return elem;
        }
    }
    return null;
}

/** functions for portlet preference editor
**/
var names = new Array();
var descriptions = new Array();
var values = new Array();
var modifiables = new Array();
var emptyPreference;
var emptyValue;

/** initializes skeletons and removes them from html
**/
function initPreferenceEditor()
{
    emptyPreference = document.getElementById("emptyPreference");
    emptyPreference.parentNode.removeChild(emptyPreference);
    emptyValue = document.getElementById("emptyValue");
    emptyValue.parentNode.removeChild(emptyValue);
}

/** reads the preferences from html structure into global arrays
  * provides simple verification    
**/

function readPreferences()
{
    var table=document.getElementById("preferences");
    if (table) {
        var prefs = table.getElementsByTagName("tr");
        var counter=0;
        for (var i=0;i<prefs.length;i++) {
            if (prefs[i].id=="preference")
            {
                var inputs = prefs[i].getElementsByTagName("input");
                var vcount=0;
                values[counter]=new Array();
                for (var m=0;m<inputs.length;m++) {
                    if (inputs[m].name=="name") {
                        if (inputs[m].value=="") {
                            inputs[m].className="error";
                            return "Name field can not be empty";
                        } else {
                            inputs[m].className="";
                            names[counter]=inputs[m];
                        }
                    }
                    if (inputs[m].name=="description") {
                        descriptions[counter]=inputs[m];
                    }
                    if (inputs[m].name=="modifiable") {
                        modifiables[counter]=inputs[m];
                    }
                    if (inputs[m].name=="value") {
                        values[counter][vcount++]=inputs[m];
                    }
                }
                counter++;
            }
         }
        for (var j=0;j<names.length;j++) {
            for (var k=0;k<j;k++) {
                if (names[j].value==names[k].value) {
                    names[k].className="error";
                    names[j].className="error";
                    return "Name fields must be unique";
                }
            }
        }
    }
    return "";
}

/** stores the preferences in encoded string 
**/
function storePreferences()
{
    var msg=readPreferences();
    if (msg!="") {
        alert("Errors were found in preferences.\n\n"+msg);
        return false;
    } else {
        var res="";
        for (var i=0;i<names.length;i++) {
            var elem = encodeValue(names[i].value,":");
            elem+= encodeValue(descriptions[i].value, ":");
            if (modifiables[i].checked) {
                elem+= encodeValue("true", ":");
            } else {
                elem+= encodeValue("false", ":");
            }
            var vals="";
            for (var j=0;j<values[i].length;j++) {
                vals+=encodeValue(values[i][j].value,";");
            }
            elem+=encodeValue(vals,":");
            res+=encodeValue(elem,"/");
        }
        return res;
    }
    return "";

}


/*******************************************/
/*                                         */
/*  this is the function called on submit  */
/*       of every editor in sitemap        */
/*                                         */
/*******************************************/

function prepareForm()
{

    actionForm = getForm();
    if (actionForm[label+'_edit{actionForm.preferenceCompositeValue}']) {
        pref = storePreferences();
        if (pref==false) {
            return false;
        } else {
            actionForm[label+'_edit{actionForm.preferenceCompositeValue}'].value=pref;
        }
    }
    if (actionForm[label+'_edit{actionForm.entitlementsCompositeValue}']) {
        actionForm[label+'_edit{actionForm.entitlementsCompositeValue}'].value=storeEntitlements();
    }
    if (actionForm[label+'_edit{actionForm.portletLibEntitlementCompositeValue}']) {
        actionForm[label+'_edit{actionForm.portletLibEntitlementCompositeValue}'].value=storePortletLibEntitlements();
    }
    if (actionForm[label+'_edit{actionForm.orderXML}']) {
        actionForm[label+'_edit{actionForm.orderXML}'].value = storeLayout();     
    }
    appendEditMode(actionForm);  
}

/** encodes the value, escaping the separator with "\separator" and "\" with "\\"
  * appends separator on the end
**/

function encodeValue(value, separator)
{
    var encoded="";
    if (value) {
	    for(i=0;i<value.length;i++){
	        if (value.charAt(i)==separator) {
	            encoded+="\\"+separator;
	        } else if (value.charAt(i)=="\\") {
	            encoded+="\\\\";
	        } else {
	            encoded+=value.charAt(i);
	        }
	    }
    }
    encoded+=separator;
    return encoded;
}

/** creates new preference element
**/
function createNewPreference()
{
    var pref_table = document.getElementById("preferences");
    for (i=0;i<pref_table.childNodes.length;i++) {
        if (pref_table.childNodes[i].nodeName.toLowerCase()=="tbody") {
            pref_table=pref_table.childNodes[i];
        }
    }
    pref_table.appendChild(emptyPreference.cloneNode(true)).id="preference";
}

/** deletes the preference element
**/
function deletePreference(elem)

{
    if (confirm("Please confirm deleting this preference.")) {
        var tr = elem.parentNode.parentNode;
        tr.parentNode.removeChild(tr);
    }
}

/** deletes the value element from a preference
**/
function deleteValue(elem)
{
    if (confirm("Please confirm deleting this value.")) {
        var div =elem.parentNode;
        div.parentNode.removeChild(div);
    }
}

/** adds a value element to a preference
**/
function addValue(elem)
{
    var pref_td = elem.parentNode;
    pref_td.insertBefore(emptyValue.cloneNode(true),elem).id="";
}

/** event handler called on preference name change
**/
function nameChanged(elem)
{
    if (elem.value=="channel") {
        elem.parentNode.parentNode.className="portletSuitePreference";
    } else {
        elem.parentNode.parentNode.className="preference";
    }
}

/** opens the modal popu window with supplied link (can be string or a element)
**/
function openModalPopup2(a)
{
    if (typeof a=="object" && a.tagName=="A") {
        var href=a.href;
    } else if (typeof a=="string") {
        var href=a;
    }
    var _wpopup_ = window.open(href,"","width=740, height=600, scrollbars=yes, status=yes");
    window.onfocus=function(){if(!_wpopup_.closed) _wpopup_.focus()}
}

/** closes the popup window
**/
function closeModalPopup(windowObject) 
{
    windowObject.close();
}


/** removes edit icons for portlets that don't have edit mode
**/
function processEditIcons()
{
    var alist = document.getElementsByTagName("a");
    for (var i=0;i<alist.length;i++) {
        if (alist[i].id=="editPortletButton") {
            if (alist[i].href.indexOf("no_edit_mode")==-1) {
            	var oldUrl = alist[i].href;
                var j = alist[i].href.indexOf(contextPath);
                j+=contextPath.length;
                var str = alist[i].href.substring(0,j+1);
                j = alist[i].href.lastIndexOf("portletmanager");
                str += alist[i].href.substring(j,alist[i].href.length);
                alist[i].href = str;
            } else {
                alist[i].parentNode.removeChild(alist[i]);
            }
        }
    }     
}

/**
**/
function appendEditMode(elem)
{
// this function caused errors in SEF mode, but seems now unnecessary
// in case the sitemanager goes out of edit mode this function must be used.
/*
    if (elem.href)
    {
       if (elem.href.indexOf("/_windowLabel/")==-1)
        {
            if (elem.href.indexOf("_mode=edit")==-1)
                elem.href = elem.href+"&_mode=edit";
        }
        else
        {
            if (elem.href.indexOf("_mode/edit")==-1)
            {
                wi = elem.href.indexOf("/_windowLabel/");
                st1 = elem.href.substring(0,wi);
                st2 = elem.href.substring(wi,elem.href.length);
                elem.href = st1+"/_mode/edit"+st2;
            }
        }
    }
    if (elem.action)
    {
        //if (elem.action.indexOf("_mode=edit")==-1)
         //   elem.action = elem.action+"&_mode=edit";
         
        if (elem.action.indexOf("_mode=edit")>-1){
            elem.action = elem.action.substring(0, elem.action.indexOf("&_mode=edit"));
        } 
         
        if (elem.action.indexOf("/_windowLabel/")==-1)
        {
            if (elem.action.indexOf("_mode=edit")==-1)
                elem.action = elem.action+"&_mode=edit";
        }
        else
        {
            if (elem.action.indexOf("_mode/edit")==-1)
            {
                wi = elem.action.indexOf("/_windowLabel/");
                st1 = elem.action.substring(0,wi);
                st2 = elem.action.substring(wi,elem.action.length);
                elem.action = st1+"/_mode/edit"+st2;
            }
        } 
    }
    */
    return true;
}

/**
**/
function clickTree(index)
{
    elem = document.getElementById(index);
    elem.style.display="none";
}