/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
 * Runtime JavaScript library for Cocoon forms.
 *
 * @author <a href="http://www.apache.org/~sylvain/">Sylvain Wallez</a>
 * @version CVS $Id: forms-lib.js,v 1.4 2004/05/11 22:50:25 joerg Exp $
 */

// Handlers that are to be called in the document's "onload" event
var forms_onloadHandlers = new Array();

function forms_onload() {
    for (var i = 0; i < forms_onloadHandlers.length; i++) {
        forms_onloadHandlers[i].forms_onload();
    }
    // Clear it (we no more need them)
    forms_onloadHandlers = null;
}

// Handlers that are to be called in form's "onsubmit" event
//FIXME: this single var implies only one form per page, and needs to be
//       visited if we decide to support several forms per page.
var forms_onsubmitHandlers = new Array();

function forms_onsubmit(submitId) {
    if (forms_onsubmitHandlers == null) {
    //    alert("onsubmit called twice!");
    } else {
      for (var i = 0; i < forms_onsubmitHandlers.length; i++) {
          forms_onsubmitHandlers[i].forms_onsubmit(submitId);
      }
    }
    // clear it
    forms_onsubmitHandlers = null;
}

/**
 * Submit the form containing an element, also storing in the hidden
 * 'forms_submit_id' field the name of the element which triggered the submit.
 */
function forms_submitForm(element, name) {
    if (name == undefined) {
        name = element.name;
    }
    
    var form = forms_getForm(element);
    if (form == null) {
        alert("Cannot find form for " + element);
    } else {
        form["forms_submit_id"].value = name;
        // FIXME: programmatically submitting the form doesn't trigger onsubmit ? (both in IE and Moz)
        forms_onsubmit(name);
        form.submit();
    }
}

/**
 * Crawl the parents of an element up to finding a form.
 */
function forms_getForm(element) {
    while(element != null && element.tagName != "FORM") {
        element = element.parentNode;
    }
    return element;
}

/**
 * Move a named element as an immediate child of the <body> element.
 * This is required for help popups inside <wi:group> tabs. The reason is that CSS positioning
 * properties ("left" and "top") on a block with a "position: absolute" are actually relative to
 * the nearest ancestor that has a position of "absolute", "relative" or "fixed".
 * See http://www.w3.org/TR/CSS21/visudet.html#containing-block-details $4
 */

function forms_moveInBody(element) {
    element.parentNode.removeChild(element);
    document.body.appendChild(element);
}

/**
 * Create a popup window for a named element.
 *
 * @param id the ID of the element to make a popup with.
 */
function forms_createPopupWindow(id) {
    var result = new PopupWindow(id);
    result.autoHide();
    // add to onload handlers
    result.forms_id = id;
    result.forms_onload = function() {
        forms_moveInBody(document.getElementById(this.forms_id));
    }
    forms_onloadHandlers.push(result);
    return result;
}


function forms_createOptionTransfer(id, submitOnChange) {
    var result = new OptionTransfer(id + ".unselected", id);
    result.setAutoSort(true);
    // add to onload handlers
    result.forms_id = id;
    result.forms_onload = function() {
        var form = forms_getForm(document.getElementById(this.forms_id));
        this.init(form);
        sortSelect(this.left);
        sortSelect(this.right);
    }
    result.submitOnChange = submitOnChange;
    result.forms_transferLeft = function() {
        this.transferLeft();
        if (this.submitOnChange) {
            forms_submitForm(document.getElementById(this.forms_id));
        }
    }
    result.forms_transferRight = function() {
        this.transferRight();
        if (this.submitOnChange) {
            forms_submitForm(document.getElementById(this.forms_id));
        }
    }
    result.forms_transferAllLeft = function() {
        this.transferAllLeft();
        if (this.submitOnChange) {
            forms_submitForm(document.getElementById(this.forms_id));
        }
    };
    result.forms_transferAllRight = function() {
        this.transferAllRight();
        if (this.submitOnChange) {
            forms_submitForm(document.getElementById(this.forms_id));
        }
    };
    forms_onloadHandlers.push(result);
    
    // add to onsubmit handlers
    result.forms_onsubmit = function() {
        // Select all options in the "selected" list to that
        // its values are sent.
        selectAllOptions(this.right);
    }
    forms_onsubmitHandlers.push(result);
    return result;
}


/**
 * Show a tab in a <wi:group>
 *
 * @param tabgroup (string) name of the <wi:group>
 * @param idx (integer) index of the selected tab
 * @param length (integer) total number of tabs
 * @param state (string, optional) name of the input storing the tabgroup state
 */
function forms_showTab(tabgroup, idx, length, state, form) {
    for (var i = 0; i < length; i++) {
        // Change tab status (selected/unselected)
        var tab = document.getElementById(tabgroup + "_tab_" + i);
        if (tab != null) {
            tab.className = (i == idx) ? 'forms-tab forms-activeTab': 'forms-tab';
        }
        // Change tab content visibilty
        var tabitems = document.getElementById(tabgroup + "_items_" + i);
        if (tabitems != null) {
            tabitems.style.display = (i == idx) ? '' : 'none';
        }
    }
    // Change state value
    if (state.length > 0) {
    	if (document.forms[form][state] != undefined)
    		document.forms[form][state].value = idx;
    }
}

/****************************************************************************
 ****************************************************************************
 ****************   NON-CFORMS SCRIPTS USED IN THE PORTAL *******************
 ****************************************************************************
 **************************************************************************** 
 */

/**
 * Check all checkboxes on a given form
 * 
 * Use case
 * 
 * form
 *    input type="checkbox"/
 *    ...
 *    button onclick="checkUncheckAll(this.form)"/
 * /form
 */
function checkUncheckAll(aForm, checkIt) {
    if (checkIt == undefined) checkIt = true;

    for(var i = 0; i < aForm.length; i++) {
      if (aForm[i].type == 'checkbox') aForm[i].checked = checkIt;
    }
}

/**
 * Retrieve values of all checkboxes with the specified name
 * on the form and concatenate them into a string to be used 
 * as a part of url  
 */
function buildParameterStringForRequestUrl(aForm, formFieldName) {
    if (aForm == undefined || formFieldName == undefined)
        return "";
    
    var resultString = "";
    
    for(var i = 0; i < aForm.length; i++) {
        if (aForm[i].type == 'checkbox') {            
	        if (aForm[i].name == formFieldName && aForm[i].checked) {
	            if (i != 0)
	                resultString += "&";
	            resultString += formFieldName + "=" + aForm[i].value;
	        }
        }
    }
    
    return resultString;
}

/*
 * STYLING SCRIPTS
 */

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if (document.getElementById && document.getElementById(objectId)) {
    // W3C DOM
    return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility

function changeObjectDisplay(objectId, newDisplay) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.display = newDisplay;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility

/*
 * END OF STYLING SCRIPTS
 */

function debug(message){
    if(window.console) {
		window.console.log(message);
	} 
}

/*
 * PROGRESS BAR SCRIPT
 */
var progressEnd = 20;			// set to number of progress <span>'s.
var progressColor = 'blue';		// set to progress bar color
var progressInterval = 500;	// set to time between updates (milli-seconds)

var progressAt = progressEnd;
var progressTimer;

function progress_clear() {
	for (var i = 1; i <= progressEnd; i++) 
	    document.getElementById('progress'+i).style.backgroundColor = 'transparent';

	progressAt = 0;
}

function progress_update() {
	progressAt++;
	if (progressAt > progressEnd)
	    progress_clear();
	else {
	    var progressElement = document.getElementById('progress'+progressAt);
	    progressElement.style.backgroundColor = progressColor;
	}
	progressTimer = setTimeout('progress_update()',progressInterval);
}

function progress_stop() {
	clearTimeout(progressTimer);
	progress_clear();
}

function show_progress() {
    var progressBarElement = document.getElementById('progressBar');
    changeObjectDisplay('progressBar', 'block');
    progress_update();
}

function progress_cancel(newWin){
    document.getElementById('progress_message').innerHTML = 'Cancelling...';
    progress_stop();
    
    if (newWin == 'true') {
        window.close();
    } else {
        window.location.replace('portal');
    }
}

// progress_update();		// start progress bar

/*
 * Shows a popup window with the specified link, name and dimensions
 * 
 * link - Either <a href=...> tag for which the value of href is used as the URL of the popup
 *        or a URL itself
 * name - name of the window to be opened (not title)
 * isFull - optional boolean flag indicating that location, menubar and scrollbars should be displayed when set to true. If not set,
 *      then the controls are not shown
 * dimensions - optional parameter that allows to specify the dimensions of the popup.
 *        if it's not specified, 550x350 will be used.
 * 
 * Return
 *      void
 */
function showWindow(link, name, isFull, dimensions) {
    openWindow(link, name, isFull, dimensions);
    return false;
}

/*
 * Shows a popup window with the specified link, name and dimensions
 * 
 * link - Either <a href=...> tag for which the value of href is used as the URL of the popup
 *        or a URL itself
 * name - name of the window to be opened (not title)
 * isFull - optional boolean flag indicating that location, menubar and scrollbars should be displayed when set to true. If not set,
 *      then the controls are not shown
 * dimensions - optional parameter that allows to specify the dimensions of the popup.
 *        if it's not specified, 550x350 will be used.
 * 
 * Return
 *      returns a new window
 */
function openWindow(link, name, isFull, dimensions) {
    if (isFull == undefined)
        isFull = false;
    if (dimensions == undefined)
        dimensions = 'width=550,height=350'; 
    
    var url = (link.href) ? link.href : link;
    var controls = (isFull) ? 'location=1,menubar=1,status=1,toolbar=1,' : 'location=0,menubar=0,status=0,toolbar=0,';    
    var newWin = window.open(url, name, controls + 'resizable=1,scrollbars=1,top=50,left=50,screenX=50,screenY=50,' + dimensions);
    if (newWin.focus) 
        newWin.focus();
    return newWin;
}

/*
 * Looks up the object with the specified id on the 
 * currenly displayed page
 * 
 * name - id of the HTML element to be lookedup
 * 
 * Return
 *      Returns the HTML element with the specified id or null if
 *      such an element doesn't exist
 */
function getObj(name) {
  var obj = null;
  if (document.getElementById)
    obj = document.getElementById(name);
  else if (document.all)
    obj = document.all[name];
  else if (document.layers)
    obj = document.layers[name];
  
  return obj;
}

/*
 * Adds text with the specified text id to the list of my texts
 * 
 * textId - identifier of the text to add
 * topicId - identifier of the topic to add text to. This value is
 *           optional, if it's not specified, general topic will be
 *           used for adding texts. 
 */
function addToFavorites(link, textId, topicId) {
  if (window.opener&&window.opener.location) {
    window.opener.location.href='/portal/public2private?text-id=' + textId + '&amp;topic-id=' + topicId;
    
    // disable link to avoid clicking same link over again 
    link.removeAttribute('href');
    link.removeAttribute('onclick');
    // link.style.display="none";
    alert('Added text successfully'); 
  } else 
    alert('We are sorry, the text can not be added.');
  return false;
}
