// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name portfolio.min.js
// ==/ClosureCompiler==

/* JSLint configuration */
/*global PORTFOLIO, $, jQuery */

if (typeof PORTFOLIO === 'undefined' ) {
  var PORTFOLIO={};
}


PORTFOLIO.addCollectableElement = function(id,title,type) {

  if (!( id && title && type )) {
    return false;
  }

  if (!PORTFOLIO.elementCollection) {
    PORTFOLIO.elementCollection=[];
  }

  PORTFOLIO.elementCollection.push({
    id    : id,
    title : title,
    type  : type
  });

  return true;

};

PORTFOLIO.showAddCollectionWindow = function(id) {

  var el, tbody, i, content, item, tbody_el;

  if(!PORTFOLIO.elementCollection) {
    alert(PORTFOLIO.gettext('No element collection found!'));
    return false;
  }

  if(!PORTFOLIO.elementCollection.length > 0 ) {
    alert(PORTFOLIO.gettext('No collectable elements found!'));
    return false;
  }

  //console.dir(PORTFOLIO.elementCollection);

  el=document.getElementById(id);

  if (!el) {
    return false;
  }
  if ( el.style.display=='block') {
    el.style.display='none';
//    document.getElementById('colButSwtch').innerHTML='&#187;';
    return false;
  }
  tbody=el.getElementsByTagName('tbody');
  if(tbody && tbody[0] ) {
    tbody=tbody[0];
  }

  if(tbody) {

    // Remove any existing child nodes
    while(tbody.lastChild) {
      tbody.removeChild(tbody.lastChild);
    }

    // Insert new nodes
    for(i=0; i < PORTFOLIO.elementCollection.length; i++) {
      item=PORTFOLIO.elementCollection[i];
      if (item.id && item.title && item.type) {

        var tr_el=document.createElement('tr');
        tbody.appendChild(tr_el);

        var td_el=document.createElement('td');
        tr_el.appendChild(td_el);

        var input_el=document.createElement('input');
        input_el.type='checkbox';
        input_el.name='element';
        input_el.value=item.id;
        td_el.appendChild(input_el);
        input_el.checked=true; // IE doesn't allow checked to be set before the element is appended, *sigh*

        // It seems like IE6 doesn't like one text node with the combined string in it
        // This is because the width of the string causes the table to overflow, and this creates scrollbars,
        // which is handled wrong by IE6.
        var td2_el=document.createElement('td');
        tr_el.appendChild(td2_el);
        td2_el.appendChild(document.createTextNode(item.type + ":"));

        var td3_el=document.createElement('td');
        tr_el.appendChild(td3_el);
        td3_el.appendChild(document.createTextNode(item.title));

      }
    }

  }
//  document.getElementById('colButSwtch').innerHTML='&#171;';
  el.style.display='block';

  return true;

};

PORTFOLIO.reorderAllEvents = function() {
  var eventCollection = PORTFOLIO.events;
// Hide the variable window.console temporary. Seem to make trouble for Safari. 
//    if (window.console) 
//       { console.dir(eventCollection) };

  var reorderedEventCollection=eventCollection;
  return reorderedEventCollection;
};

/*
 Fetches translated string from the message catalog.
 Input: Original string (in English)
 Output: Translated string (default is input string)
 Uses PORTFOLIO.client_language to determine locale
*/
PORTFOLIO.gettext=function(str) {
    /* Client language not set */
    if (! PORTFOLIO.client_language ) { return str; }

    /* Lookup table must exist */
    if (! PORTFOLIO.messages ) { return str; }

    /* Original string (msgid) must exist */
    if (! PORTFOLIO.messages[str] ) { return str; }

    /* Translation must exist */
    if (! PORTFOLIO.messages[str][PORTFOLIO.client_language] ) { return str; }

    /* Everything is ok, return translated string */
    return PORTFOLIO.messages[str][PORTFOLIO.client_language];
};

PORTFOLIO.loadContentEditor = function(object_type,form_id) {
  //alert(object_type + ' ' + form_id);
  var formObj = document.getElementById(form_id);
  var content_editor = document.getElementById('editor_'+object_type);
  if (!content_editor){
    return;
  }
  var split_custom_init = formObj.custom_init.value.split('\|');
  var player_name = '';
  for (i = 0; i < split_custom_init.length; i++){
    var name_value = split_custom_init[i].split('\=');
    if (name_value[0] == 'player'){
      player_name =name_value[1];
    }
  }
  content_editor.setExercise(player_name,formObj.content.value);
  formObj.content.style.display = 'none';
// if NN6 then OK to use the standard setAttribute
  if ((!document.all) && (document.getElementById)){
   formObj.setAttribute('onsubmit','return PORTFOLIO.submitContentEditor(\''+object_type+'\',\''+form_id+'\');');
  }    
//workaround for IE 
  else if ((document.all) && (document.getElementById)){
    formObj.onsubmit = new Function('return PORTFOLIO.submitContentEditor(\''+object_type+'\',\''+form_id+'\')');
  }
  return 1;
};

PORTFOLIO.submitContentEditor=function(object_type,form_id){
  var formObj = document.getElementById(form_id);
  var content_editor = document.getElementById('editor_'+object_type);
  if (!content_editor){
    return;
  }
  if (content_editor.isValidExercise() == false){ 
    alert( PORTFOLIO.gettext('Invalid exercise, check syntax.') );
    return false;
  }
  else{
    formObj.content.value = content_editor.getExercise();
    var player= 'player=' + content_editor.getAppID();
    player = player.replace('applet_','');
    var new_custom_init = player;
// Need to take care of eventually other values in custom_init
    var split_custom_init = formObj.custom_init.value.split('\|');
    for (var i = 0; i < split_custom_init.length; i++){
      var name_value = split_custom_init[i].split('\=');
      if (name_value[0] != 'player'){
        new_custom_init = new_custom_init + '|' + split_custom_init[i];
      }
    }
    formObj.custom_init.value = new_custom_init;
    return 1;
  }
};

PORTFOLIO.check_required = function(form_obj){
  var all_inputs = form_obj.getElementsByTagName('input');
  var all_labels = form_obj.getElementsByTagName('label');
  for (var i = 0; i < all_inputs.length; i++){
    var classAttr = all_inputs[i].getAttribute('class');
    if (classAttr && classAttr.match('required') && all_inputs[i].value == '') {
      var inp_name = all_inputs[i].getAttribute('name');
      if (inp_name == '') {
        inp_name = all_inputs[i].getAttribute('id');
      }
      var label_text = inp_name;                                // need a default value;
      for (var j = 0; j < all_labels.length; j++) {             // but try to find a label if present
// Firefox grabs object.getAttribute('for'), while IE may use object.getAttribute('htmlFor').
// Instead of object.getAttribute() and client-check we use the DOM1HTML binding object.htmlFor
// wich work for both.
        var label_for = all_labels[j].htmlFor;
        if (label_for == inp_name) {
          label_text = $(all_labels[j]).text();
        }
      }
      all_inputs[i].focus();
      alert(label_text + ' - ' + PORTFOLIO.gettext('required, please enter a value!') );
      return false;
    }
  }
 return true;
};

PORTFOLIO.toggle_checkboxes = function(form_obj,what_todo){
// what_todo: 'all' or 'none'. Anything else will invert
  var checkboxes = form_obj.getElementsByTagName('input');
  for (var i = 0; i < checkboxes.length; i++){
    if (checkboxes[i].type == 'checkbox'){
      switch(what_todo){
        case 'all' :
          checkboxes[i].checked = true; 
        break;
        case 'none' :
          checkboxes[i].checked = false; 
        break;
        default :
          checkboxes[i].checked = !checkboxes[i].checked; 
        break;
      }
    }
  }
};

PORTFOLIO.anything_checked = function(form_obj){
  var checkboxes = form_obj.getElementsByTagName('input');
  for (var i = 0; i < checkboxes.length; i++){
    if (checkboxes[i].type == 'checkbox' && checkboxes[i].checked){
      return true;
    }
  }
  form_obj.focus();
  return false;
};

//----------------- STRING FUNCTIONS --------------------------------//

// Remove all HTML-tags
PORTFOLIO.remove_html_tag = function(str){
  if (str==undefined){return str;}
  str = str.replace(/<\/p>/g, '\n');
  return str.replace(/<\/?[^>]+(>|$)/g, '');
};

// Removes leading whitespaces
PORTFOLIO.l_trim = function (str) {
  if (str==undefined){return str;}
  return str.replace( /^\s+/g, "" );
};

// Removes ending whitespaces
PORTFOLIO.r_trim = function(str) {
  if (str==undefined){return str;}
  return str.replace( /\s+$/g, "" );
};

// Removes leading and ending whitespaces
PORTFOLIO.trim = function (str) {
  if (str==undefined){return str;}
  return PORTFOLIO.l_trim(PORTFOLIO.r_trim(str));
};

//------------------------------------------------------------------//

/*
SELECT_CTRL is partly based on sort <SELECT> field script by Babvailiica
www.babailiica.com (http://www.babailiica.com/js/sorter/)
version 1.3
*/

PORTFOLIO.SELECT_CTRL={}; // namespace for manipulation of select element
// Necessary in MSIE to keep visual control 
PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView = function(obj){
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select"){
    return;
  }
  PORTFOLIO.SELECT_CTRL.toggle_line_numbers(obj,'check_setting');
  obj.focus(); // seem to be necessary to focus the select-element first...
  var last_selected = -1;
  for (var i = 1; i < obj.options.length; i++){
    if (obj.options[i].selected) {
      last_selected = i;
    }
  }
  if (last_selected < obj.options.length-1){
    obj.options[last_selected+1].selected = true;
    obj.options[last_selected+1].selected = false;
  }
  else if (last_selected != -1){
    obj.options[last_selected].selected = true;
  }
};

PORTFOLIO.SELECT_CTRL.selectall = function (obj) {
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select"){
    return;
  }
  for (var i=0; i<obj.length; i++){
    obj[i].selected = true;
  }
};

PORTFOLIO.SELECT_CTRL.selectnone = function(obj){
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select"){
    return;
  }
  for (var i=0; i<obj.length; i++){
    obj[i].selected = false;
  }
};

PORTFOLIO.SELECT_CTRL.invert_selection = function(obj){
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select"){
    return;
  }
  for (var i=0; i<obj.length; i++) {
    if (obj[i].selected) {
      obj[i].selected = false;
    }
    else {
      obj[i].selected = true;
    }
  }
};

PORTFOLIO.SELECT_CTRL.swap = function(obj){  // Need to be completly rewritten
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1){
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  var first_element = false;
  var last_element = false;
  for (var i=0; i<obj.length; i++){
    if (obj[i].selected) {
      if (first_element === false){
        first_element = i;
      } 
      else{
        last_element = i;
      }
    }
  }
  if (first_element === false || last_element === false){
    return false;
  }
  var tmp = [(document.body.innerHTML ? obj[first_element].innerHTML : obj[first_element].text), obj[first_element].value, obj[first_element].style.color, obj[first_element].style.backgroundColor, obj[first_element].className, obj[first_element].id, obj[first_element].selected];
  if (document.body.innerHTML){
    obj[first_element].innerHTML = obj[last_element].innerHTML;
  }
  else{
    obj[first_element].text = obj[last_element].text;
  }
  obj[first_element].value = obj[last_element].value;
  obj[first_element].style.color = obj[last_element].style.color;
  obj[first_element].style.backgroundColor = obj[last_element].style.backgroundColor;
  obj[first_element].className = obj[last_element].className;
  obj[first_element].id = obj[last_element].id;
  obj[first_element].selected = obj[last_element].selected;
  if (document.body.innerHTML) {
    obj[last_element].innerHTML = tmp[0];
  }
  else {
    obj[last_element].text = tmp[0];
  }
  obj[last_element].value = tmp[1];
  obj[last_element].style.color = tmp[2];
  obj[last_element].style.backgroundColor = tmp[3];
  obj[last_element].className = tmp[4];
  obj[last_element].id = tmp[5];
  obj[last_element].selected = tmp[6];
};

PORTFOLIO.SELECT_CTRL.sort2d = function(arrayName, element, num, cs) {
  if (num){
    for (var i=0; i<(arrayName.length-1); i++){
      for (var j=i+1; j<arrayName.length; j++){
        if (parseInt(arrayName[j][element],10) < parseInt(arrayName[i][element],10)){
          var dummy = arrayName[i];
          arrayName[i] = arrayName[j];
          arrayName[j] = dummy;
        }
      }
    }
  } 
  else {
    for (var i=0; i<(arrayName.length-1); i++){
      for (var j=i+1; j<arrayName.length; j++){
        if (cs){
          if (arrayName[j][element].toLowerCase() < arrayName[i][element].toLowerCase()) {
            var dummy = arrayName[i];
            arrayName[i] = arrayName[j];
            arrayName[j] = dummy;
          }
        } else {
          if (arrayName[j][element] < arrayName[i][element]){
            var dummy = arrayName[i];
            arrayName[i] = arrayName[j];
            arrayName[j] = dummy;
          }
        }
      }
    }
  }
};

/* sort the list!
by = 0 - order by text (default)
by = 1 - order by value
by = 2 - order by color
by = 3 - order by background color
by = 4 - order by class name
by = 5 - order by id
num = if true sorts numbers e.g. 2 before 10
cs = casesensitive e.g. a before Z*/

PORTFOLIO.SELECT_CTRL.listsort = function(obj, by, num, cs) {
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  by = (parseInt("0" + by,10) > 5) ? 0 : parseInt("0" + by,10);
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  var elements = [];
  for (var i=0; i<obj.length; i++) {
    elements[elements.length] = [ (document.body.innerHTML ? obj[i].innerHTML : obj[i].text), obj[i].value, (obj[i].currentStyle ? obj[i].currentStyle.color : obj[i].style.color), (obj[i].currentStyle ? obj[i].currentStyle.backgroundColor : obj[i].style.backgroundColor), obj[i].className, obj[i].id, obj[i].selected ];
  }
  PORTFOLIO.SELECT_CTRL.sort2d(elements, by, num, cs);
  for (i=0; i<obj.length; i++) {
    if (document.body.innerHTML) {
        obj[i].innerHTML = elements[i][0];
    }
    else {
        obj[i].text = elements[i][0];
    }
    obj[i].value = elements[i][1];
    obj[i].style.color = elements[i][2];
    obj[i].style.backgroundColor = elements[i][3];
    obj[i].className = elements[i][4];
    obj[i].id = elements[i][5];
    obj[i].selected = elements[i][6];
  }
};

PORTFOLIO.SELECT_CTRL.viceversa = function(obj, onlyselected) { 
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
   return false;
  }
  var elements = [];
  for (var i=obj.length-1; i>-1; i--) {
    if (obj[i].selected || !onlyselected) {
      elements[elements.length] = [ (document.body.innerHTML ? obj[i].innerHTML : obj[i].text), obj[i].value, obj[i].style.color, obj[i].style.backgroundColor, obj[i].className, obj[i].id, obj[i].selected ];
    }
  }
  var a = 0;
  for (i=0; i<obj.length; i++) {
    if (obj[i].selected || !onlyselected) {
      if (document.body.innerHTML) {
        obj[i].innerHTML = elements[a][0];
      }
      else {
        obj[i].text = elements[a][0];
      }
      obj[i].value = elements[a][1];
      obj[i].style.color = elements[a][2];
      obj[i].style.backgroundColor = elements[a][3];
      obj[i].className = elements[a][4];
      obj[i].id = elements[a][5];
      obj[i].selected = elements[a][6];
      a++;
    }
  }
};

// Move selected options one row up
PORTFOLIO.SELECT_CTRL.up = function(obj){
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  var sel = [];
  for (var i=0; i < obj.length; i++) {
    if (obj[i].selected == true) {
      sel[sel.length] = i;
    }
  }
  for (i in sel) {
    if (sel[i] != 0 && !obj[sel[i]-1].selected) {
      obj.insertBefore(obj[sel[i]],obj[sel[i]-1]);
    }
  }
  PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView(obj);
};

// Move selected options one row down
PORTFOLIO.SELECT_CTRL.down = function(obj){
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  var sel = [];
  for (var i = obj.length-1; i > -1; i--) {
    if (obj[i].selected == true) {
      sel[sel.length] = i;
    }
  }
  for (i in sel) {
    if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
      obj.insertBefore(obj[sel[i]+1],obj[sel[i]]);
    }
  }
  PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView(obj);
};

// Move selected options to given line
PORTFOLIO.SELECT_CTRL.move_selection_to = function(obj,insertpoint) { // Added by frode@rustoy.no
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  var sel = [];
  for (var i=0; i < obj.length; i++) {
    if (obj[i].selected) {
      sel[sel.length] = i;
    }
  }
  insertpoint = prompt( PORTFOLIO.gettext('Move selection before number:') ,0);
  if (!insertpoint) {
    return false;
  }
  else if (!PORTFOLIO.is_integer(insertpoint)) {
    alert( PORTFOLIO.gettext('Not a valid number:') + ' "'+insertpoint+'"');
    return false;
  }
  else {
    insertpoint--;
    if (insertpoint < 0 || insertpoint > obj.length-1) {
      alert( PORTFOLIO.gettext('Number must be in the range 1 to') + ' ' + obj.length);
      return false;
    }
    else if (insertpoint >= sel[0] && insertpoint <= sel[sel.length-1]) {
      alert( PORTFOLIO.gettext('Can not move selection onto itself or between selected elements!') );
      return false;
    }
  }
  if (insertpoint < sel[0]) {
    PORTFOLIO.SELECT_CTRL.move_selection_upwards(obj,insertpoint); 
  }
  else {
    PORTFOLIO.SELECT_CTRL.move_selection_downwards(obj,insertpoint);
  }
};

// Move selected options upwards, default to top of list
PORTFOLIO.SELECT_CTRL.move_selection_upwards = function(obj,insertpoint) { // Completly rewritten by frode@rustoy.no
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  if (!insertpoint) {
   insertpoint = 0; // move to top by default...
  }
  for (var i=0;i<obj.length; i++) {
    if (obj[i].selected) {
      obj.insertBefore(obj[i],obj[insertpoint]);
      insertpoint++;
    }
  }
  PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView(obj);
};

// Move selected options to bottom of list
PORTFOLIO.SELECT_CTRL.move_selection_downwards = function(obj,insertpoint) { // Completly rewritten by frode@rustoy.no
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select" && obj.length < 2) {
    return false;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  if (!insertpoint) {
    insertpoint = obj.length; // move to bottom by default;
  }
  for (var i=obj.length-1; i > (-1); i--) {
    if (obj[i].selected) {
    if (insertpoint == obj.length) {
          obj.appendChild(obj[i]);
        }
    else {
          obj.insertBefore(obj[i],obj[insertpoint]);
    }
       insertpoint--;
    }
  }
  PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView(obj);
};

// Move selected options from one select list to another
PORTFOLIO.SELECT_CTRL.moveOptionsAcross = function(obj, toSelect) { // Added by frode@rustoy.no
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select") {
    return;
  }
  toSelect = (typeof toSelect == "string") ? document.getElementById(toSelect) : toSelect;
  if (toSelect.tagName.toLowerCase() != "select") {
    return;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  PORTFOLIO.SELECT_CTRL.selectnone(toSelect);
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].selected) {
      toSelect.appendChild(obj[i]);
      i--;
    }
  }
  PORTFOLIO.SELECT_CTRL.scrollSelectionIntoView(toSelect);
};

PORTFOLIO.SELECT_CTRL.toggle_line_numbers = function(obj,show) {
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select") {
    return;
  }
  if (show == 'check_setting') {
    if (obj.show_numbers) {
      show = obj.show_numbers;
    }
    else {
     return;
    }
    if (!show) {
      return;
    }
  }
  else {
    obj.show_numbers = show;
  }
  var MyRegExp= /\[\d{4}\] /;
  for (var i = 0; i < obj.length; i++) {
    obj[i].text = obj[i].text.replace(MyRegExp,''); // remove line numbers if present
    if (show == true) {
      var i_string = (i+1).toString();
      while (i_string.length < 4) {
        i_string = '0' + i_string;
      } 
      obj[i].text = '[' +i_string+'] ' + obj[i].text; // add new line numbers
    }
  }
};

PORTFOLIO.SELECT_CTRL.alert_nothing_selected = function(obj) {
  alert( PORTFOLIO.gettext('Nothing selected!') );
  obj.focus();
  return false;
};

PORTFOLIO.SELECT_CTRL.preview_selected_object = function(obj,url) {
  obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  if (obj.tagName.toLowerCase() != "select") {
    return;
  }
  if (obj.selectedIndex == -1) {
    return PORTFOLIO.SELECT_CTRL.alert_nothing_selected(obj);
  }
  var uuid = obj.options[obj.selectedIndex].value;
  var cmd='read_object';
  var pf_preview=window.open(url+'?cmd='+cmd+';object='+uuid+';no_framework=1','pf_preview','resizable=yes,menubar=no,toolbar=no,scrollbars=yes,hotkeys=no,width=650,height=500,top=100,left=100');
  pf_preview.window.focus();
};

PORTFOLIO.SELECT_CTRL.populate_select_from_textarea = function(text_area,select_element,separator,val,txt,sortkeys) {
  text_area = (typeof text_area == "string") ? document.getElementById(text_area) : text_area;
  if (text_area.tagName.toLowerCase() != "textarea") {
    return;
  }
  var textbuffer = text_area.value;
  select_element = (typeof select_element == "string") ? document.getElementById(select_element) : select_element;
  if (select_element.tagName.toLowerCase() != "select") {
    return;
  }
  while (select_element.length > 0) {
    select_element.removeChild(select_element[0]);
  }
  var show_numbers = false;
  if (select_element.show_numbers) {
     show_numbers = select_element.show_numbers; // check if line numbers should be added
  }
  var textarray = textbuffer.split('\n');
  var sortkeyarray = sortkeys.split(separator);
  for (var j = 0; j < textarray.length; j++) {
    if (textarray[j] != '') {
      var textfields = textarray[j].split(separator);
      if (show_numbers == true) {
        var j_string = (j+1).toString();
        while (j_string.length < 4) {
          j_string = '0' + j_string;
        }
        textfields[txt] = '[' +j_string+'] ' + textfields[txt]; // add new line numbers       
      }
      select_element.options[select_element.options.length] = new Option(textfields[txt],textfields[val]);
      for (var i = 0; i < sortkeyarray.length; i++) {
        var sortkey = 'sortkey'+(i+1);
        select_element.options[j][sortkey] = textfields[sortkeyarray[i]];
      }
    }
  }  
};

PORTFOLIO.SELECT_CTRL.populate_textarea_from_select = function(select_element,text_area,separator,sortkeys) {
  text_area = (typeof text_area == "string") ? document.getElementById(text_area) : text_area;
  if (text_area.tagName.toLowerCase() != "textarea") {
    return;
  }
  select_element = (typeof select_element == "string") ? document.getElementById(select_element) : select_element;
  if (select_element.tagName.toLowerCase() != "select") {
    return;
  }
  var newtext = '';
  var sortkeyarray = sortkeys.split(separator);
  for (var j = 0; j < select_element.length; j++) {
    var newline = '';
    for (var i = 0; i < sortkeyarray.length; i++) {
      newline += select_element.options[j][sortkeyarray[i]];
      if (i < sortkeyarray.length-1) {
        newline += separator;
      }
    }
   newline = newline.replace(/\[\d{4}\] /,''); // remove line numbers if present
   newtext += newline + '\n';
  }  
   text_area.value = newtext;
};

//----------------------- MANAGE_INST BEGIN ----------------------------//

PORTFOLIO.MANAGE_INST = {}; // namespace for manage_institution GUI

PORTFOLIO.MANAGE_INST.remember_last_separator_value = '';

PORTFOLIO.MANAGE_INST.selectOptions= [
  [ '',         PORTFOLIO.gettext('Ignore field') ],
  [ 'email',    PORTFOLIO.gettext('Email')        ],
  [ 'firstname',PORTFOLIO.gettext('First name')   ],
  [ 'lastname', PORTFOLIO.gettext('Last name')    ],
  [ 'username', PORTFOLIO.gettext('User name')    ],
  [ 'id',       PORTFOLIO.gettext('ID (uuid)')    ],
  [ 'password', PORTFOLIO.gettext('Password')     ],
  [ 'role',     PORTFOLIO.gettext('Role'), 'student/supervisor' ]
];

PORTFOLIO.MANAGE_INST.setForm = function(el) {
    if ( ! el ) {
        throw new SyntaxError("Element was not specified");
    }
    PORTFOLIO.MANAGE_INST.form = el;
    return true;
};

PORTFOLIO.MANAGE_INST.setTextUIContainer = function(el) {
    if ( ! el ) {
        throw new SyntaxError("Element was not specified");
    }
    PORTFOLIO.MANAGE_INST.textUIContainer = el;
    return true;
};

PORTFOLIO.MANAGE_INST.setTableUIContainer = function(el) {
    if ( ! el ) {
        throw new SyntaxError("Element was not specified");
    }
    PORTFOLIO.MANAGE_INST.tableUIContainer = el;
    return true;
};

PORTFOLIO.MANAGE_INST.showTableUI = function() {
    if ( ! PORTFOLIO.MANAGE_INST.form.separator.value ) {
        alert( PORTFOLIO.gettext('Need to select separator') );
        return false;
    }

    // Add table to DOM
    var newTable = document.createElement('table');
    $( PORTFOLIO.MANAGE_INST.tableUIContainer ).prepend(newTable);
    
    // Add THEAD part to table
    newTable.appendChild( PORTFOLIO.MANAGE_INST.makeTableHead() );

    // Add TBODY part to table
    // Head must be in DOM before this is run because it ( appendRow() )
    // uses select boxes in head
    var tableBody = PORTFOLIO.MANAGE_INST.makeTableBody();
    newTable.appendChild( tableBody );

    // Because of a strange rule in MSIE it is neccessary
    // to set checked after inserting the table into DOM
    $( 'input:checkbox', tableBody ).each(function() {
        this.checked = true;
    });

    $( PORTFOLIO.MANAGE_INST.textUIContainer  ).hide();
    $( PORTFOLIO.MANAGE_INST.tableUIContainer ).show();

    PORTFOLIO.MANAGE_INST.form._gui_mode[0].checked = true;
    return true;
};

PORTFOLIO.MANAGE_INST.showTextUI = function () {
    PORTFOLIO.MANAGE_INST.form._gui_mode[1].checked = true;
    if ( document.getElementById('usertable_body') ) {
        var allRows = document.getElementById('usertable_body').getElementsByTagName('tr');
        var separator = PORTFOLIO.MANAGE_INST.form.separator.value;
        var allStrings = '';
        for (var i = 0; i < allRows.length; i++) {
            var allCells = allRows[i].getElementsByTagName('td');
            var getString = '';
            var some_content_present = false;
            checkValue = allRows[i].getElementsByTagName('th')[0].getElementsByTagName('input')[0].checked;
            if (checkValue) {
                var passwdGiven = false;
                for (var j = 0; j < allCells.length; j++) {
                    var theInput= allCells[j].getElementsByTagName('input')[0];
                    var theName = theInput.getAttribute('name');
                    if (theName == 'null'){
                        theName = '';
                    }
                    var theValue = theInput.value;
                    if (theValue == 'null' || theValue == null) {
                        theValue = '';
                    }
                    if (theValue != '') {
                        some_content_present = true;
                    }
                    getString = getString + theValue;
                    if (j < allCells.length-1) {
                        getString += separator;
                    }
                }
                if ( some_content_present == true ) {
                    allStrings=allStrings+getString+'\n';
                }
            }
        }
        var selectArr = document.getElementById('usertable_head').getElementsByTagName('select');
        var selectString = '';
        for (var i = 0; i < selectArr.length; i++) {
            selectString += selectArr[i].options[selectArr[i].selectedIndex].value;
            if (i < selectArr.length-1) {
                selectString += separator;
            }
        }
        $( 'table', PORTFOLIO.MANAGE_INST.tableUIContainer ).remove();
        PORTFOLIO.MANAGE_INST.form.fields.value = selectString;
        PORTFOLIO.MANAGE_INST.form.users.value= allStrings;
        $( PORTFOLIO.MANAGE_INST.tableUIContainer ).hide();
        $( PORTFOLIO.MANAGE_INST.textUIContainer  ).show();
    }
};

PORTFOLIO.MANAGE_INST.makeTableHead = function() {
    var separator = PORTFOLIO.MANAGE_INST.form.separator.value;
    var activeFields = PORTFOLIO.MANAGE_INST.form.fields.value.split(separator);

    var tableHead = document.createElement('thead');
    tableHead.setAttribute('id','usertable_head');

    var newRow = document.createElement('tr');
    var newCell = document.createElement('th');
    newCell.style.width = '1em';

    var checkField = document.createElement('input');
    checkField.setAttribute('type','checkbox');
    checkField.setAttribute("disabled","disabled");
    checkField.style.visibility = 'hidden';
    newCell.appendChild(checkField);
    newRow.appendChild(newCell);

    var selectField;
    for (var i = 0; i < activeFields.length; i++) {
        newCell = document.createElement('th');
        selectField = document.createElement('select');
        for (var j = 0; j < PORTFOLIO.MANAGE_INST.selectOptions.length; j++) {
            selectField.options[selectField.options.length] = new Option(
                PORTFOLIO.MANAGE_INST.selectOptions[j][1],
                PORTFOLIO.MANAGE_INST.selectOptions[j][0]
            );
            if ( PORTFOLIO.MANAGE_INST.selectOptions[j][0] == activeFields[i] ) {
                selectField.options[j].selected='selected';
                if ( PORTFOLIO.MANAGE_INST.selectOptions[j][2] ) {
                    selectField.setAttribute('input_alternatives',PORTFOLIO.MANAGE_INST.selectOptions[j][2]);
                }
            }
        }
        $(selectField).change(function() {
            PORTFOLIO.MANAGE_INST.toggleColumn(this);
        });
        newCell.appendChild(selectField);
        newRow.appendChild(newCell);
    }
    tableHead.appendChild(newRow);
    return tableHead;
};

PORTFOLIO.MANAGE_INST.makeTableBody = function() {
    var tableBody = document.createElement('tbody');
    tableBody.setAttribute('id','usertable_body');

    // Add a new row for each line of import info
    // Will always add one empty line because [ "" ] is the result of split if value is ""
    var users = PORTFOLIO.MANAGE_INST.form.users.value.split('\n');
    for (var i = 0; i < users.length; i++) {
        PORTFOLIO.MANAGE_INST.appendRow(tableBody,users[i]);
    }
    return tableBody;
}

PORTFOLIO.MANAGE_INST.appendRow = function(tableBody,record_string) {
    var newRow = document.createElement('tr');
    var newCell = document.createElement('th');

    var checkField = document.createElement('input');
    checkField.setAttribute('type','checkbox');
    $(checkField).click(function() {
        PORTFOLIO.MANAGE_INST.toggleRow(this);
    });
    newCell.appendChild(checkField);
    newRow.appendChild(newCell);

    // Get rid of newlines
    record_string = record_string && record_string.replace(/\n/g,'');
    record_string = record_string && record_string.replace(/\r/g,'');

    // Split line according to separator
    var newUser = record_string
                ? record_string.split( PORTFOLIO.MANAGE_INST.form.separator.value )
                : [];

    var selectArr = $('select', PORTFOLIO.MANAGE_INST.tableUIContainer).get();
    for (var j = 0; j < selectArr.length; j++) {
        var newCell = document.createElement('td');
        var inputField = document.createElement('input');
        if (newUser[j]) {
            inputField.setAttribute('value',newUser[j]);
        }
        var fieldName = selectArr[j].options[selectArr[j].selectedIndex].value;
        inputField.setAttribute('name',fieldName);
        if (fieldName == '') {
            // "Ignore field" selected
            inputField.setAttribute('disabled','disabled');
            inputField.style.backgroundColor = "#ccc"; // visualize disabling in MSIE
        }
        if (selectArr[j].getAttribute('input_alternatives')) {
            var selectField = document.createElement('select');
            var selectOpt = selectArr[j].getAttribute('input_alternatives').split('/');
            for (var n= 0; n < selectOpt.length; n++) {
                selectField.options[selectField.options.length] = new Option(selectOpt[n],selectOpt[n]);
            }
        }
        inputField.setAttribute('type','text');
        newCell.appendChild(inputField);
        newRow.appendChild(newCell);
    }
    tableBody.appendChild(newRow);

    // Set checkbox active and focus first input field
    checkField.checked = true;
    $('input:text:first', newRow).focus();

    return true;
};

PORTFOLIO.MANAGE_INST.toggleColumn = function(selectBox) {
    // Because of checkboxes to the left
    var column = selectBox.parentNode.cellIndex-1;
    var selectValue = selectBox.options[selectBox.selectedIndex].value;
    if ( document.getElementById('usertable_body') ) {
        var setSelectIgnore = -1;
        var allRows = document.getElementById('usertable_body').getElementsByTagName('tr');
        for (var i = 0; i < allRows.length; i++) {
            var allCells = allRows[i].getElementsByTagName('td');
            for (var j = 0; j < allCells.length; j++) {
                var theInput= allCells[j].getElementsByTagName('input')[0];
                if (j == column) {
                    theInput.setAttribute('name',selectValue);
                    if (selectValue == '') {
                        theInput.disabled = 'disabled';
                        theInput.style.backgroundColor = "#ccc"; // visualise disabling in MSIE
                    }
                    else {
                        theInput.disabled = false;
                        theInput.style.backgroundColor = ""; // visualise enabling in MSIE
                    }
                }
                // Make sure that not two fields has the same name.....
                else if ( theInput.getAttribute('name') == selectValue && selectValue != '' ) {
                    setSelectIgnore = j;
                    theInput.setAttribute('name','');
                    theInput.disabled = 'disabled';
                    theInput.style.backgroundColor = "#ccc"; // visualise disabling in MSIE
                }
            }
        }
    }
    if ( setSelectIgnore > -1 ) {
        // Toggle the select to show that column is ignored
        var allSelects = document.getElementById('usertable_head').getElementsByTagName('select');
        allSelects[setSelectIgnore].options[0].selected =true;
    }
};

PORTFOLIO.MANAGE_INST.toggleRow = function(checkBox) {
    var selectArr = PORTFOLIO.MANAGE_INST.form.getElementsByTagName('select');
    var row = checkBox.parentNode.parentNode.rowIndex -1;
    var checkValue = checkBox.checked;
    if ( document.getElementById('usertable_body') ) {
        var allRows = document.getElementById('usertable_body').getElementsByTagName('tr');
        var allCells = allRows[row].getElementsByTagName('td');
        for (var j = 0; j < allCells.length; j++) {
            var theInput= allCells[j].getElementsByTagName('input')[0];
            var fieldName = selectArr[j].options[selectArr[j].selectedIndex].value;
            if (checkValue == false || fieldName == '') {
                theInput.disabled = 'disabled';
                theInput.style.backgroundColor = "#ccc"; // visualize disabling in MSIE
            }
            else {
                theInput.disabled = false;
                theInput.style.backgroundColor = ""; // visualize enabling in MSIE
            }
        }
    }
};


PORTFOLIO.MANAGE_INST.setSeparator = function(value) {
    if (value == 'other') {
        value = '';
        PORTFOLIO.MANAGE_INST.form.separator.focus();
    }
    PORTFOLIO.MANAGE_INST.form.separator.value = value;
};

//------------------------- MANAGE_INST END ----------------------------//

PORTFOLIO.is_uuid = function (string) {
  var MyRegExp = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
  var matchArray = string.toString().match(MyRegExp);
  if (matchArray && matchArray[0] != '') {
    return true;
  }
  else {
   return false;
  }
};

PORTFOLIO.is_integer = function (string) {
  var MyRegExp = /^\d+$/;
  var matchArray = string.toString().match(MyRegExp);
  if (matchArray && matchArray[0] != '') {
    return true;
  }
  else {
   return false;
  }
};

PORTFOLIO.ContainerBrowser=function(target_id,target_title,start_container_uuid) {
  return PORTFOLIO.fileBrowser('select','container',target_id,target_title,target_id,700,380,'',start_container_uuid);
};

PORTFOLIO.ObjectBrowser=function(target_id,target_title,start_container_uuid) {
//  return PORTFOLIO.fileBrowser('select','object',target_id,target_title,target_id,700,380,'',start_container_uuid);
  return PORTFOLIO.fileBrowser('select','object',null,target_title,target_id,700,380,'',start_container_uuid);
};

/* timeout-functions for automatic submit of a form */
/* initiated with call to PORTFOLIO.set_time_out    */
/* Sample:                                          */
/* PORTFOLIO.set_time_out('id_of_visual form_element_acting_as_clock',minutes,seconds,interrupt_interval); */

PORTFOLIO.timer_count_down = function (mm,ss) {
    PORTFOLIO.timeout_minutes = mm;
    PORTFOLIO.timeout_seconds=ss;
    if (PORTFOLIO.timeout_seconds==0) {
        PORTFOLIO.timeout_seconds = 60;
        PORTFOLIO.timeout_minutes--;
    }
    PORTFOLIO.timeout_seconds--;
    if (PORTFOLIO.timeout_seconds<10) {
        PORTFOLIO.timeout_seconds="0" + PORTFOLIO.timeout_seconds;
    }
    document.getElementById(PORTFOLIO.timer_id).value = PORTFOLIO.timeout_minutes+":"+PORTFOLIO.timeout_seconds;
    if ((PORTFOLIO.timeout_minutes==0) && (PORTFOLIO.timeout_seconds==0)) {
        PORTFOLIO.time_is_up();
    }
    else {
        setTimeout(function() { PORTFOLIO.timer_count_down(PORTFOLIO.timeout_minutes,PORTFOLIO.timeout_seconds); },1000);
    }
};

PORTFOLIO.time_is_up = function() {
    if (document.getElementById(PORTFOLIO.timer_submit_button)) {
        // in case button is not present
        document.getElementById(PORTFOLIO.timer_submit_button).click();
    }
    else {
        alert(PORTFOLIO.gettext("Your time is up!"));
    }
};

PORTFOLIO.start_quiz_timer = function(min,sec,timer_id,timer_submit_button) {
    if (document.forms.pf_quiz) {
        if (document.forms.pf_quiz.evaluate_quiz || document.forms.pf_quiz.send_quiz) {
            if (timer_id ) {
                PORTFOLIO.timer_id = timer_id;
            }
            else {
                PORTFOLIO.timer_id = 'display_quiz_timer';
            }
            if (timer_submit_button) {
                PORTFOLIO.timer_submit_button = timer_submit_button;
            }
            else {
                PORTFOLIO.timer_submit_button = 'evaluate_quiz';
            }
            setTimeout('PORTFOLIO.timer_count_down('+min+','+sec+')',1000);
        }
        else if (document.getElementById('pf_quiz_timer')) {
            document.getElementById('pf_quiz_timer').innerHTML = '';
        }
    }
};

/* dhtmlwindow.js */

PORTFOLIO.initColList = function() {
    if (document.getElementById('webfx_container') && document.getElementById('webfx_head') && document.getElementById('webfx_body') ) {
        PORTFOLIO.currentColumnList = new WebFXColumnList();
        var rc = PORTFOLIO.currentColumnList.bind(
            document.getElementById('webfx_container'),
            document.getElementById('webfx_head'),
            document.getElementById('webfx_body')
        );
        PORTFOLIO.currentColumnList.setSortTypes([TYPE_STRING_NO_CASE,TYPE_NUMBER,TYPE_STRING,TYPE_STRING]);
        PORTFOLIO.currentColumnList._setAlignment();
        //PORTFOLIO.currentColumnList.selectRow(3);
        //PORTFOLIO.currentColumnList.resize(640, 480);
        //PORTFOLIO.currentColumnList.sort(0);
    }
};

PORTFOLIO.selectRowByFilename = function(fileName) {
  var tbl = document.getElementById('columnlist_body');
  var rows = tbl.getElementsByTagName('tr');
  for (var tr = 0; tr < rows.length; tr++) {
    if (rows[tr].getAttribute('filename') == fileName) {
      PORTFOLIO.currentColumnList.selectRow(tr);
      PORTFOLIO.update_inputs(rows[tr],'/');
      return null;
    }
  }
  return null;
};

PORTFOLIO.selectRowByObjectId = function(id) {
    var tbl = document.getElementById('columnlist_body');
    var rows = tbl.getElementsByTagName('tr');
    for (var tr = 0; tr < rows.length; tr++) {
        if (rows[tr].getAttribute('id') == id) {
            PORTFOLIO.currentColumnList.selectRow(tr);
            return null;
        }
    }
    return null;
};

PORTFOLIO.ajaxpage = function(url, containerid,reportUpload) {
    var doAsyncron = true;
    var page_request = false;
    if (window.XMLHttpRequest) {
      // if Mozilla, Safari etc
      page_request = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
      // if IE
      try {
        page_request = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
      }
      try {
          page_request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e){
      }
    }
    else {
        return false;
    }

// NOE RART HER. HVORFOR loadpage TO STEDER?
    page_request.onreadystatechange=function() {
        PORTFOLIO.loadpage(page_request, containerid,reportUpload);
    };

    page_request.open('GET', url, doAsyncron);
    page_request.send(null);
    if (doAsyncron == false) {
        PORTFOLIO.loadpage(page_request, containerid,reportUpload);
    }
    return 1;
};

PORTFOLIO.loadpage = function(page_request,containerid,reportUpload) {
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
        document.getElementById(containerid).innerHTML=page_request.responseText;
        if (document.getElementById('currentcontainer_title') && document.getElementById('currentcontainer')) {
            if (document.getElementById('pf_browser_uuid')) {
                document.getElementById('pf_browser_uuid').value = document.getElementById('currentcontainer').value;
                if (document.getElementById('container')) {
                    document.getElementById('container').value = document.getElementById('currentcontainer').value;
                }
            }
            if (document.getElementById('filebrowser_title')) {
                document.getElementById('filebrowser_title').value = document.getElementById('currentcontainer_title').value;
            }
            if (document.getElementById('filebrowser_description')) {
                document.getElementById('filebrowser_description').value = document.getElementById('currentcontainer_description').value;
            }
            if (document.getElementById('pf_browser_typeof_uuid')) {
                document.getElementById('pf_browser_typeof_uuid').value = 'container';
            }
        }
        PORTFOLIO.initColList(); // In case WebFX
        if (reportUpload) {
            var splitLocalPath = document.getElementById('content_file').value.split('\\');
            var filename = splitLocalPath[splitLocalPath.length-1];
            PORTFOLIO.selectRowByFilename(filename);
            // Reset the upload form to prevent user from uploading same file twice;
            document.getElementById('uploadForm').reset();
            // Reset history for the hidden upload-frame to avoid problems if user try to reload window
            //history.back();
        }
    }
};

PORTFOLIO.doTransfer =false;

PORTFOLIO.giveTransferFeedback = function(url) {
    // Update the filelist after upload
    url += '?cmd=list;container='+document.getElementById('currentcontainer').value;
    PORTFOLIO.ajaxpage(
        url+';response=xml;server_xsl=list_element',
        'pf_fileBrowserInnerDiv',
        true
    );
    PORTFOLIO.doTransfer = false;
};

PORTFOLIO.get_row = function(table_element_id,num) {
  var tbl = document.getElementById(table_element_id);
  var rows = tbl.getElementsByTagName('tr');
  return rows[num];
};

/* Used by: PORTFOLIO.delete_selected() */
PORTFOLIO.doAjaxCmd = function(url,rowId) {
    var page_request = false;
    if (window.XMLHttpRequest) {
        // if Mozilla, Safari etc
        page_request = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                page_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    else {
        return false;
    }
    page_request.onreadystatechange = function() {
        PORTFOLIO.xmlCallBack(page_request,rowId);
    };
    page_request.open('GET', url, true);
    page_request.send(null);
    return 1;
};

/* Used by: PORTFOLIO.doAjaxCmd() */
PORTFOLIO.xmlCallBack = function(http_request,rowId) {
    if (http_request.readyState == 4) {
        if (http_request.status==200) {
            var xmldoc = http_request.responseXML;
            var pf_root_node = xmldoc.getElementsByTagName('portfolio').item(0);
            if (!pf_root_node) {
                alert(PORTFOLIO.gettext('Not Portfolio XML-response')); // +http_request.responseText);
                return false;
            }

            var response_node = pf_root_node.getElementsByTagName('response').item(0);
            var my_request = response_node.getAttribute("request");
            var message_text = response_node.firstChild.data;
            var status_text = response_node.getAttribute('status');
            var code_text = response_node.getAttribute('code');
            if (code_text < 200 || code_text > 299) {
                alert(message_text+'\n'+status_text+'\n'+code_text);
            }
            else {
                // File is deletede from database, time to remove from screen..
                PORTFOLIO.selectRowByObjectId(rowId);
                var row = PORTFOLIO.currentColumnList.getSelectedRange();
                PORTFOLIO.currentColumnList.removeRange(row);

                // NB MARKER NYTT OBJEKT ELLER FJERN PREVIEW_THUMB
                //PORTFOLIO.currentColumnList.selectRow(row);
                //var row = PORTFOLIO.currentColumnList.getSelectedRange();
                PORTFOLIO.update_inputs(-1,'/');
            }
        }
    }
    return 1;
};

PORTFOLIO.delete_selected = function() {

    var myArr = PORTFOLIO.currentColumnList.getSelectedRange();

    if (myArr.length) {
        if ( confirm( PORTFOLIO.gettext("Selected rows:") + " " + myArr.length + "\n" + PORTFOLIO.gettext('Delete now?') ) ) {
            var i=0;
            do {
                var row = PORTFOLIO.get_row('columnlist_body',myArr[i]);
                PORTFOLIO.doAjaxCmd(
                    '/?cmd=delete_'+row.getAttribute('objecttype')+';'+row.getAttribute('objecttype')+'_id='+row.getAttribute('id')+';from_outbox='+row.getAttribute('outbox')+';response=xml;',
                    row.getAttribute('id')
                );
                i+=1;
            } while (i < myArr.length);
            //PORTFOLIO.currentColumnList.removeRange(myArr);
        }
    }
    else {
        alert( PORTFOLIO.gettext('Nothing selected!') );
    }
};

PORTFOLIO.browser_show_imagethumb = function(row,url) {
    var thumb_div;
    var thumb_table = document.getElementById('filebrowser_imgthumb_container');
    if (thumb_table) {
        if (row == -1) {
            thumb_div.innerHTML = '';
        }
        else {
            var type = row.getAttribute('type');
            var mimetype = row.getAttribute('mimetype');
            var width = row.getAttribute('objectwidth');
            var height = row.getAttribute('objectheight');
            var title =  row.getAttribute('objecttitle');
            var maxwidth = thumb_table.offsetWidth -30; // Need space to show float left/right
            var maxheight = thumb_table.offsetHeight -20; // Need space to vertical-align
            //alert(width+' '+height);
            var thumb_div = document.getElementById('filebrowser_imgthumb');
            if (type == 'image') {
                thumb_div.innerHTML = '<img src="'+url+'thumbnail/'+row.getAttribute('id')+'/'+maxheight+'" />';
            }
            else if (type == 'audio' && mimetype == 'audio/mpeg') {
                thumb_div.innerHTML = '<object class="inline" type="application/x-shockwave-flash"data="'+PORTFOLIO.static_url+'musicplayer/player_slim.swf?autoplay=true&amp;song_title='+title+'&amp;song_url='+url+'?cmd=read;raw=1;response=http;object='+row.getAttribute('id')+'"width="250" height="17"><param name="movie" value="'+url+'/static/musicplayer/player_button.swf?autoplay=true&amp;autoload=true&amp;song_title='+title+'&amp;song_url='+PORTFOLIO.static_url+'?cmd=read;raw=1;response=http;object='+row.getAttribute('id')+'" />'+PORTFOLIO.gettext('Your browser does not support Flash content.')+'<a target="_blank" href="http://www.macromedia.com/go/getflashplayer/" rel="external">'+PORTFOLIO.gettext('Download Flash Player.')+'</a></object>';
            }
            else {
                thumb_div.innerHTML = '<img src="'+row.getElementsByTagName('img')[0].src+'" /><br />'+type+'<br /><small>'+mimetype+'</small>';
            }
        }
        var adjust_select = document.getElementById('preview_thumb_adjustment');
        var my_style = '';
        if (adjust_select) {
            my_style = adjust_select.options[adjust_select.selectedIndex].value;
            adjust_img_thumb(my_style);
        }
/*
        if (my_style != '') {
            my_style= ' style="'+my_style+'"';
        }
*/
    }
};

PORTFOLIO.update_inputs = function(row,url) {

    var myArr = PORTFOLIO.currentColumnList.getSelectedRange();
    if (document.getElementById('filebrowser_insert')) {
        if (row== -1) {
            document.getElementById('filebrowser_insert').disabled=true;
            document.getElementById('filebrowser_insert_link').disabled=true;
            document.getElementById('filebrowser_insert_uri').disabled=true;
            if (document.getElementById('filebrowser_preview')) {
                document.getElementById('filebrowser_preview').disabled=true;
            }
        }
        else {
            document.getElementById('filebrowser_insert').disabled=false;
            document.getElementById('filebrowser_insert_link').disabled=false;
            document.getElementById('filebrowser_insert_uri').disabled=false;
            if (document.getElementById('filebrowser_preview')) {
                document.getElementById('filebrowser_preview').disabled=false;
            }
        }
    }

    if (row == -1) {
        if ( document.getElementById('pf_updateOnServer') ) {
            document.getElementById('pf_updateOnServer').disabled=false;
        }
        if ( document.getElementById('pf_browser_uuid') ) {
            document.getElementById('pf_browser_uuid').value='';
        }
        if ( document.getElementById('pf_browser_typeof_uuid') ) {
            document.getElementById('pf_browser_typeof_uuid').value='';
        }
        if ( document.getElementById('filebrowser_title') ) {
            document.getElementById('filebrowser_title').value='';
        }
        if ( document.getElementById('filebrowser_description') ) {
            document.getElementById('filebrowser_description').value='';
        }
        if ( document.getElementById('filebrowser_mimetype') ) {
            document.getElementById('filebrowser_mimetype').value='';
        }
        if ( document.getElementById('filebrowser_width') ) {
            document.getElementById('filebrowser_width').value='';
        }
        if ( document.getElementById('filebrowser_height') ) {
            document.getElementById('filebrowser_height').value='';
        }
        if ( document.getElementById('filebrowser_mediatype') ) {
            document.getElementById('filebrowser_mediatype').value='';
        }
        if ( document.getElementById('filebrowser_filename') ) {
            document.getElementById('filebrowser_filename').value='';
        }
        if ( document.getElementById('filebrowser_xlinkhref') ) {
            document.getElementById('filebrowser_xlinkhref').value='';
        }
        PORTFOLIO.browser_show_imagethumb(row,url);
    }
    else {
        if ( document.getElementById('pf_updateOnServer') ) {
            document.getElementById('pf_updateOnServer').disabled=true;
        }
        if ( document.getElementById('pf_browser_uuid') ) {
            document.getElementById('pf_browser_uuid').value=row.getAttribute('id');
        }
        if ( document.getElementById('pf_browser_typeof_uuid') ) {
            document.getElementById('pf_browser_typeof_uuid').value=row.getAttribute('objecttype');
        }
        if ( document.getElementById('filebrowser_title') ) {
            document.getElementById('filebrowser_title').value=row.getAttribute('objecttitle');
        }
        if ( document.getElementById('filebrowser_description') ) {
            document.getElementById('filebrowser_description').value=row.getAttribute('description');
        }
        if ( document.getElementById('filebrowser_mimetype') ) {
            document.getElementById('filebrowser_mimetype').value=row.getAttribute('mimetype');
        }
        if (document.getElementById('filebrowser_width')) {
            document.getElementById('filebrowser_width').value=row.getAttribute('objectwidth');
        }
        if (document.getElementById('filebrowser_height')) {
            document.getElementById('filebrowser_height').value=row.getAttribute('objectheight');
        }
        if ( document.getElementById('filebrowser_mediatype') ) {
            document.getElementById('filebrowser_mediatype').value=row.getAttribute('type');
        }
        if (document.getElementById('filebrowser_filename')) {
            document.getElementById('filebrowser_filename').value=row.getAttribute('filename');
        }
        if ( document.getElementById('filebrowser_xlinkhref') ) {
            document.getElementById('filebrowser_xlinkhref').value=row.getAttribute('href');
        }
        //if (row.mimetype=='application/zip') {confirm('Unzip file now?')};
        PORTFOLIO.browser_show_imagethumb(row,url);
    }
};

PORTFOLIO.browser_preview = function() {
  var typeoff = document.getElementById('pf_browser_typeof_uuid').value;
  var uuid    = document.getElementById('pf_browser_uuid').value;
//  if (typeoff == 'object')
//    var cmd='read'
//  else
  var cmd='read_'+typeoff;
  var pf_preview=window.open(document.getElementById('base_site').value+'/?cmd='+cmd+';'+typeoff+'='+uuid+';basic_page=1','pf_preview','resizable=yes,menubar=no,toolbar=no,scrollbars=yes,hotkeys=no,width=450,height=300,top=100,left=50');
  pf_preview.window.focus();
};

PORTFOLIO.create_window = function(winId,title,content,url,left,top,width,height,argumentList) {
    if (argumentList) {
        PORTFOLIO.modalbox_targetinfo=argumentList;
    }
    if (url) {
        PORTFOLIO.ajaxpage( url, winId+'InnerDiv' );
    }
};

/* Cookie functions acquired from: http://www.quirksmode.org/js/cookies.html */

PORTFOLIO.setCookie = function(name,value,days) {
    $.cookie(name, value, {expires: days, path: "/"});
    return true;
}

PORTFOLIO.getCookie = function(name) {
    return $.cookie(name);
}

PORTFOLIO.deleteCookie = function(name) {
    $.cookie(name, null);
    return true;
}

/* portfolio.js original */

PORTFOLIO.removePopup = function() {
    if (PORTFOLIO.pf_popwindow && PORTFOLIO.pf_popwindow.open) {
        PORTFOLIO.pf_popwindow.close();
    }
};

//select,object,value,object_title,value,700,380,'',null
PORTFOLIO.fileBrowser = function(mode,type,container,title_target,id_target,width,height,trig_Save,container_uuid) {
    // mode = get|upload|......

    var url = PORTFOLIO.site_url + "selector/?type=" + type + ";no_title=1";

    if ( ! ( mode == 'select' ) ) {
        url+=";callback_mode=tinymce";
    }

    if (!container_uuid) {
        if (container) {
            container_uuid=document.getElementById(container) ? document.getElementById(container).value : '';
        }
    }

    //alert("container_uuid:"+container_uuid);

    if (!width)  { width = 700; }
    if (!height) { height= 450; }

    //alert("showModalDialog support? " + window.showModalDialog);

    if (window.showModalDialog) {
        // MSIE, Firefox3, Google Chrome

        // IE modal dialogs need some extra height compared to modal dialogs in other browsers
        height += 52;
        
        var args={
            mode         : mode,
            type         : type,
            container     : container_uuid,
            title_target : title_target,
            id_target     : id_target
        };

        if (title_target && document.getElementById(title_target) ) {
            args.title_value = document.getElementById(title_target).value;
        }

        if (id_target && document.getElementById(id_target) ) {
            args.id_value = document.getElementById(id_target).value;
        }

        // Here we open the dialog window
        var returValue = window.showModalDialog(url, args, "dialogWidth:"+width+"px;dialogHeight:"+height+"px;scrollbars=no" );

        if (returValue) {

            if (returValue.title && returValue.title != '' && document.getElementById(title_target)) {
                document.getElementById(title_target).value = returValue.title;
            }

            if (returValue.uuid && document.getElementById(id_target)) {
                document.getElementById(id_target).value = returValue.uuid;
            }
        }
    }
    else {
        // This is for those that don't implement showModalDialog()
        // like Firefox2 and Opera

        if (!document.getElementById('filebrowser_args')) {
            var newHiddenInput = document.createElement('input');
            newHiddenInput.type = "hidden";
            newHiddenInput.id = "filebrowser_args";
            document.getElementsByTagName('body')[0].appendChild(newHiddenInput);
        }

        document.getElementById('filebrowser_args').value = [
            mode,
            type,
            container_uuid,
            title_target,
            id_target,
            trig_Save
        ].join(",");

        var left = (PORTFOLIO.windowWidth() - width) / 2;
        var top  = (screen.height - height) / 2;

        //coverBackground();

        var window_url_opts = "width=" + width;
        window_url_opts+=",height=" + height;
        window_url_opts+=",top=" + top;
        window_url_opts+=",left=" + left;
        window_url_opts+=",scrollbars=no,menubars=no,titlebar=no,modal=yes,dialog=yes,resizable=no";
        PORTFOLIO.pf_popwindow = window.open( url, "pf_popwindow", window_url_opts );
        PORTFOLIO.pf_popwindow.focus();
    }

    // Everything finished
    return true;

};

PORTFOLIO.windowWidth = function() {
    if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
        return window.innerWidth;
    }
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    }
    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
        return document.body.clientWidth;
    }
    return 0;
};

PORTFOLIO.getElementsByClassName = function(strClass, strTag, objContElm) {
// Function by http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = objContElm.getElementsByTagName(strTag);
    if (!objColl.length &&  strTag == "*" &&  objContElm.all) {
        objColl = objContElm.all;
    }
  var arr = [];
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);

  for (var i = 0, j = objColl.length; i < j; i++) {
    if(typeof objColl[i].className == "undefined") {
        continue;
    }
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) {
        continue;
    }
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) {
            c++;
        }
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
};

PORTFOLIO.toggleEditorMode = function(id) {
    if (!tinyMCE) {
        return false;
    }
    if (tinyMCE.get(id).isHidden() == false) {
        tinyMCE.get(id).hide();
    }
    else {
        tinyMCE.get(id).show();
    }
};

PORTFOLIO.setWysiwygMode = function(sEditorID,wysiwyg) {
    if (wysiwyg) {
        // Will set wysiwyg-mode if wysiwyg=true and not set already
        //tinyMCE.addMCEControl(document.getElementById(sEditorID), sEditorID);
        tinyMCE.get(sEditorID).show();
        tinyMCEmode = true;
    }
    else if (!wysiwyg) {
        // Will remove wysiwyg-mode if wysiwyg=false and wysiwyg-mode set
        //tinyMCE.removeMCEControl(tinyMCE.getEditorId(sEditorID));
        tinyMCE.get(sEditorID).hide();
        tinyMCEmode = false;
    }
};

PORTFOLIO.setEditEnvironment = function(optvalue) {
// Will activate/deactivate wysiwyg-mode and hide/show editor according to object-type
// Will also hide/show field for file-upload according to the object
    var use_wysiwyg = false;
    var use_content = true;
    var use_content_file = true;
      switch(optvalue){
          case 'document' :
            use_wysiwyg = true;
            use_content = true;
            use_content_file = false;
          break;
           case 'page' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;
           case 'image' :
             use_wysiwyg = false;
             use_content = false;
             use_content_file = true;
          break;
            case 'audio' :
              use_wysiwyg = false;
              use_content = false;
              use_content_file = true;
          break;
            case 'binary' :
              use_wysiwyg = false;
              use_content = false;
              use_content_file = true;
          break;
           case 'text' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;
           case 'link' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;
           case 'forum' :
             use_wysiwyg = true;
             use_content = true;
             use_content_file = false;
          break;
           case 'stylesheet' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;
           case 'javascript' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;
            case 'template' :
              use_wysiwyg = false;
              use_content = true;
              use_content_file = false;
          break;
           case 'script' :
             use_wysiwyg = false;
             use_content = true;
             use_content_file = false;
          break;  
              case 'java-settings' :
                use_wysiwyg = false;
                use_content = true;
                use_content_file = false;
            break;
             case 'java-data' :
               use_wysiwyg = false;
               use_content = false;
               use_content_file = true;
          break;
              case 'flash-settings' :
                use_wysiwyg = false;
                use_content = true;
                use_content_file = false;
            break;
             case 'flash-data' :
               use_wysiwyg = false;
               use_content = false;
               use_content_file = true;
          break;          
      }
  if (!use_content) {    
      PORTFOLIO.setWysiwygMode('content',false);
      document.getElementById('content').style.display = "none";
      document.getElementById('content_div').style.display = "none";
  }
  else {
        document.getElementById('content_div').style.display = "block";
        document.getElementById('content').style.display = "block";
      PORTFOLIO.setWysiwygMode('content',use_wysiwyg);
  }
  if (use_content_file) {
      document.getElementById('content_file_div').style.display = "block";
      document.getElementById('content_file').style.display = "block";
  }
  else {
    if ( document.getElementById('content_file') ) {
          document.getElementById('content_file').style.display = "none";
    }
    if ( document.getElementById('content_file_div') ) {
        document.getElementById('content_file_div').style.display = "none";
    }
  }
};

PORTFOLIO.toggleVisibility = function(objId) {
   if (document.getElementById(objId)) {
        var element = document.getElementById(objId);
        element.style.display = (element.style.display != 'block' ? 'block' : 'none' );
   }
};

PORTFOLIO.stripe_table = function(id) {
    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#eee";
    var oddColor = arguments[2] ? arguments[2] : "#fff";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var table = document.getElementById(id);
    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s 
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a backgroundColor style
        if (! trs[i].style.backgroundColor) {
           
          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a backgroundColor style
            if (! mytd.style.backgroundColor) {
        
              mytd.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
};

/* portfolio_xslt.js */

/*
   Client side XSLT-script

    Copyright (C) Portfolio AS - (www.portfolio.no).
    All rights reserved
    Written by Frode Rustoy (Frode@Rustoy.no), 2006
*/

PORTFOLIO.do_decoding = function(divId) {
    var el = document.getElementById(divId);
    var str = el.innerHTML;
    str = str.replace(/&lt;/g, '<' );
    str = str.replace(/&gt;/g, '>' );
    str = str.replace(/&quot;/g, '"' );
    str = str.replace(/&amp;/g, '&' );
    str = unescape(str);
    el.innerHTML=str;
};

/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@volmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
                
PORTFOLIO.handleEnter = function(field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    var i;
    if (keyCode == 13) {
        for (i = 0; i < field.form.elements.length; i++) {
            if (field == field.form.elements[i]) {
                break;
            }
        }
        i = (i + 1) % field.form.elements.length;
        field.form.elements[i].focus();
        return false;
    }
    else {
        return true;
    }
};

PORTFOLIO.POPUP = {};

PORTFOLIO.POPUP.init = function() {

    // Lots of defaults
    var selector = 'a.popup'; // What elements to generate popups on, CSS selector
    var popup_id = 'tooltip'; // DOM id of the popup
    var iframe_id = popup_id + '_iframe'; // DOM id of the IE select hack iframe 
    var offsetX = 16; // Distance from pointer popup will be placed (horizontal)
    var offsetY = 13; // Distance from pointer popup will be placed (vertical)
    var zIndex = 100; // CSS z-index of popup

    $(selector).each(function() {
        // #1686: people cut/paste documents with popup() markup in them.
        // This should at least make sure the popup code generation is skipped
        // if dependencies (jQuery metadata plugin) are not present on the page.
        var metadata = $(this).metadata ? $(this).metadata() : null;

        // We need some metadata
        if ( ! ( metadata && typeof metadata === 'object' ) ) {
            return false; // Ignore elements that do not have metadata
        }
        
        // Check that event_type value is defined
        if ( ! metadata.event_type ) {
            throw new SyntaxError("You need to specify event type");
        }

        // Bind default values
        metadata.popup_id = popup_id;
        metadata.iframe_id = iframe_id;
        metadata.offsetX = offsetX;
        metadata.offsetY = offsetY;
        metadata.zIndex = zIndex;

        // Bind to click or mouseover event
        $(this).bind(metadata.event_type, function(event) {
            PORTFOLIO.POPUP.show(
                PORTFOLIO.POPUP.getContent(this),
                metadata,
                event
            );
        });

        // Kill contents of tooltip and remove mousemove event
        // on mouseout event 
        $(this).mouseout(function() {
            $('#' + popup_id + ',#' + iframe_id).fadeOut().remove();
            $(document).unbind('mousemove');
        });

    });
    return true;
};

PORTFOLIO.POPUP.getContent = function(el) {
    if ( ! el ) {
        throw new SyntaxError("Argument was not specified");
    }

    if ( typeof el !== 'object' ) {
        throw new TypeError("Argument is not an object");
    }

    if ( ! ( el.nextSibling && typeof el.nextSibling === 'object' ) ) {
        throw new Error("nextSibling is not an object");
    }

    if ( el.nextSibling.nodeType !== 8 ) {
        throw new Error("nextSibling is not a comment node");
    }

    return el.nextSibling.data;
};

PORTFOLIO.POPUP.show = function(text, metadata, event) {

    var popup_id = metadata.popup_id;
    var iframe_id = metadata.iframe_id;

    // Remove old popup div and iframe if still around
    $('#' + popup_id).remove();
    $('#' + iframe_id).remove();

    // Create popup div and background iframe
    $('body').append('<div id="' + popup_id + '" style="display: none; position: absolute;"><div id="tooltip_content"></div></div>');
    $('body').append('<iframe ' + ( $.browser.msie ? 'frameborder="0"' : '' ) + ' id="' + iframe_id + '" style="display: none; position: absolute;"></iframe>');

    var popup = $('#' + popup_id);

    // Set z-index and add content
    popup.css('z-index',metadata.zIndex);
    $('#' + popup_id + '_content').html(text);
    
    // Set explicit width of popup if specified
    if ( metadata.width ) {
        popup.width(metadata.width);
    }
    else {
    // If not set, use a sane max-width to avoid jumping around the screen
        popup.css('max-width','40em');
    }

    // Show popup offscreen to be able to fetch width/height
    popup.css('left',-10000).css('top',-10000).show();

    // Calculate actual popup position
    var point = PORTFOLIO.POPUP.calcPoint({
        mouseX : event.pageX,
        mouseY : event.pageY,
        offsetX : metadata.offsetX,
        offsetY : metadata.offsetY,
        popupWidth : popup.width(),
        popupHeight : popup.height()
    });

    // Hide popup again, since we now have the dimensions
    popup.hide();

    var left = point.X;
    var top = point.Y;

    // Set top/left and show popup
    popup.css('left',left).css('top',top);
    
    if ( $.browser.msie ) {
        // if IE - this should be replaced with fadeIn()
        // when there is a new version of IE/jQuery available
        popup.show();
    }
    else {
        // fadeIn() works in non-IE browsers
        popup.fadeIn();
    }

    // Set iframe position and other details.
    // LP #1650289: Due to padding of the popup div element, the iframe
    // needs some extra height/width to ensure that iframe background is
    // complete when hovering over embedded objects.
    $('#' + iframe_id).
        height( popup.height() ).
        width( popup.width() ).
        css('background-color', '#fff'). // Sets default background color to white
        css('z-index', popup.css('z-index') - 1 ).
        css('left',left).
        css('top',top).
        show();

    // Make sure popup moves with mouse
    $(document).mousemove(function(event) {
        PORTFOLIO.POPUP.onMove(event, metadata);
    });

    return true;
};

PORTFOLIO.POPUP.onMove = function(event, metadata) {

    if ( ! ( metadata && typeof metadata === 'object' ) ) {
        return false; // Called in the wrong way
    }

    var popup_id = metadata.popup_id;
    var iframe_id = metadata.iframe_id;

    if ( ! $('#' + popup_id).get(0) ) {
        return false; // Popup not present on page
    }

    // Calculate actual top/left point
    var point = PORTFOLIO.POPUP.calcPoint({
        mouseX : event.pageX,
        mouseY : event.pageY,
        offsetX : metadata.offsetX,
        offsetY : metadata.offsetY,
        popupWidth : $('#' + popup_id).width(),
        popupHeight : $('#' + popup_id).height()
    });

    // Set top/left coordinates for popup div and iframe
    $('#' + popup_id + ",#" + iframe_id).
        css('left',point.X).
        css('top',point.Y);

    return true;
};

PORTFOLIO.POPUP.calcPoint = function(vars) {

    if ( ! ( vars && typeof vars === 'object' ) ) {
        return false; // Invalid usage
    }

    // Determine new top/left coordinates
    var left = vars.mouseX + vars.offsetX;
    var top = vars.mouseY + vars.offsetY;

    // Determine bottom/right coordinates
    var right = left + vars.popupWidth;
    var bottom = top + vars.popupHeight;

    // Will popup go outside right of viewport?
    // If so, try to shift to the left of pointer instead
    if ( ( right + 20 ) > $(window).width() ) {
        left = vars.mouseX - vars.offsetX - vars.popupWidth;
    }

    // Check if left is off the left border
    if ( left <= 20 ) {
        left = 20;
    }

    // Will popup go outside bottom of viewport?
    // If so, try to shift above pointer instead
    if ( ( bottom + 20 ) > $(window).height() ) {
        top = vars.mouseY - vars.offsetY - vars.popupHeight;
    }

    return { X: left, Y: top };
};

/* xml_dialog.js */

PORTFOLIO.makeRequest = function(url, parameters,just_alert) {

    var http_request = false;

    if (window.XMLHttpRequest) {
      // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
         http_request.overrideMimeType('text/xml');
      }
    }
    else if (window.ActiveXObject) {
        // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            }
        }
    }
    
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    if (just_alert) {
      http_request.onreadystatechange = function() { PORTFOLIO.give_report(http_request); };
    }
    else {
      http_request.onreadystatechange = function() { PORTFOLIO.get_portfolio_response(http_request); };
    }
    http_request.open('GET', url + parameters, true);
    http_request.send(null);
    
    return 1;
};

PORTFOLIO.give_report = function(http_request) {
  if (!http_request) {
    return false; // Do not use global here
  }
  if (http_request.readyState == 4) {
//alert(http_request.responseText)
//alert(http_request.responseXML)
//alert(http_request.status)
//alert(http_request.statusText)
//alert(http_request.responseBody)
      var xmldoc = http_request.responseXML;
      var pf_root_node = xmldoc.getElementsByTagName('portfolio').item(0);
      if (!pf_root_node) {
        alert( PORTFOLIO.gettext('Unrecognized XML response') + "\n" + http_request.responseText );
        return false;
      }
      var response_node = pf_root_node.getElementsByTagName('response').item(0);
      var my_request = response_node.getAttribute("request");
      if (my_request != 'list_class' && my_request != 'list_account') {
          var message_text = response_node.firstChild.data;
          var status_text = response_node.getAttribute('status');
          var code_text = response_node.getAttribute('code');
      }
    if (code_text > 199 && code_text < 300) {
      alert(message_text);
    }
    else {
      alert( PORTFOLIO.gettext('Server response:') +' ' + code_text + ' ' + status_text + '\n\n   ' + message_text);
    }
  }
};
 
PORTFOLIO.xmldialog_table_id='group_list';

PORTFOLIO.get_portfolio_response = function(http_request) {
    if (!http_request) {
        return false; // Do not use global here
    }
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            //alert(http_request.responseText)
            //alert(http_request.responseXML)
            //alert(http_request.status)
            //alert(http_request.statusText)
            //alert(http_request.responseBody)
            var xmldoc = http_request.responseXML;
            //http_request = false;
            var pf_root_node = xmldoc.getElementsByTagName('portfolio').item(0);
            if (!pf_root_node) {
                alert( PORTFOLIO.gettext('Unrecognized XML response') + "\n" + http_request.responseText);
                return false;
            }
            var response_node = pf_root_node.getElementsByTagName('response').item(0);
            var my_request = response_node.getAttribute("request");
            if (my_request != 'list_class' && my_request != 'list_account') {
                var message_text = response_node.firstChild.data;
                var status_text = response_node.getAttribute('status');
                var code_text = response_node.getAttribute('code');
            }
            if (code_text > 199 && code_text < 300) {
                if (my_request == 'list_class') {
                    var class_nodes = pf_root_node.getElementsByTagName('class');
                    document.getElementById('pf_popdiv').style.display='block';
                    document.getElementById('pf_popdiv_content').innerHTML='<input type="button" value="Ny" onclick="var group_name=prompt(\'Navn p&aring; ny gruppe:\',\'\');if (group_name!=null) PORTFOLIO.do_ajax_cmd(\'cmd=write_class;name=\'+group_name+\';response=xml\',\''+PORTFOLIO.xmldialog_table_id+'\');" />'
                    + '<br /><table id="'+PORTFOLIO.xmldialog_table_id+'" type="class" class="sort-table" cellspacing="0">'
                    + '<col style="width:100%" /><col style="text-align: center" /><col style="text-align: center" />'
                    + '<col style="text-align: center" /><col style="text-align: center" />'
                    + '<thead><tr><td pfFieldName="name">Gruppenavn</td><td>Slette</td>'
                    + '<td>Redigere</td><td>Rettigheter</td><td>Tilh&oslash;righet</td></tr></thead>'
                    + '<tbody><tr><td></td><td></td><td></td><td></td><td></td></tr></tbody></table> ';
                    for (var i = 0; i < class_nodes.length; i++) {
                        var current_id = class_nodes.item(i).getAttribute("id");
                        var current_name = class_nodes.item(i).firstChild.data;
                        var arr = [
                            current_name,
                            '<input type="button" value="Slette" command="delete_class" onclick="PORTFOLIO.ajax_command(this);">',
                            '<a href="/?cmd=edit_class;class_id='+current_id+'">[Rediger]</a>',
                            '<a href="/?cmd=list_class_permission;class_id='+current_id+'">[Rettighet]</a>',
                            '<a href="/?cmd=list_class_membership;class_id='+current_id+'">[Tilh&oslash;righet]</a>'
                        ];
                        PORTFOLIO.addrow(PORTFOLIO.xmldialog_table_id, arr,current_id);
                    }
                    PORTFOLIO.st1 = new SortableTable(document.getElementById(PORTFOLIO.xmldialog_table_id),["CaseInsensitiveString", "None", "None", "None", "None"]);
                    PORTFOLIO.st1.onsort = function () {
                        var rows = PORTFOLIO.st1.tBody.rows;
                        var l = rows.length;
                        for (var i = 0; i < l; i++) {
                            removeClassName(rows[i], i % 2 ? "odd" : "even");
                            addClassName(rows[i], i % 2 ? "even" : "odd");
                        }
                    };
                    PORTFOLIO.st1.sort(0,false);
                }
                // Midlertidig - skal inn i case
                //else if (my_request == 'update_account') {
                //  alert(http_request.responseText);
                //}
                else if (my_request.indexOf('account') > -1) {
                    //alert(http_request.responseText);
                    var account_node = pf_root_node.getElementsByTagName('account').item(0);
                    var account_id  = account_node.getAttribute('id');
                    //var name_text = account_node.firstChild.data;
                    if (account_node.getElementsByTagName('name').item(0).firstChild) {
                        var nickname = account_node.getElementsByTagName('name').item(0).firstChild.data;
                    }
                    else {
                        var nickname = "";
                    }
                    if (account_node.getElementsByTagName('name').item(1).firstChild) {
                        var firstname = account_node.getElementsByTagName('name').item(1).firstChild.data;
                    }
                    else {
                        var firstname = "";
                    }
                    if (account_node.getElementsByTagName('name').item(2).firstChild) {
                        var lastname = account_node.getElementsByTagName('name').item(2).firstChild.data;
                    }
                    else {
                        var lastname = "";
                    }
                    if (account_node.getElementsByTagName('email').item(0).firstChild) {
                        var email = account_node.getElementsByTagName('email').item(0).firstChild.data;
                    }
                    else {
                        var email="";
                    }
                    //alert(account_id +' '+nickname+' '+firstname+' '+lastname+' '+email);
                    switch(my_request) {
                        case 'write_account' :
                            if (code_text >= '200' && code_text <= '299') {
                                document.getElementsByTagName('body')[0].removeChild(document.getElementById('coverDiv'));
                                document.getElementsByTagName('body')[0].removeChild(document.getElementById('tempDiv'));
                                var arr = [
                                    unescape(lastname),
                                    unescape(firstname),
                                    unescape(nickname),
                                    unescape(email),
                                    '**********',
                                    '<input  onclick="PORTFOLIO.doCommand(this)" type="image" src="'+PORTFOLIO.static_url+'theme/crystal/16x16/actions/edit.png" />',
                                    '<input type="checkbox" class="delete" />',
                                    '',
                                    '',
                                    '',
                                    ''
                                ];
                                PORTFOLIO.addrow(PORTFOLIO.xmldialog_table_id, arr,account_id);
                                PORTFOLIO.st1.sort(0,false);
                                // Lage en metode for scrollIntoFocus
                                //PORTFOLIO.findRow(PORTFOLIO.xmldialog_table_id,account_id).focus();
                                //alert(http_request.responseText)
                            }
                            else {
                                alert(message_text);
                            }
                            break;
                        case 'delete_account' :
                            var client_tablerow = PORTFOLIO.findRow(PORTFOLIO.xmldialog_table_id,account_id);
                            if (client_tablerow != null) {
                                // Delete succeded on server. Delete corresponding row to reflect the change visualy
                                PORTFOLIO.delRow(client_tablerow);
                            }
                            PORTFOLIO.st1.sort(0,false); // just to fix zebra-stripes
                            break;
                        case 'update_account' :
                            allTds = PORTFOLIO.findRow(PORTFOLIO.xmldialog_table_id,account_id).getElementsByTagName('td');
                            if (allTds[0].lastChild.data != unescape(lastname)) {
                                allTds[0].lastChild.data = unescape(lastname);
                            }
                            if (allTds[1].lastChild.data != unescape(firstname)) {
                                allTds[1].lastChild.data = unescape(firstname);
                            }
                            if (allTds[2].lastChild.data != unescape(nickname)) {
                                allTds[2].lastChild.data = unescape(nickname);
                            }
                            if (allTds[3].lastChild.data != unescape(email)) {
                                allTds[3].lastChild.data = unescape(email);    
                            }
                            //for (var i = 0; i < allTds.length; i++) {
                            //  if (all)
                            //}
                            //alert(http_request.responseText)
                            break;
                    }
                }
                else {
                    var name_node = pf_root_node.getElementsByTagName('class').item(0);
                    var name_text = name_node.firstChild.data;
                    var class_id  = name_node.getAttribute('id');
                    //alert(class_id+' '+name_text);
                    switch(my_request) {
                        case 'write_class' :
                            var arr = [
                                unescape(name_text),
                                '<input type="button" value="Slette" command="delete_class" onclick="PORTFOLIO.ajax_command(this);">',
                                '<a href="/?cmd=edit_class;class_id='+class_id+'">[Rediger]</a>',
                                '<a href="/?cmd=list_class_permission;class_id='+class_id+'">[Rettighet]</a>',
                                '<a href="/?cmd=list_class_membership;class_id='+class_id+'">[Tilh&oslash;righet]</a>'
                            ];
                            PORTFOLIO.addrow(PORTFOLIO.xmldialog_table_id, arr,class_id);
                            PORTFOLIO.st1.sort(0,false);
                            break;
                        case 'delete_class' :
                            var client_tablerow = PORTFOLIO.findRow(PORTFOLIO.xmldialog_table_id,class_id);
                            if (client_tablerow != null) {
                                // Delete succeded on server. Delete corresponding row to reflect the change visualy
                                PORTFOLIO.delRow(client_tablerow);
                            }
                            PORTFOLIO.st1.sort(0,false);
                            break;
                        case 'update_class' :
                            var client_tablerow = PORTFOLIO.findRow(PORTFOLIO.xmldialog_table_id,class_id);
                            if (client_tablerow != null) {
                                // Renaming succeded on server. Inserting new string to reflect the change visualy as well 
                                client_tablerow.firstChild.innerHTML=name_text;
                            }
                            break;
                    }
                }
            }
            else {
                alert(code_text+' - '+status_text+'\n'+message_text);
            }
        }
        else {
            alert('Unknown error!\nThere was a problem with the request.');
        }
    }
    return 1;
};

PORTFOLIO.ajax_command = function(obj) {
    var command=obj.getAttribute('command');
    var table_cell=obj.parentNode;
    var table_row = table_cell.parentNode;
    var uuid = table_row.getAttribute('id');
    var table_body = table_row.parentNode;

    var confirmDelRow = function(table_row) {
        var myBackground = table_row.style.backgroundColor;
        table_row.style.backgroundColor = "red";
        var myColor = table_row.style.color;
        table_row.style.color = "yellow";
        var user_answer = confirm('Markert rad vil bli slettet...');
        table_row.style.backgroundColor = myBackground;
        table_row.style.color = myColor;
        return user_answer;
    };

    PORTFOLIO.xmldialog_table_id  = table_body.parentNode.getAttribute('id');
    if (command == 'delete_class') {
        if (confirmDelRow(table_row) == false) {
            return false;
        }
    }

    //alert('/?cmd='+command+';class_id='+uuid+';response=xml');
    PORTFOLIO.makeRequest('/','?cmd='+command+';class_id='+uuid+';response=xml');
    
    return 1;
};

PORTFOLIO.do_ajax_cmd = function(get_string,table_name,typeoff) {
    if (table_name) {
        PORTFOLIO.xmldialog_table_id = table_name;    
    }
//    if (typeoff == 'rss'){
//        try_multiple('/frode/get_rss.pl?'+get_string);
//    }
//    else
        PORTFOLIO.makeRequest('/', '?'+get_string);
};

PORTFOLIO.findRow = function(table_element_id,lookup_uuid) {
    var tbl = document.getElementById(table_element_id);
    var rows = tbl.getElementsByTagName('TR');
    for (var tr = 0; tr < rows.length; tr++) {
        uuid = rows[tr].getAttribute('id');
        if (uuid ==lookup_uuid) {
            return rows[tr];
        }
    }
    return null;
};

PORTFOLIO.addrow = function(table_element_id, arr,uuid) {
    var tbl = document.getElementById(table_element_id);
    var lastRow = tbl.rows.length;
    var row = tbl.insertRow(lastRow);
// using zebra-striped style on the list 
    if (lastRow % 2 == 0) {
        row.setAttribute('class','even');
    }
    else {
        row.setAttribute('class','odd');
    }
    row.setAttribute('id',uuid);
    for (var r = 0; r < arr.length; r++) {   
            var cell = row.insertCell(r);
//        cell.setAttribute('class',tbl.cols.className)
//        cell.setAttribute('className',tbl.cols.className)
        if (r == 0) {
            cell.setAttribute('class','editable');
            cell.setAttribute('className','editable');
        }
             cell.innerHTML = arr[r];
    }
};

PORTFOLIO.delRow = function(table_row) {
    var table_body = table_row.parentNode;
    var table = table_body.parentNode;
    table.deleteRow(table_row.rowIndex);
};

PORTFOLIO.createModalDialog = function(header,body) {
  var docWidth = screen.width; //document.body.clientWidth;
  var docHeight = screen.height; //document.body.clientHeight;
  //Creating a div in the background to prevent the user from clicking outside the dialog
  var docBody=document.getElementsByTagName('body')[0];
  var coverDiv=document.createElement('iframe');
  coverDiv.setAttribute('id', 'coverDiv');
  coverDiv.style.position = 'absolute';
  coverDiv.style.width=docWidth+'px';
  coverDiv.style.height=docHeight+'px';
  coverDiv.style.top = '0';
  coverDiv.style.left = '0';
  coverDiv.style.background = 'white';
  coverDiv.style.filter = 'alpha(opacity=50)';
  coverDiv.style.mozOpacity = '.50'; //-moz-opacity:.25;
  coverDiv.style.opacity = '.50';
  coverDiv.style.border = 'solid 1px';
  docBody.appendChild(coverDiv);

// Creating and appending the dialog-div
// Need to append this to the body as well because of the transparency
  var tempDiv = document.createElement('div');
  tempDiv.setAttribute('id', 'tempDiv');
  tempDiv.style.position = 'absolute';
  tempDiv.style.background = '#D4D0C8';
  tempDiv.style.color = 'black';
  tempDiv.style.border = 'outset 2px silver';
  tempDiv.style.zIndex = '30';
  tempDiv.style.left = '150px';
  tempDiv.style.top = '100px';
  tempDiv.style.width = '450px';
  tempDiv.style.height = '350px';
  docBody.appendChild(tempDiv);

// Creating and appending the header
  var headerDiv = document.createElement('div');
  headerDiv.style.background = '#41629C';
  headerDiv.style.color = 'white';
  headerDiv.style.padding = '0';
  header = '<img src="'+PORTFOLIO.static_url+'gfx/foldericon2.gif" style="border:none; margin-left:5px;margin-right:10px"/>' + header;
  headerDiv.innerHTML = '<input type="button" style="float:right" value="x" onclick="document.getElementsByTagName(\'body\')[0].removeChild(document.getElementById(\'coverDiv\'));this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)" /><b>'+header+'</b>';
  document.getElementById('tempDiv').appendChild(headerDiv);  

// Creating and appending content
  bodyContent = document.createTextNode(body);
  tempDiv.appendChild(bodyContent);
  PORTFOLIO.do_decoding('tempDiv');
  var modalBox = document.getElementById('tempDiv');
  var modalBoxWidth = modalBox.offsetWidth;
  var modalBoxHeight = modalBox.offsetHeight;
  modalBox.style.left = ((docWidth -modalBoxWidth) / 2) +'px';
  modalBox.style.top = ((docHeight -modalBoxHeight) / 2) +'px';
};

PORTFOLIO.doCommand = function(obj){
 var tableRow = obj.parentNode.rowIndex;
 var uuid = obj.parentNode.getAttribute('id');
 var tableElement = obj.parentNode.parentNode.parentNode;
 var command = tableElement.rows[0].cells[+obj.cellIndex].getAttribute('pfCommand');
 var item_type=tableElement.getAttribute('type');
 if (command && item_type && uuid) {
    var get_string = '/?cmd='+command+'_'+item_type+';'+item_type+'_id='+uuid;
    PORTFOLIO.createModalDialog(command+' '+item_type,'Her kommer dialogen '+get_string+';response=xml');
 }
};

var lastURL;
PORTFOLIO.modalbox_targetinfo='';

PORTFOLIO.filebrowser_insertResult = function() {
  var my_object     = document.getElementById('pf_browser_uuid').value;
  var insert_method = document.getElementById('pf_browser_insert_method').value;
  if (!my_object) {
      alert('No object chosen');
  }
  else {
    var pf_arguments = PORTFOLIO.modalbox_targetinfo.split('\,');
//alert(pf_arguments[i]);
      var my_title = document.getElementById('filebrowser_title').value;
        var my_mediatype  = document.getElementById('filebrowser_mediatype').value;
        var my_mimetype  = document.getElementById('filebrowser_mimetype').value;
//alert(my_mediatype+ ' -> '+my_mimetype);
    var my_style = '';
/*
        var my_width  = document.getElementById('filebrowser_width').value;
    if (my_width != '') {
       my_style += 'width: '+my_width+'px;';
        }
        var my_height  = document.getElementById('filebrowser_height').value;
    
    if (my_height != '') {
       my_style += 'height: '+my_height+'px;';
        }
*/
    my_style=document.getElementById('styleString') ? document.getElementById('styleString').value : '';

    if (my_style != '') {
       my_style = ', style => \'' + my_style+'\'';
        }
        for (var i = 0; i < pf_arguments.length; i+=3) {
        var target=document.getElementById(pf_arguments[i]);
                var source_code = '';
//                var mimeArr = my_mimetype.split('\/');
//                var media_type = mimeArr[0];
        switch(insert_method){
//        switch(pf_arguments[i+1]){
            case 'title' :
                source_code = my_title;
            break;
            case 'uuid' :
                source_code = my_object;
            break;
            case 'embed' :
                var player = '';
                if (my_mediatype == 'audio') {
                    player = ",player => 'normal'";
                }
                source_code = '[% embed(\''+my_object+'\',{type => \''+my_mediatype+'\', mimetype => \''+my_mimetype+'\''+player+my_style+'}) %]';
            break;
            case 'link' :
                var selectedHTML = tinyMCEPopup.editor.selection.getContent();
                var PF_cmd='read';
                if (document.getElementById('pf_browser_typeof_uuid') && (document.getElementById('pf_browser_typeof_uuid')== 'container')) {
                   PF_cmd='read_container';
                }
                if (selectedHTML !='') {
//                  source_code = '<a href="[% uri(\''+my_object+'\') %]">'+selectedHTML+'</a>';
//alert(source_code);
                  source_code = '<a href="[% site_url %]'+PF_cmd+'/'+my_object+'">'+selectedHTML+'</a>';
                }
                else {
                  source_code = '[% link(\''+my_object+'\') %]';
                }
            break;
            case 'uri' :
                source_code = '[% uri(\''+my_object+'\') %]';
            break;
            default : 
                source_code = my_object;
            break;
        }
        if (pf_arguments[i]=='content') {

    // tinyMCE might not be defined
    try {
              tinyMCE.execCommand("mcePFmacroedit_insert",true,source_code);
    }
    catch (e) {
        alert("Problems calling tinyMCE\n" + e);
    }
    // Close the dialog
        // tinyMCEPopup.close();

          if (document.getElementById('pf_fileBrowserInnerDiv').parentWindow) {
        document.getElementById('pf_fileBrowserInnerDiv').parentWindow.close();
      }
}

else {
        switch(pf_arguments[i+2]){
                     case 'append' :
                target.value += source_code;
             break;
                     case 'replace' :
                target.value = source_code;
             break;
        }
}
        
//        alert(pf_arguments[i] + '=' + pf_arguments[i+1] + ' method='  + pf_arguments[i+2] + ' ')
        }
    PORTFOLIO.modalbox_targetinfo='';
  }
};

/*
 * Workaround because XHTML doesn't allow target="_blank" in anchors.
 * More information: http://www.sitepoint.com/article/standards-compliant-world
 */
PORTFOLIO.updateExternalLinks = function() { 
    $("a[rel='external']").attr("target", "_blank");
    return true;
};

/* expand_collapse.js  */

/* 

Matryshka dolls or a Russian nested doll is a set of dolls of decreasing
sizes placed one inside another. Its name is a diminutive form of a 
Russian female name "Matryona".

These functions are inspired by Matryshka dolls and are aimed to
show or hide nested nodes in DOM.

    Copyright (C) Portfolio AS,  http://www.portfolio.as/
    version 1.0 22.09.2005-20.01.2006 by Frode Rustoy

Some functions to expand and collapse nodes in unordered lists and nodes in divs

The functions takes the folowing parameters:

    XXXX: bla bla
    YYYY: bla bla

SAMPLE:
    HTML-sample here....

*/

/* Find the last element with class="<specified>" inside the
 * container element and scroll the viewport to it.
 * Obviously requires the container to have style overflow
 * set to something sensible (like overflow:auto).
 */
PORTFOLIO.scrollContainerToElementByClass = function(containerSelector,elementClass) {

    // Find container to scroll
    if (!containerSelector) {
        return false;
    }
    var container = $(containerSelector);

    // Find element to scroll to
    if (!elementClass) {
        return false;
    }
    var elem = $("." + elementClass + ":last",container);
    if ( ! ( elem && elem.get(0) ) ) {
        return false;
    }

    // Find amount of pixels to scroll
    var pos = 0;
    while ( elem && elem.get(0) && elem.get(0) !== container.get(0) ) {
        pos += elem.position().top;
        elem = elem.offsetParent();
    };

    // Set scroll value
    container.scrollTop(pos);

    return true;
};

PORTFOLIO.layout_fix_height = function () {
    var footer = document.getElementById('element_bottom_info');
    if (!footer) {
        return false;
    }
    var middle_row = document.getElementById('element_middle_row');
    if (!middle_row) {
        return false;
    }
    var footer_top = footer.offsetTop;
    var middle_row_top = middle_row.offsetTop;
    var middle_row_bottom = middle_row.offsetHeight+middle_row_top;
    var footer_top = footer.offsetTop;
    var diff = footer_top - middle_row_bottom;
    if (diff != 0) {
        middle_row.style.height = (middle_row.offsetHeight+diff)+'px';
    }
    //alert('fixing');
};

PORTFOLIO.node_toggle_display = function (a,b) {
    //alert(a.getElementsByTagName('a')[0].id);
    var theUl = a.parentNode.getElementsByTagName('ul')[0];
    var theDiv = a.parentNode.getElementsByTagName('div')[0];
    if (theUl.style.display == 'block') {
        theUl.style.display = 'none';
        theDiv.innerHTML = '+';
    }
    else {
        theUl.style.display = 'block';
        theDiv.innerHTML = '-';
    }
};

PORTFOLIO.activate_folder_menu = function (startId) {
 if (!startId) {
    return false;
 }

 var startEl=document.getElementById(startId);
 if (!startEl) {
    return false;
 }

 var indentSpan = document.createElement('div');
 var indentContent = document.createTextNode(' ');
 indentSpan.appendChild(indentContent);
 indentSpan.className="spacer";
 var allExpandedNodes = PORTFOLIO.getCookie('PF_expandable_elements');
 var all_li = startEl.getElementsByTagName('li');
 for (var i = 1; i < all_li.length; i++) {
  if (all_li[i].innerHTML.length > 1) { // Hack to avoid insert spacer into empty object_list
    var NoCookieSetOnCurrentLi = (allExpandedNodes == null || allExpandedNodes.indexOf(all_li[i].id) == -1);
    all_li[i].insertBefore(indentSpan.cloneNode(true),all_li[i].firstChild);
    li_ul = all_li[i].getElementsByTagName('ul');

  // hide all child-uls initially
    for (var u = 1; u < li_ul.length; u++) {
      li_ul[u].style.display = 'block';
    }
    if (li_ul.length > 0) {
     var anchors = all_li[i].getElementsByTagName('a');
     var done = false;
     for (var a = 0; a < anchors.length; a++) {
      if (anchors[a].className == 'highlight') {
       all_li[i].firstChild.innerHTML = '-';
       li_ul[0].style.display = 'block';
       done = true;
       break;
      }
     }
     if (!done) {
      all_li[i].firstChild.innerHTML = '+';
      li_ul[0].style.display = 'none';
     }

     //if NN6 then OK to use the standard setAttribute
     if ((!document.all) && (document.getElementById)){
      all_li[i].firstChild.setAttribute('onclick','PORTFOLIO.node_toggle_display(this,false);');
     }
     //workaround for IE
     else if ((document.all) && (document.getElementById)){
      all_li[i].firstChild.onclick = new Function('PORTFOLIO.node_toggle_display(this.nextSibling,false);');
     }
     all_li[i].firstChild.style.borderColor = '#eee';
    }
    else {
     all_li[i].firstChild.style.cursor = 'default';
    }
  }
  else {  // Hack needed for IE to hide empty object_list
    all_li[i].style.display='none';
  }
 }
    return;
};

/* find_in_page.js (formerly search_etc.js) */

/******************************************
* Find In Page Script -- Submitted/revised by Alan Koontz (alankoontz@REMOVETHISyahoo.com)
* Visit Dynamic Drive (http://www.dynamicdrive.com/) for full source code
* This notice must stay intact for use
******************************************/

// revised by Alan Koontz -- May 2003

// SELECTED BROWSER SNIFFER COMPONENTS DOCUMENTED AT
// http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html

PORTFOLIO.agt = navigator.userAgent.toLowerCase();
PORTFOLIO.is_major = parseInt(navigator.appVersion,10);
PORTFOLIO.is_ie = (PORTFOLIO.agt.indexOf("msie") != -1);
PORTFOLIO.is_ie4up = (PORTFOLIO.is_ie && (PORTFOLIO.is_major >= 4));
PORTFOLIO.is_opera = (PORTFOLIO.agt.indexOf("opera") != -1);

PORTFOLIO.searchForText = function(elem, whichframe) {

    var TRange = null;
    var dupeRange = null;
    var TestRange = null;
    var win = null;
    
    var is_mac = (PORTFOLIO.agt.indexOf("mac")!=-1);
    
    // GECKO REVISION
    var is_gecko = (PORTFOLIO.agt.indexOf('gecko') != -1);
    var is_rev=0;
    if (is_gecko) {
      var temp = PORTFOLIO.agt.split("rv:");
      is_rev = parseFloat(temp[1]);
    }

    // USE THE FOLLOWING VARIABLE TO CONFIGURE FRAMES TO SEARCH
    // (SELF OR CHILD FRAME)
    
    // If you want to search another frame, change from "self" to
    // the name of the target frame:
    // e.g., var frametosearch = 'main'
    
    //var frametosearch = 'main';
    var frametosearch = self;

  // TEST FOR IE5 FOR MAC (NO DOCUMENTATION)
  if (PORTFOLIO.is_ie4up && is_mac) {
    alert('We are sorry, but your browser has not documented this functionality');
    return;
  }

  // TEST FOR NAV 6 (NO DOCUMENTATION)
  if (is_gecko && (is_rev <1)) {
    alert('We are sorry, but your browser has not documented this functionality');
    return;
  }

  // TEST FOR Opera (NO DOCUMENTATION)
  if (PORTFOLIO.is_opera) {
    alert('We are sorry, but your browser has not documented this functionality');
    return;
  }

  // INITIALIZATIONS FOR FIND-IN-PAGE SEARCHES

  if (elem.value != null && elem.value != '') {
    str = elem.value;
    elem.value = ''; //Trick to avoid finding text entered in input 'findthis'- replaced at end of function
    if (whichframe) {
      win = whichframe;
    }
    else {
      win = frametosearch;
    }
    var frameval = false;
    if (win != self) {
      frameval = true; // this will enable Nav7 to search child frame
      win = parent.frames[whichframe];
    }
  }
  else {
    return; // i.e., no search string was entered
  }

  var strFound;

  // NAVIGATOR 4 SPECIFIC CODE
  var nom = navigator.appName.toLowerCase();
  var is_nav = (nom.indexOf('netscape')!=-1);
  var is_nav4 = (is_nav && (PORTFOLIO.is_major == 4));
  var is_minor = parseFloat(navigator.appVersion);
  if (is_nav4 && (is_minor < 5)) {
    strFound=win.find(str); // case insensitive, forward search by default
    // There are 3 arguments available:
    // searchString: type string and it's the item to be searched
    // caseSensitive: boolean -- is search case sensitive?
    // backwards: boolean --should we also search backwards?
    // strFound=win.find(str, false, false) is the explicit
    // version of the above
    // The Mac version of Nav4 has wrapAround, but
    // cannot be specified in JS
  }

  // NAVIGATOR 7 and Mozilla rev 1+ SPECIFIC CODE (WILL NOT WORK WITH NAVIGATOR 6)
  if (is_gecko && (is_rev >= 1)) {
    if (frameval!=false){
      win.focus(); // force search in specified child frame
    }
    strFound = win.find(str, false, false, true, false, frameval, false);
  }

  if (PORTFOLIO.is_ie4up) {
    // EXPLORER-SPECIFIC CODE revised 5/21/03
    if (TRange!=null) {
      TestRange=win.document.body.createTextRange();
      if (dupeRange.inRange(TestRange)) {
        TRange.collapse(false);
        strFound=TRange.findText(str);
        if (strFound) {
          TRange.select();
        }
      }
    else {
      TRange=win.document.body.createTextRange();
      TRange.collapse(false);
      strFound=TRange.findText(str);
      if (strFound) {
        TRange.select();
      }
    }
  }

  if (TRange==null || strFound==0) {
    TRange=win.document.body.createTextRange();
    dupeRange = TRange.duplicate();
    strFound=TRange.findText(str);
    if (strFound) {
     if (TRange.boundingWidth < 1) {
    alert('"'+str+'" '+PORTFOLIO.gettext('found in hidden element.')+' '+PORTFOLIO.gettext('Unable to higlight.'));
     }
     else {
       TRange.select();
     }
    }
  }
}
elem.value = str; //Trick to avoid finding text entered in input 'findthis'
  if (!strFound) {
    alert ('"'+str+'" '+PORTFOLIO.gettext('not found!')); // string not found
  }
};

/* Converts UTF8 encoded URL component, like d%C3%B8r into d%F8r

See these URLs for more information:
http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
http://xkr.us/articles/javascript/encode-compare/

*/

PORTFOLIO.convert_utf8_encoded_to_latin1_encoded = function(utf8_encoded_str) {
    return escape(decodeURIComponent(utf8_encoded_str));
}

PORTFOLIO.searchEngine = function() {
    var listBox = document.getElementById('whereToSearch');
    var categories = document.getElementById('categories');
    var searchFrase = document.getElementById('whatToSearchFor').value;

    // Search engines that need latin1 hack - they need Latin1 query string
    // FIXME: Add informative element about encoding to data structure instead
    var needLatin1 = {
        'http://www.dokpro.uio.no/perl/ordboksoek/ordbok.cgi?&bokmaal=S%F8k+i+Bokm%E5lsordboka&ordbok=bokmaal&s=n&alfabet=n&renset=n&alle_former=on&fritekst=on&OPP=' : true,
        'http://www.dokpro.uio.no/perl/ordboksoek/ordbok.cgi?nynorsk=S%F8k+i+Nynorskordboka&ordbok=nynorsk&alfabet=n&renset=j&OPP=' : true,
        'http://www.gulesider.no/tk/search.c?q=' : true,
        'http://www.vilbli.no/4daction/WA_Oppslag/?x=0&y=0&ASP=6887067&Ran=93305&Niva=V&Return=WA_kurstilbud&TP=06-04-08&find=' : true,
        'http://www.leksikon.org/search2.php?val=' : true,
        'http://norge.no/sok/?txtQueryString=' : true,
        'http://www.ssb.no/cgi-bin/swish_no.cgi?submit=S%F8k%21&sokebase=www&sort=swishrank&query=' : true,
        'http://www.alltheweb.com/cgi-bin/search?type=all&query=' : true
    };

    var dstUrl = listBox.options[listBox.selectedIndex].value;
    if ( needLatin1[dstUrl] ) {
        searchFrase = PORTFOLIO.convert_utf8_encoded_to_latin1_encoded(searchFrase);
    }

    var getString = dstUrl + searchFrase;

    if (searchFrase != '') {
        if (listBox.options[listBox.selectedIndex].value == 'clientside') {
            // && IE4){
            //document.getElementById('whatToSearchFor').value == ''; // FIXME: What's the purpose of this one?
            PORTFOLIO.searchForText(document.getElementById('whatToSearchFor'),self);
            document.getElementById('whatToSearchFor').value = searchFrase;
        }
        //findInPage(searchFrase);
        else if (categories.selectedIndex > 0) {
            externalSearch = window.open(getString,"externalSearch","location=yes,resizable=yes,scrollbars=yes,toolbar=yes,directories=no,menubar=no,width=810,height=600");
            externalSearch.focus();
        }
        else {
            window.open(getString,'_self');
        }
    }
    else {
        alert('Empty search!');
        document.getElementById('whatToSearch').focus();
    }
};

PORTFOLIO.getSelected = function(fName)  {
    if (PORTFOLIO.is_opera) {
        return;
    }
    if (PORTFOLIO.is_ie4up) {
        // MSIE
        var selectedText  =window.document.selection.createRange().text;
    }
    else if ( window.getSelection() ) {
        // Firefox/Mozilla
        var selectedText = window.getSelection();
    }
    if (selectedText != '') {
        selectedText = new String(selectedText);
        document.getElementById(fName).value = selectedText;
    }
};

/* search_build_form.js */
search_select = [
    PORTFOLIO.gettext('Search:'),
    'whereToSearch',
    [
        PORTFOLIO.gettext('Local search'),
        [
            'clientside',
            PORTFOLIO.gettext('This document')
        ],
/*
        [
            '/search/container/XXX/?query=',
            PORTFOLIO.gettext('This folder')
        ],
*/
/*
        [
            '/search/course/XXX/?query=',
            PORTFOLIO.gettext('This course')
        ],
*/
        [
            PORTFOLIO.site_url + 'search/site/?query=',
            PORTFOLIO.gettext('This site')
        ],
        [
            PORTFOLIO.site_url + 'read_glossary/?code=',
            PORTFOLIO.gettext('Portfolio glossary')
        ],
        [
            PORTFOLIO.site_url + 'search/my_portfolio/?query=',
            PORTFOLIO.gettext('My documents')
        ],
        [
            PORTFOLIO.site_url + 'search/user/?query=',
            PORTFOLIO.gettext("Search for user")
        ],
        [
            PORTFOLIO.site_url + 'search/group/?query=',
            PORTFOLIO.gettext("Search for group")
        ]
    ],
    [
        PORTFOLIO.gettext('Dictionaries and Glossaries'),
        [
            'http://www.dokpro.uio.no/perl/ordboksoek/ordbok.cgi?&bokmaal=S%F8k+i+Bokm%E5lsordboka&ordbok=bokmaal&s=n&alfabet=n&renset=n&alle_former=on&fritekst=on&OPP=',
            'Bokmålsordboka (uio)'
        ],
        [
            'http://www.dokpro.uio.no/perl/ordboksoek/ordbok.cgi?nynorsk=S%F8k+i+Nynorskordboka&ordbok=nynorsk&alfabet=n&renset=j&OPP=',
            'Nynorskordboka (uio)'
        ],
        [
            'http://dictionary.reference.com/search?db=dictionary&q=',
            'Dictionary.com'
        ],
        [
            'http://thesaurus.reference.com/search?db=thesaurus&q=',
            'Thesaurus.com'
        ],
        [
            'http://www.ordboka.net/?q=',
            'Ordboka.net (norsk-engelsk)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&run-search=&search=',
            'Lexin (norsk)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-ara-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=ARA&run-search=&search=',
            'Lexin (norsk-arabisk)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-kku-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=KKU&run-search=&search=',
            'Lexin (norsk-kurdisk/kurmanji)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-kso-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=KSO&run-search=&search=',
            'Lexin (norsk-kurdisk/sorani)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-per-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=PER&run-search=&search=',
            'Lexin (norsk-perisk)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-som-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=SOM&run-search=&search=',
            'Lexin (norsk-somali)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-tam-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=T&run-search=&search=',
            'Lexin (norsk-tamil)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-tir-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=TIR&run-search=&search=',
            'Lexin (norsk-tigrinja)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-tur-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=TUR&run-search=&search=',
            'Lexin (norsk-tyrkisk)'
        ],
        [
            'http://www.lexin.no/lexin.html?dict=nbo-ur-maxi&ui-lang=nbo&checked-languages=E&checked-languages=N&checked-languages=UR&run-search=&search=',
            'Lexin (norsk-urdu)'
        ]
    ],
    [
        PORTFOLIO.gettext('Search engines'),
        [
            'http://www.altavista.com/web/results?itag=ody&kgs=1&kls=1&q=',
            'AltaVista'
        ],
        [
            'http://no.altavista.com/web/results?itag=ody&kgs=1&kls=1&q=',
            'AltaVista Norge '
        ],
        [
            'http://www.ask.com/main/askJeeves.asp?Source=0&site_name=Jeeves&scope=web&metasearch=yes&r=x&frames=no&spellcheck=on&ask=',
            'Ask Jeeves'
        ],
        [
            'http://www.google.com/search?hl=no&q=',
            'Google ('+ PORTFOLIO.gettext('Norwegian - Bokmaal') +')'
        ],
        [
            'http://www.google.com/search?hl=nn&q=',
            'Google ('+ PORTFOLIO.gettext('Norwegian - Nynorsk') +')'
        ],
        [
            'http://scholar.google.no/scholar?hl=no&lr=&q=',
            'Google Scholar'
        ],
        [
            'http://books.google.com/books?as_brr=0&q=',
            'Google Book Search'
        ],
        [
            'http://video.google.com/videosearch?q=',
            'Google Video'
        ],
        [
            'http://www.hotbot.com/?&ps=&loc=searchbox&tab=web&mode=search&query=',
            'HotBot'
        ],
        [
            'http://www.alltheweb.com/cgi-bin/search?type=all&query=',
            'FAST - All the Web'
        ],
        [
            'http://www.kvasir.no/nettsok/searchResult.html?x=61&y=19&searchRegion=country&searchExpr=',
            'Kvasir'
        ],
        [
            'http://www.metacrawler.com/metacrawler/ws/redir/rfcp=Other/rfcid=999915/_iceUrlFlag=11?_IceUrl=true&qcat=web&qkw=',
            'MetaCrawler / WebCrawler'
        ],
        [
            'http://www.bing.com/search?q=',
            'Microsoft Bing search'
        ],
        [
            'http://no.search.yahoo.com/search;_ylt=A1f4cff6BNdKbOoANZ0qNAx.?fr=sfp&fr2=&rd=r1&p=',
            'Yahoo (Norge)'
        ],
        [
            'http://search.yahoo.com/search?q=',
            'Yahoo (verden)'
        ]
    ],
    [
        PORTFOLIO.gettext('Graphic Resources'),
        [
            'http://www.altavista.com/image/results?pg=q&stype=simage&imgset=2&avkw=xytx&q=',
            'AltaVista graphics'
        ],
        [
            'http://images.google.no/images?hl=en&q=',
            'Google Images'
        ],
        [
            'http://www.morguefile.com/archive/browse/#/?qury=',
            'MorgueFile'
        ]
    ],
    [
        PORTFOLIO.gettext('Indexes and Start Pages'),
        [
            'http://abcsok.no/index.html?lr=www-en-us&q=',
            'ABC Startsiden'
        ],
        [
            'http://origo.no/-/explore/posts?q=',
            'Origo Index'
        ]
    ],
    [
        PORTFOLIO.gettext('Public Services'),
        [
            'http://www.nav.no/systemsider/Søk?queryparameter=',
            'NAV'
        ],
        [
            'http://norge.no/sok/?txtQueryString=',
            'Norge.no'
        ],
        [
            'http://www.regjeringen.no/nb/sok.html?id=86008&quicksearch=',
            'Regjeringen.no'
        ],
        [
            'http://www.ssb.no/cgi-bin/swish_no.cgi?submit=S%F8k%21&sokebase=www&sort=swishrank&query=',
            'Statistisk sentralbyrå'
        ]
    ],
    [
        PORTFOLIO.gettext('Encyclopedias'),
        [
            'http://encarta.msn.com/encnet/refpages/search.aspx?q=',
            'Encarta'
        ],
        [
            'http://www.google.com/custom?domains=www.pantheon.org&sitesearch=www.pantheon.org&client=pub-4733091037612954&forid=1&channel=6911122456&ie=UTF-8&oe=UTF-8&safe=active&cof=GALT%3A%23000088%3BGL%3A1%3BDIV%3A%23FFFFFF%3BVLC%3A000088%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A4B82CC%3BALC%3A000088%3BLC%3A000088%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BLH%3A50%3BLW%3A164%3BL%3Ahttp%3A%2F%2Fwww.pantheon.org%2Fimages%2Fmythica_small.png%3BS%3Ahttp%3A%2F%2Fwww.pantheon.org%2F%3BFORID%3A1%3B&hl=en&q=',
            'Encyclopaedia Mythica'
        ],
        [
            'http://www.bartleby.com/cgi-bin/texis/webinator/sitesearch?FILTER=col65&query=',
            'Columbia Encyclopedia'
        ],
        [
            'http://www.leksikon.org/search2.php?val=',
            'Leksikon.org ('+PORTFOLIO.gettext('danish')+')'
        ],
        [
            'http://en.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('english')+')'
        ],
        [
            'http://fr.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('french')+')'
        ],
        [
            'http://no.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('norwegian')+')'
        ],
        [
            'http://pt.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('portugis')+')'
        ],
        [
            'http://es.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('spanish')+')'
        ],
        [
            'http://de.wikipedia.org/wiki/Spesial:Search/?search=',
            'Wikipedia ('+PORTFOLIO.gettext('german')+')'
        ]
    ],
    [
        PORTFOLIO.gettext('Religious Scriptures'),
        [
            'http://www.islam.no/newsite/content/default.asp?Action=NewSearch&nTopPage=52&searchstring=',
            'Koranen (norsk database)'
        ]
    ],
    [
        PORTFOLIO.gettext('School and Education'),
        [
            'http://utdanning.no/finn/?s=',
            'Utdanning.no'
        ],
        [
            'http://www.utdanningsnytt.no/templates/Search20____307.aspx?quicksearchquery=',
            'Utdanning.ws'
        ],
        [
            'http://utdanningsdirektoratet.no/templates/udir/TM_S%C3%B8k.aspx?id=197&quicksearchquery=',
            'Utdanningsdirektoratet'
        ],
        [
            'http://www.vilbli.no/4daction/WA_Oppslag/?x=0&y=0&ASP=6887067&Ran=93305&Niva=V&Return=WA_kurstilbud&TP=06-04-08&find=',
            'vilbli.no'
        ]
    ],
    [
        PORTFOLIO.gettext('Media'),
        [
            'http://search.bbc.co.uk/cgi-bin/search/results.pl?uri=%2F&scope=all&go=toolbar&q=',
            'BBC'
        ],
        [
            'http://search.cnn.com/search.jsp?type=web&sortBy=date&intl=false&query=',
            'CNN'
        ],
        [
            'http://www.mylder.no/newssearch.php?kategori=&limit=50&search=',
            'Mylder.no (nyheter)'
        ],
        [
            'http://partner.sesam.no/nrk/?c=n&ss_lt=sitesearch&ss_ss=nrk.no&ss_pid=nrk&ss_vpos=top&userSortBy=datetime&q=',
            'NRK'
        ],
        [
            'http://www.wired.com/search?siteAlias=all&x=0&y=0&query=',
            'Wired News'
        ],
        [
            'http://no.news.search.yahoo.com/search/news?fr=sfp&ei=UTF-8&p=',
            'Yahoo nyheter'
        ]
    ],
    [
        PORTFOLIO.gettext('Phone Books'),
        [
            'http://www.gulesider.no/tk/search.c?q=',
            'Gule sider'
        ],
        [
            'http://www.1881.no/?qt=8&Query=',
            '1881'
        ]
    ]
];

// FOR TEST PURPOSES
// PORTFOLIO.default_search = 'http://decentius.hit.uib.no/lexin.html?dict=nbo-maxi&checked-languages=E&checked-languages=N&search=';
// NB! uncoment all lines with remember_search_engine

PORTFOLIO.populateSelect = function(sel1,sel2,selArr,is_logged_in) {
  if (is_logged_in) {
    document.forms.element_search.remember_search_engine.checked ='';
  }
  var select1 = document.getElementById(sel1);
  var index = select1.selectedIndex +2;
  var select2 = document.getElementById(sel2);
  select2.options.length = 0;
  for (var j = 1; j < selArr[index].length; j++) {
    select2.options[select2.options.length] = new Option(search_select[index][j][1],search_select[index][j][0]); 
    if (is_logged_in) {
      if (selArr[index][j][0] == PORTFOLIO.default_search) {
        select2.options[j-1].selected='selected';
        document.forms.element_search.remember_search_engine.checked ='checked';
      }
    }
  }
};

PORTFOLIO.write_search_config = function (checked_element) {
    var ajax_param = '';
    var check_el = document.getElementById(checked_element);
    var sel1 = document.forms.element_search.categories;
    var sel2 = document.forms.element_search.whereToSearch;
    var option1 = sel1.options[sel1.selectedIndex].value;
    var option2 = sel2.options[sel2.selectedIndex].value;
    if (check_el.checked) {
        if (confirm( PORTFOLIO.gettext('Set as preferred search engine?') + '\n\n     ' + sel2.options[sel2.selectedIndex].text)) {
            ajax_param = 'xml/write_config/?type=account;code=default_search;value='+encodeURIComponent(option2)+';force_overwrite=1';
        }
        else {
            check_el.checked = '';
            return false;
        }
    }
    else {
        if (confirm( PORTFOLIO.gettext('Remove preferred search engine?') + '\n\n     ' + sel2.options[sel2.selectedIndex].text)) {
            ajax_param = 'xml/delete_config/?type=account;code=default_search';
        }
        else {
            check_el.checked = 'checked';
            return false;
        }
    }
    if (ajax_param != '') {
        PORTFOLIO.makeRequest('/',ajax_param,true);
    }
};

PORTFOLIO.uncheck_search_checkbox = function(){
  document.forms.element_search.remember_search_engine.checked ='';
};

PORTFOLIO.create_search_form = function(build_in_this_element,is_logged_in) {
  var container = document.getElementById(build_in_this_element);
  if (!container) {
     return false;
  }
  var newForm = document.createElement('form');
  newForm.setAttribute('id','element_search');
  newForm.setAttribute('action','javascript:PORTFOLIO.searchEngine();');
  newForm.setAttribute('method','post');
  if ((!document.all) && (document.getElementById)) {
    newForm.setAttribute('onclick','PORTFOLIO.getSelected("whatToSearchFor");'); //workaround for IE
  }
  else if ((document.all) && (document.getElementById)) {
    newForm.onclick = new Function('PORTFOLIO.getSelected("whatToSearchFor");');
  }
  var newFieldset = document.createElement('fieldset');
  
  var delimit = document.createTextNode( PORTFOLIO.gettext('Search:') + ' ');
  newFieldset.appendChild(delimit);

  var select1  = document.createElement('select');
  select1.id   = "categories";
  select1.name = "categories";
  for (var i = 2; i < search_select.length;  i++) {
    select1.options[select1.options.length] = new Option(search_select[i][0]);
    for (var j = 1; j < search_select[i].length; j++) {
      if (search_select[i][j][0] == PORTFOLIO.default_search) {
    select1.options[i-2].selected='selected';
      }
    }
  }
  if ((!document.all) && (document.getElementById)) {
    select1.setAttribute('onchange','PORTFOLIO.populateSelect("categories","whereToSearch",search_select,'+is_logged_in+');'); //workaround for IE
  }
  else if ((document.all) && (document.getElementById)) {
    select1.onchange = new Function('PORTFOLIO.populateSelect("categories","whereToSearch",search_select,'+is_logged_in+');');
  }

  newFieldset.appendChild(select1);

  var select2  = document.createElement('select');
  select2.id   = "whereToSearch";
  select2.name = "whereToSearch";
  if (is_logged_in) {
    if ((!document.all) && (document.getElementById)) {
      select2.setAttribute('onchange','PORTFOLIO.uncheck_search_checkbox();'); //workaround for IE
    }
    else if ((document.all) && (document.getElementById)) {
      select2.onchange = new Function('PORTFOLIO.uncheck_search_checkbox();');
    }
  }
  newFieldset.appendChild(select2);

// NB! IKKE FOR ANONYME BRUKERE!!!!
  if (is_logged_in) {
    var check1 = document.createElement('input');
    check1.type = 'checkbox';
    check1.id = 'remember_search_engine';
    check1.name = 'remember_search_engine';

    if ((!document.all) && (document.getElementById)) {
      check1.setAttribute('onclick','PORTFOLIO.write_search_config("remember_search_engine");'); //workaround for IE
    }
    else if ((document.all) && (document.getElementById)) {
      check1.onclick = new Function('PORTFOLIO.write_search_config("remember_search_engine");');
    }
    check1.title = PORTFOLIO.gettext('Remember selected');
    newFieldset.appendChild(check1);
  }
  var textinput  = document.createElement('input');
  textinput.setAttribute('type','text');
  textinput.setAttribute('id','whatToSearchFor');
  textinput.setAttribute('name','whatToSearchFor');  
  textinput.setAttribute('value','');


  newFieldset.appendChild(textinput);

  var mybutton  = document.createElement('input');
  mybutton.setAttribute('type','button');
  mybutton.setAttribute('id','goSearch');
  mybutton.setAttribute('name','goSearch');  
  mybutton.setAttribute('value', PORTFOLIO.gettext('Search') );  
  mybutton.setAttribute('accesskey','s');  
  if ((!document.all) && (document.getElementById)) {
    mybutton.setAttribute('onclick','PORTFOLIO.getSelected("whatToSearchFor");PORTFOLIO.searchEngine();'); //workaround for IE
    mybutton.setAttribute('onkeypress','PORTFOLIO.getSelected("whatToSearchFor");PORTFOLIO.searchEngine();'); //workaround for IE    
  }
  else if ((document.all) && (document.getElementById)) {
    mybutton.onclick = new Function('PORTFOLIO.getSelected("whatToSearchFor");PORTFOLIO.searchEngine();');
    mybutton.onkeypress = new Function('PORTFOLIO.getSelected("whatToSearchFor");PORTFOLIO.searchEngine();');    
  }
  newFieldset.appendChild(mybutton);

  newForm.appendChild(newFieldset);

  container.appendChild(newForm);

  PORTFOLIO.populateSelect('categories','whereToSearch',search_select,is_logged_in);

// Need to set checked after the form is inserted to DOM
  if (is_logged_in) {
     if (PORTFOLIO.default_search && PORTFOLIO.default_search != '') {
       document.getElementById('remember_search_engine').checked ='checked';
     }
  }
};


/* togglecheckboxes.js

    Copyright (C) Portfolio AS,  http://www.portfolio.as/
    version 1.0 18.01.2006 by Frode Rustoy

Three functions to select, deselect or invert selction in one or more sets of checboxes in a form

All three functions takes the same two parameters:

    boxName: one or more name used on one set. If more then one set separate with comma
    theForm: the form containing the checboxes AND the buttons to trigger the functions

SAMPLE:

<button type="button" onclick="PORTFOLIO.checkAllCheckboxes('check_container,check_object',this.form);">
Select all
</button>

In the above sample all checboxes named check_container or check_object in the same form that
also contain the button itself should be selected.
*/


PORTFOLIO.checkAllCheckboxes = function(boxName, theForm) {
        var splitPattern = /\,/g;
        var boxNames =boxName.split (splitPattern);
        for (var i=0; i < boxNames.length; i++)  {
        var count = 0;
            do {
                var checkBox = theForm.elements[count];
                if (checkBox.name==boxNames[i] && checkBox.type == 'checkbox') {
                        checkBox.checked=true;
                }
                count++;
               } while (count < theForm.length);
    }
};
     
PORTFOLIO.uncheckAllCheckboxes = function(boxName, theForm) {
        var splitPattern = /\,/g;
        var boxNames =boxName.split (splitPattern);
        for (var i=0; i < boxNames.length; i++)  {
        var count = 0;
        do {
            var checkBox = theForm.elements[count];
                 if (checkBox.name==boxNames[i] && checkBox.type == 'checkbox') {
                        checkBox.checked=false;
                }
                count++;
               } while (count < theForm.length);
    }
};

PORTFOLIO.getPFxcellContent = function(appletID,contentID) {
  if ( ! document.getElementById(contentID) && document.getElementById(appletID)) {
    return false;
  }
  var myContent = document.getElementById(contentID);
  myContent.value=document.getElementById(appletID).getPFxcell_content('');
  if (!myContent.form) {
    return false;
  }
  var formElement = myContent.form;
  if (!(formElement.elements.type && formElement.elements.mimetype)) {
    return false;
  }
  formElement.elements.type.value='spreadsheet';
//  formElement.elements.mimetype.value='application/x-jxcell';    
  formElement.elements.mimetype.value='application/vnd.ms-excel';    
  return true;
};

/* matchbox.js */

/* Used by various array .sort() calls */
PORTFOLIO.randomSortOrder = function() {
  return (Math.round(Math.random())-0.5);
}; 

PORTFOLIO.getFlashMovieObject = function (movieName) {
  if (window.document[movieName]) {
    return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[movieName]) {
      return document.embeds[movieName];
    }
  }
  else { // if (navigator.appName.indexOf("Microsoft Internet")!=-1) {
    return document.getElementById(movieName);
  }
};

/*** BEGIN: MATCHBOX *****************************************************************************/

PORTFOLIO.MATCHBOX = {};

PORTFOLIO.MATCHBOX.match_pairs = 0;
PORTFOLIO.MATCHBOX.pairs_found = 0;
PORTFOLIO.MATCHBOX.correct_count = 0;
PORTFOLIO.MATCHBOX.error_count = 0;
PORTFOLIO.MATCHBOX.score_value_pr_pair = 0;
PORTFOLIO.MATCHBOX.last_clicked_type = '';
PORTFOLIO.MATCHBOX.last_clicked_num = '';

PORTFOLIO.MATCHBOX.encode_dos_western_europe = function (string) {
    string=string.replace(/å/g,'%86');
    string=string.replace(/æ/g,'%91');
    string=string.replace(/ø/g,'%3F');
    string=string.replace(/Å/g,'%8F');
    string=string.replace(/Æ/g,'%92');
    string=string.replace(/Ø/g,'%3F'); // May be an other code
    return string;
};

PORTFOLIO.MATCHBOX.talkbook = function (myWord,language) {
    if ( !language ) {
        language='nb_NO';
    }
    var myUrl;
    myWord = PORTFOLIO.trim(myWord);
    if(myWord.length == 1) {
        myWord = myWord.toUpperCase();
        if (language == 'en_UK') {
            myUrl = PORTFOLIO.static_url+'talkbook/en_UK/0/'+PORTFOLIO.MATCHBOX.encode_dos_western_europe(myWord)+'_sound2.mp3';
        }
        else if (language == 'nb_NO') {
            myUrl = PORTFOLIO.static_url+'talkbook/nb_NO/0/'+PORTFOLIO.MATCHBOX.encode_dos_western_europe(myWord)+'.mp3';
        }
    }
    else if(myWord.length == 2 && myWord.charAt(1) == '*') {
        myWord = myWord.charAt(0).toUpperCase();
        if (language == 'en_UK') {
            myUrl = PORTFOLIO.static_url+'talkbook/en_UK/0/'+PORTFOLIO.MATCHBOX.encode_dos_western_europe(myWord)+'.mp3';
        }
        else if (language == 'nb_NO') {
            myUrl = PORTFOLIO.static_url+'talkbook/nb_NO/0/'+PORTFOLIO.MATCHBOX.encode_dos_western_europe(myWord)+'_bokstavnavn.mp3';
        }
    }
    else {
        var FolderName = myWord.charAt(0);
        FolderName = FolderName.toLowerCase();
        FolderName = FolderName.replace(/Æ/g,'æ');
        FolderName = FolderName.replace(/Ø/g,'ø');
        FolderName = FolderName.replace(/Å/g,'å');
        myUrl = PORTFOLIO.static_url+'talkbook/'+language+'/' + PORTFOLIO.MATCHBOX.encode_dos_western_europe(FolderName)+'/' + PORTFOLIO.MATCHBOX.encode_dos_western_europe(myWord)+'.mp3';
    }

    // Remember that soundManager must be enabled with include_dep() in the calling code
    // first arg is the soundmanager unique identifier, second arg is the actual url
    if ( soundManager ) {
        soundManager.play(myUrl, myUrl);
    }
    else {
        alert("Unable to play back sound without include_dep('soundmanager') or include_dep('matchbox') specified in template!");
    }
};

PORTFOLIO.MATCHBOX.check = function(item, boxID) {
    if (item.firstChild.style.visibility != 'hidden') {
        var item_id = item.id;
        var item_type = item_id.substring(0,1);
        var error   = false;
        var correct = false;
        var undo    = false; // possible to deselect 
        item_num = item_id.substring(1,item_id.length);
        if (item_type == PORTFOLIO.MATCHBOX.last_clicked_type) {
            if (item_num == PORTFOLIO.MATCHBOX.last_clicked_num) {
                undo = true;
            }
            else {
                error = true;
            }
        }
        else if (PORTFOLIO.MATCHBOX.last_clicked_type != '') {
            if (PORTFOLIO.MATCHBOX.last_clicked_num == item_num) {
                var A = "A"+item_num;
                var B = "B"+item_num;
                document.getElementById(A).style.cursor = 'default';
                document.getElementById(A).firstChild.style.visibility = 'hidden';
                document.getElementById(A).style.background = "url("+PORTFOLIO.static_url+"gfx/matchbox_cardback.jpg) #FFFF00";
                document.getElementById(B).style.cursor = 'default';
                document.getElementById(B).firstChild.style.visibility = 'hidden';
                document.getElementById(B).style.background = "url("+PORTFOLIO.static_url+"gfx/matchbox_cardback.jpg) #FFFF00";
                correct = true;
            }
            else {
                error = true;
            }
        }
        else {
            PORTFOLIO.MATCHBOX.last_clicked_type = item_type;
            PORTFOLIO.MATCHBOX.last_clicked_num  = item_num;
            item.style.borderColor='yellow';
            item.style.backgroundColor='red';
            item.style.color='white';
        }
        if (error == true) {
            PORTFOLIO.MATCHBOX.error_count += PORTFOLIO.MATCHBOX.score_value_pr_pair;
            if (PORTFOLIO.MATCHBOX.error_count >= 100) {
                PORTFOLIO.MATCHBOX.error_count = 100;
                document.getElementById('matchbox_reshuffle').disabled=false;
                alert(
                      PORTFOLIO.gettext('You may have misunderstood this exercise.')
                    + "\n"
                    + PORTFOLIO.gettext('Try clicking on "Reshuffle" and start over again.')
                );
            }
            document.getElementById('ErrorDiagram').style.width=PORTFOLIO.MATCHBOX.error_count+'%';
        }
        else if (correct==true) {
            PORTFOLIO.MATCHBOX.correct_count += PORTFOLIO.MATCHBOX.score_value_pr_pair;
            PORTFOLIO.MATCHBOX.pairs_found++;
            document.getElementById('CorrectDiagram').style.width=PORTFOLIO.MATCHBOX.correct_count+'%';
        }
        if (correct==true || error==true || undo==true) {
            var restore_color = '';
            if (PORTFOLIO.MATCHBOX.last_clicked_type=='A') {
                restore_color = '#FFFFCC';
            }
            var last_item_id = PORTFOLIO.MATCHBOX.last_clicked_type+PORTFOLIO.MATCHBOX.last_clicked_num;
            document.getElementById(last_item_id).style.borderColor = '';
            document.getElementById(last_item_id).style.backgroundColor = restore_color;
            document.getElementById(last_item_id).style.color = '';
            PORTFOLIO.MATCHBOX.last_clicked_type = '';
            PORTFOLIO.MATCHBOX.last_clicked_num = '';
        }
        if (PORTFOLIO.MATCHBOX.pairs_found == PORTFOLIO.MATCHBOX.match_pairs) {
            var all_items = document.getElementById("element_matchbox").getElementsByTagName('td');
            for (var i = 0; i < all_items.length; i++) {
                all_items[i].style.background = "url("+PORTFOLIO.static_url+"gfx/matchbox_joker.gif) no-repeat center center #FFFF00";
            }
            document.getElementById('matchbox_reshuffle').disabled=false;
            var total_score = parseInt(PORTFOLIO.MATCHBOX.correct_count-PORTFOLIO.MATCHBOX.error_count,10);
            if (total_score < 0) {
                total_score = 0;
            }
            if (document.getElementById(boxID).value < total_score) {
                document.getElementById(boxID).value=total_score;
            }
        } 
    }
};

PORTFOLIO.MATCHBOX.make = function(quiz_id, matchbox_data) {
    if ( matchbox_data ) {
        // Store matchbox_data for potential reshuffle
        PORTFOLIO.MATCHBOX[quiz_id] = matchbox_data;
    }
    else {
        // Invoked via reshuffle, used stored matchbox_data
        matchbox_data = PORTFOLIO.MATCHBOX[quiz_id];
    }

    var pairs = matchbox_data.pairs;
    var cols = matchbox_data.cols;
    var rows = matchbox_data.rows;

    var matchboxWidth = 500;

    // Initiating global variables
    PORTFOLIO.MATCHBOX.pairs_found = 0;
    PORTFOLIO.MATCHBOX.correct_count = 0;
    PORTFOLIO.MATCHBOX.error_count = 0;
    PORTFOLIO.MATCHBOX.score_value_pr_pair = 0;
    PORTFOLIO.MATCHBOX.last_clicked_type = '';
    PORTFOLIO.MATCHBOX.last_clicked_num = '';
    PORTFOLIO.MATCHBOX.match_pairs = (cols*rows)/2;
    PORTFOLIO.MATCHBOX.score_value_pr_pair = 100 / PORTFOLIO.MATCHBOX.match_pairs;

    var CellWidth = matchboxWidth / cols;
    var CellHeight= CellWidth; //(CellWidth / 3)*4;
    //CellHeight = CellHeight-8;
    //CellWidth = CellWidth-8;
    var percentWidth = 100/cols;

    pairs.sort(PORTFOLIO.randomSortOrder);

    // Create array of HTML elements to display in table
    var item_array = [];
    for (var i = 0; i < PORTFOLIO.MATCHBOX.match_pairs; i++) {
        if (pairs[i]) {
            var item = pairs[i];
            var sound_language = item.language ? item.language : matchbox_data.language;
            item_array.push(
                  '<td id="A' + i + '"'
                + ' style="width:' + CellWidth + 'px;'
                + 'height:' + CellHeight + 'px;'
                + 'background-color:#FFFFCC;" class="match_a"'
                + ' onclick="PORTFOLIO.MATCHBOX.check(this,\'' + quiz_id + '\');">'
                + '<div style="width:' + (CellWidth-10) + 'px;'
                + 'padding:0;font-size:100%;text-align:center;">'
                + item.word1
                + '</div></td>'
            );

            var visual2;
            var onclick2='';
            if ( !item.word2 || sound_language ) {
                visual2 = '<img src="' + PORTFOLIO.site_url + 'get_icon/?icon_id=object/audio"'
                    + ' alt="' + PORTFOLIO.gettext('Matchbox: click to listen') + '"'
                    + ' title="' + PORTFOLIO.gettext('Matchbox: click to listen') + '"'
                    + ' />';
                if ( !sound_language ) {
                    sound_language = "nb_NO"; // This really should be inherited from object.content_language or something more sane
                }
                // Convention used in PORTFOLIO.MATCHBOX.talkbook() to denote a letter being spoken
                var use_letter_name=item.use_letter_name ? "*" : "";
                if ( item.word2 ) {
                    onclick2 = "PORTFOLIO.MATCHBOX.talkbook('" + item.word2.replace(/'/g,"\\'") + use_letter_name + "','"+sound_language+"');";
                }
                else {
                    onclick2 = "PORTFOLIO.MATCHBOX.talkbook('" + item.word1.replace(/'/g,"\\'") + use_letter_name + "','"+sound_language+"');";
                }
            }
            else {
                visual2 = item.word2;
            }
            item_array.push(
                  '<td id="B' + i + '"'
                + ' style="'
                + 'width:' + CellWidth + 'px;'
                + 'height:' + CellHeight + 'px;"'
                + ' class="match_b" '
                + 'onclick="PORTFOLIO.MATCHBOX.check(this,\'' + quiz_id + "');"
                + onclick2.replace(/"/g,'\\"')
                + '">'
                + '<div style="'
                + 'width:' + (CellWidth-10) + 'px;'
                + 'padding:0;margin:0;font-size:100%;text-align:center;'
                + '">'
                + visual2
                + '</div></td>'
            );
        }
    }
    item_array.sort( PORTFOLIO.randomSortOrder );

    // Build table from item_array
    var match_table = '<center><table id="element_matchbox" style="width:'+matchboxWidth+'px"><tr>';
    for (var i = 0; i < item_array.length; i++) {
        if ((i) % cols == 0) {
            match_table += "</tr><tr>";
        }
        match_table += item_array[i];
    }
    match_table += '</tr>';
    match_table +=
          '<tr><th colspan="'
        + (cols-1)
        + '" bgcolor="#eee" style="white-space:nowrap;height:10px;background-color:#fff;width:100%;padding:0;margin:0;"><img src="'
        + PORTFOLIO.static_url
        + 'gfx/matchbox_greengraph.jpg" style="height:10px; width:0;padding:0;margin:0;border:none;"'
        + ' id="CorrectDiagram" name="CorrectDiagram"></th>';
    var shuffle_button = '<button type="button" disabled="disabled" id="matchbox_reshuffle"'
        + ' onclick="PORTFOLIO.MATCHBOX.make(\'' + quiz_id + '\');"'
        + '>'
        + PORTFOLIO.gettext('Reshuffle')
        + "</button>";
    match_table +=
          '<th rowspan="2" style="text-align: center;border:none;vertical-align:top;">'
        + shuffle_button
        + '</th></tr>';
    match_table +=
          '<tr><th colspan="'
        + (cols-1)
        + '" bgcolor="#eee" style="white-space:nowrap;height:10px;background-color:#fff;padding:0;margin:0;width:100%"><img src="'
        + PORTFOLIO.static_url
        + 'gfx/matchbox_redgraph.jpg" style="height:10px; width:0;padding:0;margin:0;border:none;"'
        + ' id="ErrorDiagram" name="ErrorDiagram"></th></tr>';
    match_table += '</table></center>';

    // Find or create matchbox container DOM element
    var matchbox_container = $("#" + quiz_id + " + div.matchbox");
    if ( ! matchbox_container.get(0) ) {
        matchbox_container = $("#" + quiz_id).after("<div class=\"matchbox\" />").next();
    }

    // Add HTML to container and show it
    matchbox_container.html(match_table).show();

    // Manipulate images inside container
    matchbox_container.find("img").each(function() {

        // Get jQuery instance of current DOM element (img)
        var my = $(this);

        my.css("padding","0");
        my.parent().css("margin","0");
        my.parent().css("padding","0");
        my.parent().parent().css("text-align","center");

        if ( my.attr("title") !== PORTFOLIO.gettext('Matchbox: click to listen') ) {
            my.attr("title", PORTFOLIO.gettext('Matchbox: hidden title') );
            my.attr("alt", PORTFOLIO.gettext('Matchbox: hidden alternative text') );
        }

        // Recalculate some dimensions (must be done while visible, see offsetWidth/Height docs)
        
        // Landscape mode
        if ( my.width() > ( CellWidth - 10 ) ) {
            my.width( ( CellWidth - 10 ) + 'px' );
            my.height('auto');
        }
        
        // Portrait
        if ( my.height() > ( CellWidth - 10 ) ) {
            my.width('auto');
            my.height( ( CellWidth - 10 ) + 'px' );
        }

    });
};

/*** END: MATCHBOX *****************************************************************************/

PORTFOLIO.toggleCheckboxes = function(el,name) {

  var nodes, i, input;

  if(!el) {
    return false;
  }

  nodes=el.elements;
  for(i=0; i < nodes.length; i++) {
    input=nodes[i];
    if (input.type == 'checkbox') {
      // If name is specified, only toggle checkboxes with the specified name
      // If name is not specified, toggle all checkboxes
      if (name) {
    if ( input.name == name) {
          input.checked=input.checked ? false : true;
        }
      }
      else {
        input.checked=input.checked ? false : true;
      }
    }
  }

  return true;

};

PORTFOLIO.toggleCheckboxesWithin = function(el,name,ancestor_el) {

  var nodes, i, input;

  if(!el) {
    return false;
  }

  if(!ancestor_el) {
    return false;
  }

  nodes=el.elements;
  for(i=0; i < nodes.length; i++) {
    input=nodes[i];
    if ( $(input).parents().index(ancestor_el) < 0) {
        continue; // Let's just skip as input is not within ancestor's container
    }
    if (input.type == 'checkbox') {
      // If name is specified, only toggle checkboxes with the specified name
      // If name is not specified, toggle all checkboxes
      if (name) {
    if ( input.name == name) {
          input.checked=input.checked ? false : true;
        }
      }
      else {
        input.checked=input.checked ? false : true;
      }
    }
  }

  return true;

};

PORTFOLIO.submitXHR = function(form, callback) {

  var formData, request;

  if(!form) {
    return false;
  }

  $.ajax({
        url: form.action,
        type: form.method,
        data: $(form).serialize(),
        success: callback.success,
        error: callback.failure
    });

  return true;

};

/*************************** SPEECH SYNTHESIS ******************************/

PORTFOLIO.compressWhiteSpace=function(s) {

  // Condense white space.

  s = s.replace(/\s+/g, " ");
  s = s.replace(/^\s(.*)/, "$1");
  s = s.replace(/(.*)\s$/, "$1");

  // Remove uneccessary white space around operators, braces and parentices.

  s = s.replace(/\s([\x21\x25\x26\x28\x29\x2a\x2b\x2c\x2d\x2f\x3a\x3b\x3c\x3d\x3e\x3f\x5b\x5d\x5c\x7b\x7c\x7d\x7e])/g, "$1");
  s = s.replace(/([\x21\x25\x26\x28\x29\x2a\x2b\x2c\x2d\x2f\x3a\x3b\x3c\x3d\x3e\x3f\x5b\x5d\x5c\x7b\x7c\x7d\x7e])\s/g, "$1");
  return s;
};

PORTFOLIO.removeHTMLComments=function(html) {
    return html.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g,'');
};


PORTFOLIO.prepareHTMLtoSpeech = function(clip){
    clip = clip.replace(/\<\/h/gi,'.</h');
    clip = clip.replace(/\<\/li/gi,'.</li');
    clip = clip.replace(/\<\/td/gi,'.</td');
    clip = clip.replace(/\<\/th/gi,'.</th');
    clip = clip.replace(/\<\/block/gi,'.</block');
    clip = clip.replace(/\<br/gi,'.<br');
    clip = clip.replace(/\<\/div/gi,'.</div');
    clip = clip.replace(/\<\/p/gi,'.</p');
    clip = clip.replace(/\<(script)[^>]*>[^<]*(\<\/script>)/ig,'');
//    clip = clip.replace(/\<\!--*?--\>/g,'');
    clip = PORTFOLIO.removeHTMLComments(clip);
    clip = PORTFOLIO.remove_html_tag(clip);
//    clip = clip.replace(/-->/g,'');
    clip=clip.replace(/\«/g,' ');
    clip=clip.replace(/\r/g,'');
    clip= clip.replace(/\n/g,' ');
    clip = clip.replace(/(\s\.)+/g,'. ');
    clip = clip.replace(/(\.\s\.)+/g,'. ');
    clip = clip.replace(/(\.\s)+/g,'. ');
    clip = clip.replace(/(\.)+/g,'. ');
//    clip = clip.replace(/(\.)/g,'. ');
    clip = clip.replace(/\:/g,': ');
    clip = clip.replace(/\!/g,'! ');
    clip = clip.replace(/\?/g,'? ');
    clip = clip.replace(/(\: \.)/g,': ');
    clip = clip.replace(/\&nbsp\;/g,' ');
    clip = clip.replace(/(\s)+/g,' ');
    clip = PORTFOLIO.compressWhiteSpace(clip);
    clip = clip.replace(/\(/g,' ,');
    clip = clip.replace(/\)/g,', ');
return clip;
};

PORTFOLIO.startSynthSpeech = function(){
  extendedplayer=true;
  var clip = '';
  var isSelection=false;
  var clipLength=0;
  if (window.getSelection){
    clip = window.getSelection(); // selection on page
    if (clip=='') {               // possibly selection in some textarea
      var textareas = document.getElementsByTagName("textarea");
      for(var i=0; i < textareas.length; i++) {
    if (clip=='' && textareas[i].value){
          clip = textareas[i].value.substring(textareas[i].selectionStart,textareas[i].selectionEnd);
    }
      }
    }
    if (clip != '') {
      vFact_showplayerpopup(clip);
      return;
    }
    isSelection = (window.getSelection().isCollapsed == false);    
  }
  else if (document.selection) {
    var isSelection = document.selection.createRange().text.length >0;
  }
  if (isSelection) {
    vFact_doplay();
  }
  else if (document.getElementById('element_content')){
     if (document.getElementById('element_content').innerHTML) {
    clip = document.getElementById('element_content').innerHTML;
    clip = PORTFOLIO.prepareHTMLtoSpeech(clip);
//alert(clip);return;
    vFact_showplayerpopup(clip);
     }
    else {
      vFact_playsection('element_content');
    }
  }
  else {
    alert(PORTFOLIO.gettext('Nothing to play'));
  }
};

PORTFOLIO.stopSynthSpeech = function() {
  if (document.getElementById('MyHiddenIFrame')){
    document.getElementById('MyHiddenIFrame').src = ''; 
  }
};

PORTFOLIO.initSynthSpeech = function() {
  if (document.getElementById('pafplayerspeed')){
    var speed = PORTFOLIO.getCookie ('speed');
    if (speed) {
      speed =speed.substring(2,3); // Format: sp1, sp2 or sp3
      document.getElementById('pafplayerspeed').options[speed-1].selected = 'selected';
    }
  }
 if (document.getElementById('pafplayerscmode')) {
    var scmode = PORTFOLIO.getCookie ('scmode');
    if (scmode) {
      scmode=scmode.substring(6,7); // Format: SCMODE1, SCMODE2 or SCMODE3
      document.getElementById('pafplayerscmode').options[scmode-1].selected = 'selected';
    }
  }
};

//var PORTFOLIO.returDIV ='';

PORTFOLIO.helpSuccessHandler = function(xml,divID){
  var root = xml.documentElement;
//  var divID = PORTFOLIO.returDIV;
//  PORTFOLIO.returDIV ='';
  var helpDIV = document.getElementById(divID+'DIV');
  if (helpDIV && root.getElementsByTagName('content')) {
   if (PORTFOLIO.is_ie) {
     if (document.getElementById(divID+'Title') && root.getElementsByTagName('title')){
       document.getElementById(divID+'Title').innerHTML = root.getElementsByTagName('title')[0].text;
     }
     $(helpDIV).children().filter(':last').get(0).innerHTML = root.getElementsByTagName('content')[0].text;
   }
   else {
     if (document.getElementById(divID+'Title') && root.getElementsByTagName('title')){
       document.getElementById(divID+'Title').innerHTML = root.getElementsByTagName('title')[0].textContent;
     }
     $(helpDIV).children().filter(':last').get(0).innerHTML = root.getElementsByTagName('content')[0].textContent;
   }
  var allAnchors=$(helpDIV).children().filter(':last').find("a").get();
  for(i=0;i<allAnchors.length;i++){
    allAnchors[i].title=PORTFOLIO.gettext('Links are disabled in this view');
    $(allAnchors[i]).click(function() { return false; } );
   }
   helpDIV.style.display='block';
   var bleedStop =document.getElementById(divID+'IFRAME');
   if (bleedStop) {
     bleedStop.style.display='block';
     bleedStop.style.width=(helpDIV.offsetWidth)+'px';
     bleedStop.style.height=(helpDIV.offsetHeight)+'px';
   }

  }
};

PORTFOLIO.helpFailureHandler=function(o){
    alert(PORTFOLIO.gettext('Failed: ')+o.status + " " + o.statusText);
};

PORTFOLIO.getAjaxObject = function(sUrl,divID){
// PORTFOLIO.returDIV = divID;
     $.ajax({
        url: sUrl,
        dataType: "xml",
        success:function(o) { 
            return PORTFOLIO.helpSuccessHandler(o,divID); 
        },
        error: PORTFOLIO.helpFailureHandler 
    });
};

PORTFOLIO.PopDocAjax = function(help_uuid,divID) {
var helpDIV = document.getElementById(divID+'DIV');
if (helpDIV && helpDIV.style.display=='block') {
  helpDIV.style.display='none';
  document.getElementById(divID+'IFRAME').style.display='none';
  return;
}
if (help_uuid) {
  PORTFOLIO.getAjaxObject(PORTFOLIO.site_url+'xml/read/'+help_uuid,divID); 
}
else {
  alert(PORTFOLIO.gettext('No help is configured on this topic.'));
}
};


PORTFOLIO.contentSuccessHandler = function(o,myHref){
  var root = o.responseXML.documentElement;
  var el = document.getElementById('element_content');
  if (el && root.getElementsByTagName('content')) {
   if (PORTFOLIO.is_ie) {
     if (root.getElementsByTagName('title')){
       myHTML = '<h1>'+root.getElementsByTagName('title')[0].text+'</h1>';
     }
     myHTML += '<div id="wrapper_object_content">';
     if (root.getElementsByTagName('description')){
       myHTML += '<div class="introduction">'+root.getElementsByTagName('title')[0].text+'</div>';
     }
     myHTML+= root.getElementsByTagName('content')[0].text;
     myHTML+='</div>';
     el.innerHTML = myHTML;
     var history = window.document.location.href.split('#');
     window.document.location.href= history[0]+'#'+myHref;
   }
   else {
     if (root.getElementsByTagName('title')){
       myHTML = '<h1>'+root.getElementsByTagName('title')[0].textContent+'</h1>';
     }
     myHTML += '<div id="wrapper_object_content">';
     if (root.getElementsByTagName('description')){
       myHTML += '<div class="introduction">'+root.getElementsByTagName('title')[0].textContent+'</div>';
     }
     myHTML+= root.getElementsByTagName('content')[0].textContent;
     myHTML+='</div>';
     el.innerHTML = myHTML;
     var history = window.document.location.href.split('#');
     window.document.location.href= history[0]+'#'+myHref;
   }
  }
};

PORTFOLIO.txtSuccessHandler = function(data, href){
  $('#element_content').html('<div id="wrapper_all_content">'+ data +'</div>');
//  window.document.location.href= history[0]+'#'+myHref;
};


PORTFOLIO.getAjaxContent=function(obj){
      var myHref=obj.href;
      myHref=myHref.replace(PORTFOLIO.site_url,PORTFOLIO.site_url+'xml/read/');
     myHref = obj.href.replace(PORTFOLIO.site_url+'?',PORTFOLIO.site_url+'?html_fragment=1;');
    $.ajax({
        url: myHref,
        success: function(o) { 
            return PORTFOLIO.txtSuccessHandler(data, obj.href); 
        }, 
        error: PORTFOLIO.helpFailureHandler 
    });
};

PORTFOLIO.changeAjaxAble = function() {
  var myElement = document.getElementById('element_menu');
  var AjaxAbled = PORTFOLIO.getElementsByClassName('AjaxAble', 'a',myElement);
  for(i=0;i<AjaxAbled.length;i++){
    AjaxAbled[i].title='AjaxAble';
    if ((!document.all) && (document.getElementById)) {
      AjaxAbled[i].setAttribute('onclick','PORTFOLIO.getAjaxContent(this);return false;');
    }
    //workaround for IE
    else if ((document.all) && (document.getElementById)) {
      AjaxAbled[i].onclick = new Function('PORTFOLIO.getAjaxContent(this);return false;');
    }
  }
};

/* jQuery tablesorter - http://tablesorter.com */
PORTFOLIO.initTableSorter = function() {
    if ( $.fn.tablesorter ) {
        $.tablesorter.defaults.widgets = [ 'zebra' ];
        var vars={};
        if ( $.fn.metadata ) {
            vars.textExtraction = function(node) {
                var metadata = $(node).metadata();
                if ( metadata.sortValue !== undefined ) {
                    return metadata.sortValue;
                }
                else {
                    return node.innerHTML;
                }
            };
        }
        $("table.tablesorter").tablesorter(vars);
    }
};

/* Initialize elements with builder CSS class */
PORTFOLIO.initBuilder = function() {
    // Hide all child items (this is here in case CSS rule .builder > * { display:none; } is not present)
    $(".builder").children().hide();

    // Add button after list with click handler
    $(".builder")
        .after('<button class="builder_button" type="button">' + PORTFOLIO.gettext('Show next element') + '</button>')
        .next()
        .click(function() {
            // Show next hidden child
            var children = $(this).prev().children(":hidden");
            children.eq(0).show('slow');
            // Remove button when last element is shown
            if ( ! children.get(1) ) {
                $(this).remove();
            }
        });
};

/* Make headers in object lists clickable */
PORTFOLIO.initClickableObjectHeaders = function() {
    $(".portfolio_object_header").each(function(i) {
        $(this).css('cursor','pointer');
        $(this).click(function(e) {
            if ( e.target === this ) {
                window.location = $(this).find("a.portfolio_object_link").attr('href');
            }
        });
    });
};

/*
 Support functions for hiding/showing various parts of the UI.
 Stores state in a session cookie, so it works across pages.
*/

PORTFOLIO.FLAG = {
    defaults        : {},
    prefix          : 'portfolio_flag_',
    elementPrefix   : 'element_',
    wrapperSelector : '#wrapper_middle_row'
};

PORTFOLIO.FLAG.isSet = function(flag) {
    var value = PORTFOLIO.getCookie(PORTFOLIO.FLAG.prefix + flag + '_' + PORTFOLIO.site_hostname);
    if (value == null) {
        value = PORTFOLIO.FLAG.getDefault(flag);
    }
    return value == "1";
};

PORTFOLIO.FLAG.set = function(flag) {
    PORTFOLIO.setCookie(PORTFOLIO.FLAG.prefix + flag + '_' + PORTFOLIO.site_hostname, "1");
    var el = $('#' + PORTFOLIO.FLAG.prefix + flag).get(0);
    if ( el ) {
        el.checked = true;
    }
    return true;
};

PORTFOLIO.FLAG.unset = function(flag) {
    PORTFOLIO.setCookie(PORTFOLIO.FLAG.prefix + flag + '_' + PORTFOLIO.site_hostname, "0");
    var el = $('#' + PORTFOLIO.FLAG.prefix + flag).get(0);
    if ( el ) {
        el.checked = false;
    }
    return true;
};

PORTFOLIO.FLAG.getDefault = function(flag) {
    if ( typeof PORTFOLIO.FLAG.defaults[flag] === 'string' ) {
        return PORTFOLIO.FLAG.defaults[flag];
    }
    return "1"; // Flag is on by default
};

PORTFOLIO.FLAG.setDefault = function(flag, value) {
    PORTFOLIO.FLAG.defaults[flag] = value ? "1" : "0";
    return true;
};

PORTFOLIO.FLAG.showElement = function(flag, selector) {
    PORTFOLIO.FLAG.set(flag);
    if ( ! selector ) {
        selector = '#' + PORTFOLIO.FLAG.elementPrefix + flag;
    }
    $(selector).show();
    PORTFOLIO.FLAG.wrapperHack( flag, $(selector).width() );
    PORTFOLIO.layout_fix_height(); // Redraw sidebars
    return true;
};

PORTFOLIO.FLAG.hideElement = function(flag, selector) {
    PORTFOLIO.FLAG.unset(flag);
    if ( ! selector ) {
        selector = '#' + PORTFOLIO.FLAG.elementPrefix + flag;
    }
    $(selector).hide();
    PORTFOLIO.FLAG.wrapperHack( flag, 0 );
    PORTFOLIO.layout_fix_height(); // Redraw sidebars
    return true;
};

PORTFOLIO.FLAG.toggleElement = function(flag, selector) {
    if ( PORTFOLIO.FLAG.isSet(flag) ) {
        PORTFOLIO.FLAG.hideElement(flag,selector);
    }
    else {
        PORTFOLIO.FLAG.showElement(flag,selector);
    }
    return true;
};

/* Hack to handle quirky Portfolio layout */
PORTFOLIO.FLAG.wrapperHack = function(flag,width) {
    if ( width === 0 ) {
        if ( flag === 'cell_left' ) {
            $(PORTFOLIO.FLAG.wrapperSelector).addClass("wrapper_middle_row_margin_left_hack");
        }
        if ( flag === 'cell_right' ) {
            $(PORTFOLIO.FLAG.wrapperSelector).addClass("wrapper_middle_row_margin_right_hack");
        }
    }
    else {
        if ( flag === 'cell_left' ) {
            $(PORTFOLIO.FLAG.wrapperSelector).removeClass("wrapper_middle_row_margin_left_hack");
        }
        if ( flag === 'cell_right' ) {
            $(PORTFOLIO.FLAG.wrapperSelector).removeClass("wrapper_middle_row_margin_right_hack");
        }
    }
    return true;
};

/*
* Function to hide Portfolio MOTD element,
* and to signal this unauthorized motd visibility state to Portfolio
* via cookie so it can synchronize to it.
*/
PORTFOLIO.hideMOTD = function() {
    $('#element_motd').css('display','none');
    var options = { path: '/', expires: 7 };
    $.cookie('MOTD_invisible','1',options);
};

/* Initialize audio player on all links with class = 'audio_mpeg' */
PORTFOLIO.init_audio_mpeg = function(root) {

    /* Utility function to convert a link to a <span> node */
    var convert_link = function(el) {
        var span = $('<span style="margin-left: 0.5em;"></span>');
        span.append( $(el).contents() );
        $(el).replaceWith(span);
        return true;
    };

    /* Utility function to create play/pause/stop images */
    var create_img = function(mode) {
        var url = '#';
        if ( mode === 'play' ) {
            url = PORTFOLIO.site_url + 'get_icon/?icon_id=media/play';
        }
        else if ( mode === 'stop' ) {
            url = PORTFOLIO.site_url + 'get_icon/?icon_id=media/stop';
        }
        else if ( mode === 'pause' ) {
            url = PORTFOLIO.site_url + 'get_icon/?icon_id=media/pause';
        }
        return $('<img style="padding:0;margin:0;" src="' + url +'" />');
    };

    /* Utility method to enable/disable form elements */
    var enable  = function(el) { $(el).removeAttr('disabled');      };
    var disable = function(el) { $(el).attr('disabled','disabled'); };

    /* Utility method to disable other sounds on the page playing.
       The id specified is the sound that should NOT be paused
     */
    var pause_other = function(soundID) {
        $.each(soundManager.soundIDs, function(i,id) {
            if ( soundID === id ) {
                return true;
            }
            var sound = soundManager.getSoundById(id);
            if ( sound ) {
                sound.pause();
            }
            return true;
        });
    };

    /* Utility method to create a handler for the given buttons that should be mapped to onplay/onresume */
    var create_play_handler = function(play_button, pause_button, stop_button) {
        return function() {
            disable(play_button);
            enable(pause_button);
            enable(stop_button);
            pause_other(this.sID);
        };
    };

    /* Utility method to create a handler for the given buttons that should be mapped to onpause */
    var create_pause_handler = function(play_button, pause_button, stop_button) {
        return function() {
            enable(play_button);
            disable(pause_button);
            enable(stop_button);
        };
    };

    /* Utility method to create a handler for the given buttons that should be mapped to onstop/onfinish */
    var create_stop_handler = function(play_button, pause_button, stop_button) {
        return function() {
            enable(play_button);
            disable(pause_button);
            disable(stop_button);
        };
    };

    /* Utility method to create a sound object and attach event handlers */
    var create_sound = function(args) {
        if ( ! args ) {
            return null;
        }

        // Create event handlers (or use the one provided)
        var play_handler = args.play_handler
                        ? args.play_handler
                        : create_play_handler(args.play_button, args.pause_button, args.stop_button);
        var pause_handler = args.pause_handler
                         ? args.pause_handler
                         : create_pause_handler(args.play_button, args.pause_button, args.stop_button);
        var stop_handler = args.stop_handler
                        ? args.stop_handler
                        : create_stop_handler(args.play_button, args.pause_button, args.stop_button);

        var autoplay = args.autoplay;

        // Test if any sound is already playing, disable autoplay if any found
        $.each(soundManager.soundIDs, function(i,id) {
            var sound = soundManager.getSoundById(id);
            if ( sound ) {
                if ( sound.playState === 1 ) {
                    autoplay = false;
                    return false; // Stop testing more objects
                }
            }
            return true;
        });

        return soundManager.createSound({
            id: args.url + "#" + args.index,
            url: args.url,
            stream: true,
            volume: 100,
            autoPlay: autoplay,
            onplay: play_handler,
            onresume: play_handler,
            onpause: pause_handler,
            onstop: stop_handler,
            onfinish: stop_handler
        });

    }

    /* Utility method to create the HTML wrapper for the button(s) */
    var create_wrapper = function(type) {
        var css_class = "audio_mpeg";
        if ( type === 'inline' ) {
            return $('<span class="' + css_class + '"></span>');
        }
        if ( type === 'block' ) {
            return $('<div class="' + css_class + '"></div>');
        }
        return null; // FIXME: Throw exception?
    };

    /* Utility method to create media control buttons */
    var create_button = function(type) {
        if ( type === 'play' ) {
            return $('<button type="button" class="play_button" style="padding:0;"></button>');
        }
        if ( type === 'pause' ) {
            return $('<button type="button" class="pause_button" style="padding:0;" disabled="disabled"></button>');
        }
        if ( type === 'stop' ) {
            return $('<button type="button" class="stop_button" style="padding:0;" disabled="disabled"></button>');
        }
        if ( type === 'play_stop' ) {
            return $('<button type="button" class="play_stop_button" style="padding:0;"></button>');
        }
        return null; // FIXME: Throw exception?
    };

    /* Initializer for small players (button, inline) */
    var init_small = function(i, el, sound_url, autoplay) {
        var wrapper = create_wrapper('inline');
        var button = create_button('play_stop');
        var play_img = create_img('play');
        var stop_img = create_img('stop');
        $(button).append(play_img);
        $(wrapper).append(button);
        $(el).replaceWith(wrapper);

        var play_handler = function() {
            $(play_img).remove();
            $(stop_img).remove();
            $(button).append(stop_img);
            pause_other(this.sID);
        };
        var stop_handler = function() {
            $(play_img).remove();
            $(stop_img).remove();
            $(button).append(play_img);
        };

        var sound = create_sound({
            index: i,
            url: sound_url,
            autoplay: autoplay,
            play_handler: play_handler,
            pause_handler: stop_handler,
            stop_handler: stop_handler
        });

        $(button).click(function(event) {
                event.preventDefault();
                if ( $(':first',button).get(0) === play_img.get(0) ) {
                    sound.stop(); // If sound was paused, reset to beginning, see #1826157
                    sound.play();
                }
                else {
                    sound.stop();
                }
        });

        $(wrapper).show();
        return true;
    };

    /* Initializer for normal players (single line, block) */
    var init_normal = function(i, el, sound_url, autoplay) {
        var wrapper = create_wrapper('block');
        var play_button = create_button('play');
        var pause_button = create_button('pause');
        var stop_button = create_button('stop');
        var play_img = create_img('play');
        var pause_img = create_img('pause');
        var stop_img = create_img('stop');

        $(play_button).append(play_img);
        $(pause_button).append(pause_img);
        $(stop_button).append(stop_img);
        $(el).before(wrapper);
        $(wrapper).append(play_button);
        $(wrapper).append(pause_button);
        $(wrapper).append(stop_button);
        $(wrapper).append(el);

        convert_link(el);

        var sound = create_sound({
            index: i,
            url: sound_url,
            autoplay: autoplay,
            play_button: play_button,
            pause_button: pause_button,
            stop_button: stop_button
        });

        $(play_button).click(function(event) {
                event.preventDefault();
                sound.play();
        });
        $(pause_button).click(function(event) {
                event.preventDefault();
                sound.pause();
        });
        $(stop_button).click(function(event) {
                event.preventDefault();
                sound.stop();
        });
        $(wrapper).show();
        return true;
    };

    /* Initializer for large players (multiline, block) */
    var init_large = function(i, el, sound_url, autoplay) {
        var wrapper = create_wrapper('block');
        var play_button = create_button('play');
        var pause_button = create_button('pause');
        var stop_button = create_button('stop');
        var play_img = create_img('play');
        var pause_img = create_img('pause');
        var stop_img = create_img('stop');

        $(play_button).append(play_img);
        $(pause_button).append(pause_img);
        $(stop_button).append(stop_img);
        $(el).before(wrapper);
        $(wrapper).append(play_button);
        $(wrapper).append(pause_button);
        $(wrapper).append(stop_button);
        $(wrapper).append(el);

        convert_link(el);

        var sound = create_sound({
            index: i,
            url: sound_url,
            autoplay: autoplay,
            play_button: play_button,
            pause_button: pause_button,
            stop_button: stop_button
        });

        $(play_button).click(function(event) {
                event.preventDefault();
                sound.play();
        });
        $(pause_button).click(function(event) {
                event.preventDefault();
                sound.pause();
        });
        $(stop_button).click(function(event) {
                event.preventDefault();
                sound.stop();
        });
        $(wrapper).show();
        return true;
    };

    /* Only load if SM2 is ready and supported */
    return soundManager.onready(function(status) {

        if ( ! status.success ) {
            return false;
        }

        /* Apply correct initializer to each link inside the root element */
        $('a.audio_mpeg', root).each(function(i, el) {
            var sound_url = $(el).attr('href');
            var autoplay = $(el).hasClass('autoplay') ? true : false;
            if ( $(el).hasClass('small_audio_player') ) {
                init_small(i, el, sound_url, autoplay);
            }
            if ( $(el).hasClass('normal_audio_player') ) {
                init_normal(i, el, sound_url, autoplay);
            }
            if ( $(el).hasClass('large_audio_player') ) {
                init_large(i, el, sound_url, autoplay);
            }
        });

        return true;
    });
};

/* Initialize contract/expand behaviour on all definition lists with class="object_license" */
PORTFOLIO.init_object_license = function() {
    $('dl.object_license dd').each(function(i,el) {
        var $el = $(el);

        // Set width of dl to width of first element in dt.
        // FIXME: Disabled because the default scenetreff layout breaks the
        // width calculation
        // var containedElementWidth = $el.prev('dt').children().eq(0).width();
        // $el.parent().width( containedElementWidth );

        var contract = function() {
            $el.height( $el.css('lineHeight') );
            $el.css('overflow', 'hidden');
        };

        var expand = function(e) {
            $el.height('auto');
            $el.css('overflow','auto');
        };

        // Bind contract/expand events to hover event
        $el.hover(expand,contract);

        // Set initial state to contracted
        contract();

        // Show element
        $el.css('display', 'block');

        return true;
    });
};

// parse url http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
PORTFOLIO.parse_url = function(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function() {
            var ret = {},
                seg = a.search.replace(/^\?/,'').split(';'),
                len = seg.length,
                i = 0,
                s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
};

/* Ensures all anchors with destructive behaviour must be confirmed */
PORTFOLIO.init_confirm_delete = function() {
	$('a.confirm_delete').live('click', function() {
        if ( confirm( PORTFOLIO.gettext("Do you really want to delete?") ) ) {
            return true;
        }
        else {
            return false;
        }
    });
    return true;
};
