/*





*/
// (C) Copyright 2003-2009 Nuxeo SAS <http://nuxeo.com>
// (C) Copyright 2010 AFUL <http://aful.org/>
// Authors:
// M.-A. Darche
// Tarek Ziade
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.

var msie5 = (navigator.userAgent.indexOf('MSIE 5') != -1);

//************************************************************
// Folder content
var isSelected = false;

function toggleSelect(toggleSelectButton, selectAllText, deselectAllText) {
  formElements = toggleSelectButton.form.elements;

  if (isSelected) {
    for (i = 0; i < formElements.length; i++) {
      formElements[i].checked = false;
    }
    isSelected = false;
    toggleSelectButton.value = selectAllText;
  } else {
    for (i = 0; i < formElements.length; i++) {
      formElements[i].checked = true;
    }
    isSelected = true;
    toggleSelectButton.value = deselectAllText;
  }
}

//************************************************************
/**
 * Toggles an element's visibility.
 * Function to show tooltips.
 * If your element is a span, you must use inline display instead of block
 */
function toggleElementVisibility(id) {
  element = document.getElementById(id);
  if (element) {
    if (element.style.visibility == 'hidden') {
      element.style.visibility = 'visible';
      if (element.tagName == 'DIV') {
        element.style.display = 'block';
      } else if (element.tagName == 'SPAN') {
        element.style.display = 'inline';
      } else {
        element.style.display = 'block';
      }
    } else {
      element.style.visibility = 'hidden';
      element.style.display = 'none';
    }
  }
}

/**
 * Makes visible or hide an element given its ID.
 */
function showElement(show, id) {
  element = document.getElementById(id);
  if (element) {
    if (show) {
      element.style.visibility = 'visible';
      if (element.tagName in ['DIV', 'P']) {
        element.style.display = 'block';
      } else {
        element.style.display = 'inline';
      }
    } else {
      element.style.visibility = 'hidden';
      element.style.display = 'none';
    }
  }
}

//************************************************************
/**
 * Removes empty spaces at the beginning and end of the given string.
 */
function trim(s) {
  if (s) {
    return s.replace(/^\s*|\s*$/g, "");
  }
  return "";
}

//************************************************************
/**
 * Opens a link in a new window.
 * Returns false to prevent the browser from following the actual href.
 *
 * cf. http://openweb.eu.org/articles/popup/
 */
function openLinkInPopup(url) {
    // Call to prototype lib
    var dimension = Element.getDimensions(document.body);
    var height = dimension.height;
    var width = dimension.width;
    newWindow = window.open(url, 'cps_popup',
                            'height=' + height + ',width=' + width + ',resizable=yes,menubar=yes');
    if (window.focus) {
        newWindow.focus();
    }
    return false;
}

//************************************************************
/**
 * XXX ?
 */
function checkEmptySearch(formElem) {
  var query = trim(formElem.SearchableText.value);
  if (query != '') {
    formElem.SearchableText.value = query;
    return true;
  }
  formElem.SearchableText.value = query;
  formElem.SearchableText.focus();
  return false;
}

//************************************************************
/**
 * Sets focus on <input> elements that have a class attribute
 * containing the class 'focus'.
 * Examples:
 * <input type="text" id="username" name="__ac_name" class="focus"/>
 * <input type="text" id="searchableText" class="standalone giant focus"/>
 *
 * This function does not work on crappy MSIE5.0 and MSIE5.5.
 */
function setFocus() {
  if (msie5) {
    return false;
  }
  var elements = document.getElementsByTagName('input');
  for (var i = 0; i < elements.length; i++) {
    var nodeClass = elements[i].getAttributeNode('class');
    //alert("nodeClass = " + nodeClass);
    if (nodeClass) {
      var classes = nodeClass.value.split(' ');
      for (var j = 0; j < classes.length; j++) {
        if (classes[j] == 'focus') {
          elements[i].focus();
          return true;
        }
      }
    }
  }
}

/**
 * Validates that the input fields designated by the given ids are not empty.
 * It returns true if all the input fields are not empty, it returns false
 * otherwise.
 * Example:
 * <form onsubmit="return validateRequiredFields(['field1', 'field2'],
 * ['Title', 'Comments'], 'are empty while they are required fields.')">
 */
function validateRequiredFields(fieldIds, fieldLabels, informationText) {
  for (i = 0; i < fieldIds.length; i++) {
    element = document.getElementById(fieldIds[i]);
    if (element && !element.value) {
      window.alert("'" + fieldLabels[i] + "' " + informationText);
      return false;
    }
  }
  return true;
}

//************************************************************
/**
 * XXX ?
 */
function getSelectedRadio(buttonGroup) {
  if (buttonGroup[0]) {
    for (var i=0; i<buttonGroup.length; i++) {
      if (buttonGroup[i].checked) {
        return i;
      }
    }
  } else {
    if (buttonGroup.checked) { return 0; }
  }
  return -1;
}

/**
 * XXX ?
 */
function getSelectedRadioValue(buttonGroup) {
  var i = getSelectedRadio(buttonGroup);
  if (i == -1) {
    return "";
  } else {
    if (buttonGroup[i]) {
    return buttonGroup[i].value;
    } else {
    return buttonGroup.value;
    }
  }
}

/**
 * XXX ?
 */
function getSelectedRadioId(buttonGroup) {
  var i = getSelectedRadio(buttonGroup);
  if (i == -1) {
    return "";
  } else {
    if (buttonGroup[i]) {
      return buttonGroup[i].id;
    } else {
      return buttonGroup.id;
    }
  }
}

/**
 * Return the label content corresponding to a radio selection
 */
function getSelectedRadioLabel(buttonGroup) {
  var id = getSelectedRadioId(buttonGroup);
  if (id == "") {
    return "";
  } else {
    for (var i=0; i<document.getElementsByTagName("label").length; i++) {
      var element_label = document.getElementsByTagName("label")[i];
      if (element_label.htmlFor == id) {
        return element_label.firstChild.nodeValue;
      }
    }
  }
}


//************************************************************
/**
 * Highlights the searched terms.
 *
 * From Geir Bækholt, adapted for CPS
 */
function highlightSearchTerm() {
  // TODO: The way the strings to search are retrieved by the JavaScript
  // used for the highlighting is not strong enough and can break very easily.
  // This should be improved.
  var query_elem = document.getElementById('resultSearchText');
  if (!query_elem) {
    return false;
  }
  var query = query_elem.value;
  // _robert_ ie 5 does not have decodeURI
  if (typeof decodeURI != 'undefined') {
    query = unescape(decodeURI(query)); // thanks, Casper
  }
  else {
    return false;
  }
  if (query) {
    queries = query.replace(/\+/g,' ').split(/\s+/);
    // make sure we start the right place and not higlight menuitems or breadcrumb
    searchresultnode = document.getElementById('searchResults');
    if (searchresultnode) {
      for (q=0;q<queries.length;q++) {
        // don't highlight reserved catalog search terms
        if (queries[q].toLowerCase() != 'not'
          && queries[q].toLowerCase() != 'and'
          && queries[q].toLowerCase() != 'or') {
          climb(searchresultnode,queries[q]);
        }
      }
    }
  }
}

function climb(node, word){
  // traverse childnodes
  if (! node){
    return false;
  }
  if (node.hasChildNodes) {
    var i;
    for (i=0;i<node.childNodes.length;i++) {
      climb(node.childNodes[i],word);
    }
    if (node.nodeType == 3) {
      checkforhighlight(node, word);
      // check all textnodes. Feels inefficient, but works
    }
  }
}

function checkforhighlight(node,word) {
  ind = node.nodeValue.toLowerCase().indexOf(word.toLowerCase());
  if (ind != -1) {
    if (node.parentNode.className != "highlightedSearchTerm"){
      par = node.parentNode;
      contents = node.nodeValue;
      // make 3 shiny new nodes
      hiword = document.createElement("span");
      hiword.className = "highlightedSearchTerm";
      hiword.appendChild(document.createTextNode(contents.substr(ind,word.length)));
      par.insertBefore(document.createTextNode(contents.substr(0,ind)),node);
      par.insertBefore(hiword,node);
      par.insertBefore(document.createTextNode( contents.substr(ind+word.length)),node);
      par.removeChild(node);
    }
  }
}

//************************************************************
/**
 * searchLanguage widget functions
 * used to auto select languages checkbox/radio
 * cf CPSSchemas/skins/cps_schemas/widget_searchlanguage_render.pt
 */
function searchLanguageCheckSelected(languages, no_language, language) {
  var count=0;
  for (var i=0; i<languages.length; i++) {
    if (languages[i].checked) {
      count++;
    }
  }
  no_language.checked = (count <= 0);
  language.checked = (count > 0);
}

function searchLanguageClearSelected(languages) {
  for (var i = 0; i<languages.length; i++) {
    languages[i].checked = 0;
  }
}

function toggleLayers(more_block, more_items) {
  var objMoreBlock = document.getElementById(more_block).style;
  var objMoreItems = document.getElementById(more_items).style;
  if(objMoreBlock.display == "block")
    objMoreBlock.display = "none";
  if(objMoreItems.display == "none")
    objMoreItems.display = "block";
}

//************************************************************

// This code relies on the Prototype library
function getSelectedDocumentsTitles() {
  var titles = [];
  var elems_selected = $$('table#folder_content input:checked');
  for (var i = 0; i < elems_selected.length; i++) {
    var elem_selected = elems_selected[i];
    var document_id = elem_selected.id.substring(3);
    var elem_link = $$('table#folder_content a[id="'+ document_id +'"]')[0];
    // eleme_link IDs are made with "cb_" (3 chars long) then the document ID
    // Prototype does not (yet?) provide a crossbrowser solution for getting
    // inner text.
    // textContent is standard DOM3
    // innerText   is proprietary Microsoft
    var text = elem_link.innerText || elem_link.textContent;
    // The strip method is provided by Prototype
    var text_stripped = text.strip();
    titles.push(text_stripped);
  }
  return titles.join("\n");
}

/**
 * Namespace
 */
var org = (typeof org == 'undefined') ? {}: org;
org.cps_cms = {};

org.cps_cms.InformationMessageFetcher = {

  cookie_name: 'cps_information_message_last_acknowledged_time',
  portal_url: null,
  check_delay_initial: null,
  check_delay: null,

  markInformationMessageAsRead: function() {
    // the number of milliseconds since the Epoch
    Cookie.set(this.cookie_name, new Date().getTime(), 365, '/');
    //alert("Cookie set");
  },

  check_method_url: function() {
    return this.portal_url + '/portal_information_message/check';
  },

  display_html_url: function() {
    return this.portal_url + '/information_message';
  },

  continuousCheckForInformationMessage: function() {
    //alert("continuousCheckForInformationMessage ...");
    var that = this;
    // First check after X seconds, typically a small time,
    // so that users starting to work on a page are warned early, but not too
    // fast so that users browsing fast through the portal pages don't generate
    // too much check calls to the server.
    window.setTimeout(function() { that.checkForInformationMessage(); },
      that.check_delay_initial * 1000);
    // Then continuous check every Y seconds, typically a longer time
    window.setInterval(function() { that.checkForInformationMessage(); },
      that.check_delay * 1000);
  },

  // This code relies on the Prototype library
  checkForInformationMessage: function() {
    //alert("checkForInformationMessage check_method_url() = " + this.check_method_url());
    var that = this;
    new Ajax.Request(that.check_method_url(), {
                       method: 'get',
                       onSuccess: function(transport) {
                         var response = transport.responseText;
                         //alert("Response: [" + response + "]");
                         if (response) {
                           //alert("There is a response");
                           var display = false;
                           var last_acknowledged_time = Cookie.get(that.cookie_name);
                           //alert("last_acknowledged_time: " + last_acknowledged_time);
                           if (!last_acknowledged_time ||
                               isNaN(Number(last_acknowledged_time))) {
                             display = true;
                           }
                           else {
                             if (Number(response) > Number(last_acknowledged_time))
                               display = true;
                           }
                           if (display)
                             that.displayInformationMessage();
                         } else {
                           //alert("There isn't any information message");
                         }
                       },
                       onFailure: function() {
                         //alert("Something went wrong with checkForInformationMessage");
                       }
                     });
  },

  displayInformationMessage: function() {
    //alert("displayInformationMessage using display_html_url() = " + this.display_html_url());
    new Ajax.Request(this.display_html_url(), {
                       method: 'get',
                       onSuccess: function(transport) {
                         // Injecting the retrieved HTML into the current HTML page
                         var html = transport.responseText || "No HTML found";
                         var info_message_elem = document.createElement('div');
                         info_message_elem.innerHTML = html;
                         document.body.insertBefore(info_message_elem,
                                                    document.body.firstChild);
                         // document.body.appendChild(info_message_elem);
                         var dimension = Element.getDimensions(document.body);
                         var height = dimension.height;
                         var width = dimension.width;
                         $('informationMessageBackground').setStyle({height: height + 'px', width: width + 'px'});
                         $('informationMessageBackground').setOpacity(0.7);
                         $('informationMessageOkButton').focus();
                       },
                       onFailure: function() {
                         alert("Something went wrong with displayInformationMessage");
                       }
                     });
  }
};


// Local Variables:
// mode: js2
// End:
// vim: set filetype=javascript:

