/**
 * Browse Javascript class, contains methods unique to browse screen 
 */
var Browse = new Object({
  node_size      : null,

  /**
   * Creates the initial list of vocabs
   * called on page ready from $(document).ready(function())
   */
  listVocabs : function(data) {
    if (data[VAR_ERRORS]!=null) {
      Util.displayError(data);

    } else {
      var vocabs = data['vocabs'];
      var max = (vocabs.length-1);

      if (max==-1) {
        $('<p>'+data[VAR_NOVOCS_KEY]+'</p>').appendTo(VAR_TREE_ELEMENT);
      } else {
        $('<ul id="tree">').appendTo(VAR_TREE_ELEMENT);

        for (var i=0; i<=max; i++) {
          // gather data about this vocab
          var last     = i==max;
          var vocab    = vocabs[i];
          var voc_id   = data[VAR_LOOKUP_MODE]==VAR_LOOKUP_BY_LONG ? vocab[VAR_HEADER_ID] : vocab[VAR_IDENTIFIER];
          var voc_name = vocab[VAR_DISPLAY_NAME];
          if (voc_name==null) voc_name = VAR_UNNAMED;
          var voc_auth = vocab[VAR_AUTHORITY];
        
          // generate css class 
          var pos       = 'mid';
          var css_class = 'vocab';
          if (i==max && i==0) {
            pos = 'topsingle';
            css_class += ' last';
          } else if (i==0) {
            pos = 'top';
          } else if (i==max) {
            pos = 'bottom';
            css_class += ' last';
          }
   

          var span_class = 'fauxlink';
          if (vocab[VAR_STATUS]=='DEPRECATED') {
            span_class += ' deprecated';
            voc_name+= ' ('+data['readables'][VAR_DEP_KEY]+')';
          }
 
          // build html and append to dom
         
          var url  = '/'+voc_auth+'/'+voc_id.replace(/'/g,"\\'");
          url=url.replace(/#/g,"%23");
          var img = '<img class="cursor" alt="Tree icon" title="Tree icon" src="images/tree/'+pos+'-plus.gif" onmouseover="Util.over(this)" onmouseout="Util.out(this)" onclick="Browse.toggleVocab(this.parentNode,\''+url+'\')" />';
          var text = '<li class="'+css_class+'">'+img+'<span class="'+span_class+'" title="'+voc_name+'" onclick="Util.viewVocab(this.parentNode,\''+url+'\')">'+voc_name+'</span><ul class="treelist"></ul></li>';
 
          $(text).appendTo('#tree');
        }
        $('</ul>').appendTo(VAR_TREE_ELEMENT);
      }
    }
    Util.hideLoading();
  },


  /**
   * Expands a vocab node and appends top terms to list
   * If the terms have not yet been fetched the json list of retrieved and parsed.
   * called when user clicks [+] by a vocab
   */
  toggleVocab : function(node, url) {
    var num_kids = $(node).children('ul.treelist').children('li').length;

    if (num_kids==0) {
      $.ajax({
        type: VAR_HTTP_METHOD,
        url:  VAR_URL_TOP_TERMS.replace('_url_', url)+'?nocache='+Util.getDateString(),
        dataType: 'json',
        global: false,
        beforeSend: Util.showLoading(node),
        success: function(data) {
          if (data[VAR_ERRORS]!=null) {
            Util.displayError(data);

          } else {
            var top_terms_result = data['top_terms'];
            var readables = data['readables'];

            if (node!=null) {
              $(node).children('ul.treelist').hide();
              $(node).children('ul.treelist').html('');

              var terms    = top_terms_result[VAR_THES_RESULTS];
              var max      = terms.length-1;
              var rel_type = data[VAR_REL_TYPE];

              for (var i=0;i<=max;i++) {
                var term      = terms[i];
                var voc_auth  = term[VAR_VOC_AUTH];
                var term_name = term[VAR_DISPLAY_NAME];
                if (term_name==null) term_name = VAR_UNNAMED;
                var voc_id    = data[VAR_LOOKUP_MODE]==VAR_LOOKUP_BY_LONG ? term[VAR_VOC_HEADER_ID] : term[VAR_VOC_IDENTIFIER];
                var term_id   = data[VAR_LOOKUP_MODE]==VAR_LOOKUP_BY_LONG ? term[VAR_HEADER_ID]     : term[VAR_IDENTIFIER];
                var last      = i==max;
  
                // build html and append to dom
                var url = '/'+voc_auth+'/'+voc_id+'/term/'+term_id.replace(/'/g,"\\'");
                url=url.replace(/#/g,"%23");
              //  alert(url);
                var css_class = 'term';
                var img  = '<img src="images/tree/';
                if (!last) { 
                  img += 'mid-'; 
                  css_class += ' tmid';
                } else { 
                  img +='bottom-'; 
                  css_class += ' last'; 
                }

                var term_info = [];

                var span_class = 'fauxlink';
                if (term[VAR_STATUS]=='DEPRECATED') {
                  span_class += ' deprecated';
                  term_info[term_info.length] = readables[VAR_DEP_KEY];
                }

                if (term[VAR_TERM_TYPE]!=null && term[VAR_TERM_TYPE]!='null') {
                  span_class += ' '+term[VAR_TERM_TYPE];
                  //if (term[VAR_TERM_TYPE]=='NL') {
                  //  term_info[term_info.length] = readables[VAR_NL_KEY];
                  //}
                }
                
                if (term[VAR_SRC_VOC_ID]!=null && term[VAR_SRC_VOC_ID]!='null') 
                {
                  //  alert(term_info);
                  span_class += ' othersrc';
                  term_info[term_info.length] = readables[VAR_ORIG_KEY];
                  term_info[term_info.length] = ' ';
                  term_info[term_info.length] = term[VAR_SRC_VOC_ID];
                  //alert(term_info);
                }

                var term_title = term_name;

                if (term_info.length>0) {
                  term_title += ' (';

                  for (var j=0;j<term_info.length;j++) {
                    term_title += term_info[j];
                    //if (j<(term_info.length-1)) term_title+= ', ';
                  }

                  term_title += ')';
                }

                if (term[VAR_IS_LEAF]) {
                  img += 'line.gif"';
                } else {
                  img += 'plus.gif" class="cursor" onmouseover="Util.over(this)" onmouseout="Util.out(this)" onclick="Browse.toggleTerm(this.parentNode,\''+url+'\', \''+term[VAR_PATH]+'\')"';
                }

                var text  = '<li title="'+term_name+'" class="'+css_class+'">'+img+' alt="Tree icon" title="Tree icon" />';
                    text += '<span class="rel '+rel_type[VAR_CODE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                    text += '<span class="'+span_class+'" title="'+term_title+'" onclick="Util.viewTerm(this.parentNode,\''+url+'\')">';
                    text += term_name+'</span><ul class="treelist"></ul></li>';
                $(text).appendTo($(node).children('ul.treelist'));
              }



              // resize and show the new terms
              num_kids = $(node).children('ul.treelist').children('li').length;
              var height = num_kids*Browse.node_size;
              $(node).children('ul.treelist').css('height', 'auto');
              $(node).children('ul.treelist').slideDown('fast', Util.switchAndResize(node,'auto'))
            }
          }
          Util.hideLoading();
        }
      })

    // if previously loaded just toggle the display & tree icone
    } else {
      $(node).children('ul.treelist').slideToggle('fast', Util.switchImage(node));
    }
  },
  

  /**
   * Deals with expanding a term node and appending rels to list
   * If the rels have not yet been fetched the json list of retrieved and parsed.
   * called when user clicks [+] by a term
   */
  toggleTerm : function(node, url, path) {
    var num_kids = $(node).children('ul').children('li').length;

    if (num_kids==0) {
      $.ajax({
        type: VAR_HTTP_METHOD,
        url:  VAR_URL_TERM_RELS.replace('_url_', url)+'?nocache='+Util.getDateString()+'&path='+path,
        dataType: 'json',
        global: false,
        beforeSend: Util.showLoading(node),
        success: function(data) {
          if (data[VAR_ERRORS]!=null) {
            Util.displayError(data);
          } else {
            var thes = data['term'];
  
            if (node!=null) {
              $(node).children('ul').hide();
              $(node).children('ul').html('');

              var term      = thes[VAR_THES_RESULTS][0];
              var voc_id    = data[VAR_LOOKUP_MODE]==VAR_LOOKUP_BY_LONG ? term[VAR_VOC_HEADER_ID] : term[VAR_VOC_IDENTIFIER];
              var voc_auth  = term[VAR_VOC_AUTH];
              var rels      = term[VAR_TERM_RELS];
              var max       = rels.length-1;
              var rel_types = data[VAR_REL_TYPES];
              var readables = data['readables'];
              
              if (max>-1) {
                for (var i=0;i<=max;i++) {
                  var rel      = rels[i];
                  var rel_id   = data[VAR_LOOKUP_MODE]==VAR_LOOKUP_BY_LONG ? rel[VAR_HEADER_ID] : rel[VAR_IDENTIFIER];
                  var rel_name = rel[VAR_DISPLAY_NAME];
                  if (rel_name==null) rel_name = VAR_UNNAMED;
                  var last     = i==max;
                  var rel_type = rel_types[rel[VAR_RELCODE]];

                  // if NT and has sort key should append this to the name
                  if (rel[VAR_RELCODE]=='NT' && rel[VAR_TERM_SORT_KEY]!=null && isNaN(parseInt(rel[VAR_TERM_SORT_KEY]))==false) {
                    rel_name = rel[VAR_TERM_SORT_KEY]+'. '+rel_name;
                  }

                  // build html and append to dom
                  //var url = '/'+voc_auth+'/'+voc_id.replace(/['/']+/g,'%2f')+'/'+rel_id.replace(/['/']+/g,'%2f');
                  var url = '/'+voc_auth+'/'+voc_id+'/term/'+rel_id.replace(/'/g,"\\'");
                  url=url.replace(/#/g,"%23");
                  //alert(url);
                  var img  = '<img src="images/tree/';
                  var css_class = 'term';
                  if (!last) { 
                    img += 'mid-'; 
                    css_class += ' tmid';
                  } else { 
                    img +='bottom-'; 
                    css_class += ' last'; 
                  }
                  var span_class = 'fauxlink';
                  var term_info = [];
              
                  if (rel[VAR_STATUS]=='DEPRECATED') {
                    span_class += ' deprecated';
                    term_info[term_info.length] = readables[VAR_DEP_KEY];
                  }

                  if (rel[VAR_TERM_TYPE]!=null && rel[VAR_TERM_TYPE]!='null') 
                  {
                    span_class += ' '+rel[VAR_TERM_TYPE];
                    //if(rel[VAR_TERM_TYPE]=='NL')
                    //{
                    //    term_info[term_info.length] = readables[VAR_NL_KEY];
                    //}
                  }

                  var src_rel_id = rel[VAR_SRC_VOC_ID];
                  if (src_rel_id==null || src_rel_id=='null') src_rel_id=rel[VAR_SRC_VOCAB];

                  if (src_rel_id) 
                  {
                    span_class += ' othersrc';
                    //term_info[term_info.length] = readables[VAR_ORIG_KEY]+" "+rel[VAR_SRC_VOC_ID];
                     term_info[term_info.length] = readables[VAR_ORIG_KEY];
                    term_info[term_info.length] = ' ';
                    term_info[term_info.length] = src_rel_id;
                  }

                  var term_title = rel_name;

                  if (term_info.length>0) {
                    term_title += ' (';

                    for (var j=0;j<term_info.length;j++) {
                      term_title += term_info[j];
                      //if (j<(term_info.length-1)) term_title+= ', ';
                    }

                    term_title += ')';
                  }


                  if (rel[VAR_IS_LEAF]) {
                    img += 'line.gif"';
                  } else {
                    img += 'plus.gif" class="cursor" onmouseover="Util.over(this)" onmouseout="Util.out(this)" onclick="Browse.toggleTerm(this.parentNode,\''+url+'\', \''+term[VAR_PATH]+'\')"';
                  }

                  var text  = '<li title="'+rel_name+'" class="'+css_class+'">'+img+' alt="Tree icon" title="Tree icon" />';
                      text += '<span class="rel '+rel_type[VAR_REL_BASE_TYPE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                      text += '<span class="'+span_class+'" title="'+term_title+'" onclick="Util.viewTerm(this.parentNode,\''+url+'\')">'
                      text += rel_name+'</span><ul class="treelist"></ul></li>';
                  $(text).appendTo($(node).children('ul'));
                }

                // resize and show the new terms
                num_kids = $(node).children('ul.treelist').children('li').length;
                var height = num_kids*Browse.node_size;
                $(node).children('ul.treelist').css('height', 'auto');
                $(node).children('ul.treelist').slideDown('fast', Util.switchAndResize(node,'auto'))
                Browse.cascadeHeight($(node).parent('ul.treelist').parent('li'), 'auto');
              } else {
                Util.removeImage(node);
              }
            }
          }
          Util.hideLoading();
        }
      })
    } else {
      // if currently hidden, show it and reset height to 'auto'
      if ($(node).children('ul.treelist').css('display')=='none') {
        $(node).css('height', 'auto');
        $(node).children('ul.treelist').slideDown('fast', Util.switchImage(node));
        Browse.cascadeHeight($(node).parent('ul.treelist').parent('li'), 'auto');

      // if currently shown, hide
      } else {
        $(node).children('ul.treelist').slideUp('fast', Util.switchImage(node));
      }
    }
  },


  /**
   * Cascades the height of the child element to each of its ancestors.
   * @param node the current node to work on
   * @param child_height previously calculated total height of the nodes children to use when navigating *up* the tree
   *        This parameter can be an int or a recognised css keyword (eg, 'auto')
   */
  cascadeHeight : function(node, child_height) {
    var new_height = null;

    if (isNaN(parseInt(child_height))==false) {
      var num_kids    = $(node).children('ul.treelist').children('li').length;
      var kid_height  = num_kids*Browse.node_size;
      var curr_height = Util.pxVal($(node).children('ul.treelist').css('height'));
      if (curr_height>kid_height) kid_height = curr_height;

      new_height  = parseInt(kid_height)+parseInt(child_height);
      $(node).children('ul.treelist').css('height', new_height+'px');
    } else {
      new_height = child_height;
      $(node).children('ul.treelist').css('height', child_height);
    }

    if ($(node).parent('ul.treelist').length>0 && $(node).parent('ul.treelist').parent('li').length>0) {
      Browse.cascadeHeight($(node).parent('ul.treelist').parent('li'), new_height);
    }
  }
});


/**
 * Binds the following events to document ready status:
 *
 * - Resizes the tree & info pages to the viewport size.
 * - List the vocabs and append to dom as top level nodes starts up the app and loads the vocab list
 */
$(document).ready(function(){
  Util.sizeUpBoxes(['midcontent', 'maincontent']);

  // initialise tree node size
  Browse.node_size = 21;
  var browser_name = navigator.appName.toLowerCase();
  /*
  if (browser_name.indexOf('internet explorer')>-1 || browser_name.indexOf('msie')>-1) {
    Browse.node_size = Browse.node_size-5;
  }
  */

  var nspx = Browse.node_size+'px';
  $('li img').css('height', nspx);
  $('li span').css({'max-height' : nspx, 'height' : nspx, 'line-height': (Browse.node_size-1)+'px'}); 

  $.ajax({
    type: VAR_HTTP_METHOD,
    url:  VAR_URL_LIST_VOCABS+'?nocache='+Util.getDateString(),
    dataType: 'json',
    global: false,
    beforeSend: Util.showLoading('voc_list'),
    success: Browse.listVocabs
  });
});

/**
 * Binds the following events to the document window status:
 *
 * - Resizes the tree & info pages to the viewport size.
 */
$(window).resize(function(){
  Util.sizeUpBoxes(new Array('midcontent', 'maincontent'));
});
