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

  /**
   * Creates the initial list of vocabs
   * called on page ready from $(document).ready(function())
   */
  listVocabs : function(data) {
    if (data && data[VAR_ERRORS]) {
      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];
          var voc_unique_identifier = vocab[VAR_UNIQUE_ID];
        
          // 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] && vocab[VAR_STATUS].toLowerCase()=='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+' ' + voc_unique_identifier + '" style="direction:' + vocab[VAR_DISPLAY_NAME_DIR] + ';">';
          
          if(vocab[VAR_DISPLAY_NAME_DIR] == 'LTR')
          {
        	  text += img;
          }
          
          text += '<span class="'+span_class+'" title="'+voc_name+'" onclick="Util.viewVocab(this.parentNode,\''+url+'\')">'+voc_name+'</span>';
          
          if(vocab[VAR_DISPLAY_NAME_DIR] == 'RTL')
          {
        	  text += img;
          }
          
          text +='<ul class="treelist"></ul></li>';
 
          $(text).appendTo('#tree');
        }
        $('</ul>').appendTo(VAR_TREE_ELEMENT);
      }
    }
    Util.hideLoading();
    
	/* CALL VOCAB FILTER */    
    Browse.filterVocabs(query_string);
  },


  /**
   * 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 && data[VAR_ERRORS]) {
            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");

                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] && term[VAR_STATUS].toLowerCase()=='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+'" style="direction:' + term[VAR_DISPLAY_NAME_DIR] + ';">';
                
                
                if(term[VAR_DISPLAY_NAME_DIR] == 'LTR')
                {
                	var img_and_mnemonic = img+' alt="Tree icon" title="Tree icon" />';
                    img_and_mnemonic += '<span class="rel '+rel_type[VAR_CODE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                        
              	  	text += img_and_mnemonic;
                }
                else
                {
              	  text += '<ul class="treelist">';
                }
                    
                text += '<span class="'+span_class+'" title="'+term_title+'" onclick="Util.viewTerm(this.parentNode,\''+url+'\')">';
                text += term_name+'</span>';
                
                if(term[VAR_DISPLAY_NAME_DIR] == 'RTL')
                {
                	var img_and_mnemonic = '<span class="rel '+rel_type[VAR_REL_BASE_TYPE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                    img_and_mnemonic += img+' alt="Tree icon" title="Tree icon" />';
                    
              	  	text += img_and_mnemonic;
                }
                else
                {
              	  text += '<ul class="treelist">';
                }
                
                text+='</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 && data[VAR_ERRORS]) {
            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");
       
                  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] && rel[VAR_STATUS].toLowerCase()=='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+'" style="direction:' + term[VAR_DISPLAY_NAME_DIR] + ';">';
                  
                  if(term[VAR_DISPLAY_NAME_DIR] == 'LTR')
                  {
                	  var img_and_mnemonic = img+' alt="Tree icon" title="Tree icon" />';
                      img_and_mnemonic += '<span class="rel '+rel_type[VAR_REL_BASE_TYPE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                      
                	  text += img_and_mnemonic;
                  }
                  else
                  {
                	  text += '<ul class="treelist">';
                  }
                  
                  text += '<span class="'+span_class+'" title="'+term_title+'" onclick="Util.viewTerm(this.parentNode,\''+url+'\')">'
                  text += rel_name+'</span>';
                  
                  if(term[VAR_DISPLAY_NAME_DIR] == 'RTL')
                  {
                	  
                      var img_and_mnemonic = '<span class="rel '+rel_type[VAR_REL_BASE_TYPE]+'" title="'+rel_type[VAR_NAME]+'">'+rel_type[VAR_MNEMONIC]+'</span>';
                      img_and_mnemonic += img+' alt="Tree icon" title="Tree icon" />';
                      
                	  text += img_and_mnemonic;
                  }
                  else
                  {
                	  text += '<ul class="treelist">';
                  }
                  
                  text += '</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));
      }
    }
  },
  
  filterVocabs : function(query_string)
  {
		$.ajax({	
					type: VAR_HTTP_METHOD,
					url:  VAR_URL_LIST_FILTERS + query_string,
					dataType: 'json',
					global: false,
					success: Browse.updateAndApplyFilters
				});  
  },
  
  updateAndApplyFilters : function(data) 
  {
	  //clear existing filters
	  $('#vocab_filter dl').remove();
	  
	  if (data && data[VAR_ERRORS]) 
	  {
	      Util.displayError(data);
	      //if we have errors show all vocabs
	      
		  	//reset query string
		  	query_string = 'uniqueIdentifier=*';
		  	//re-execute query
		  	Browse.filterVocabs(query_string);	
	  }
	  
	  var filters = data['filters'];
	 	  
	  $('#vocab_filter').append('<dl></dl>');
 
	  if(filters)
	  {		  
		  for(var j = 0; j < filters.length; j++ )
		  {
			  if(filters[j] != 'uniqueIdentifier')
			  {
				  $('#vocab_filter dl').append('<dt class="' + filters[j] + '"><b>'+ data[filters[j]]['localisedName'] +'</b><dt>');
				  
				  var children = data[filters[j]]['children'];
				  
				  for(var i = 0; i < children.length; i++ )
				  {
					  var child_name = children[i]['localisedName'];
					  
					  if(child_name && child_name.length > 23)
					  {
						  child_name = child_name.substring(0,22) + "...";
					  }
					  
					  $('#vocab_filter dl').append('<dd><a href="#" rel="' + filters[j] + '=' + children[i]['name'] + '" title="' + children[i]['localisedName'] + '"><span>' + child_name + '</span></a><span class="counter">(' + children[i]['results'] + ')</span></dd>');
				  }
			  }
		  }
	  }
	  
	  //Hide all vocabs not in the filter results
	  $('li.vocab').each(	function()
							{
								var a = $(this).attr('class');
							
								var toggleIcon = $(this).children('img');
								
								$(this).removeClass('last');
								
								if(toggleIcon.attr('src').indexOf("plus") == -1)
								{
									toggleIcon.attr('src', 'images/tree/mid-minus.gif');
								}
								else
								{
									toggleIcon.attr('src', 'images/tree/mid-plus.gif');
								}
								
								if(query_string && query_string != 'uniqueIdentifier=*')
								{
									$(this).hide();
									
									for(x in data['uniqueIdentifier'])
									{
										if(a.indexOf(data['uniqueIdentifier'][x]) > 0)
										{
											$(this).show();
										}
									}
								}
								else
								{
									$(this).show();
								}
							});
	  
	  var firstVisible = $('li.vocab:visible').first().children('img');
	  var lastVisible =  $('li.vocab:visible').last().children('img');
	  
	  if(firstVisible.attr('src'))
	  {
		  if(firstVisible.attr('src').indexOf("plus") == -1)
		  {
			  firstVisible.attr('src', 'images/tree/top-minus.gif');
		  }
		  else
		  {
			  firstVisible.attr('src', 'images/tree/top-plus.gif');
		  }
	  }
	  
	  if(lastVisible.attr('src'))
	  {
		  if(lastVisible.attr('src').indexOf("plus") == -1)
		  {
			  lastVisible.attr('src', 'images/tree/bottom-minus.gif');
		  }
		  else
		  {
			  lastVisible.attr('src', 'images/tree/bottom-plus.gif');
		  }
	  }
	  
	  $('li.vocab:visible').last().addClass('last');

	  if($('li.vocab:visible').length == 0)
	  {
		  //display alert - no vocabs found from filter
		  
		  if($('#tree_cont p').size() <= 1)
		  {
			  $('#tree_cont p').show(); 
			  expandFilter();
		  }
	  }
	  else
	  {
		  $('#tree_cont p').hide(); 
	  }
	  
	  //handle click events on filters
	  $('#vocab_filter a').not('#reset').click(	function(evt)
												{
		  											//clear error message when new filter applied
		  											$('#errors').remove();
		  											
							  						var query_param = $(this).attr('rel');
							  							
							  						if(query_string.indexOf(query_param) > 0)
							  						{
							  							query_string = query_string.replace('&' + query_param, '');
							  						}
							  						else
							  						{
								  						query_string += '&' + query_param;
							  						}
							  						
													Browse.filterVocabs(query_string);
													evt.preventDefault();	
												});
	  
	  //set selected if in browser query string
	  $('#vocab_filter a').each(function()
				  				{
			  						var query_param = $(this).attr('rel');
				
									if(query_string.indexOf(query_param) > 0)
									{
										expandFilter();
										$(this).toggleClass('selected');							
										$(this).next('.counter').toggle();
									}
				  				});
	  
	  $('#vocab_filter dt').click(	function()
			  						{
		  								var id = $(this).attr(id);
		  								$(this).next().nextUntil('dt').toggle();
		  								$(this).toggleClass('selected');
			  						});
	  
  },


  /**
   * 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;
  }
  */

  $('.box-resize-inner').resize(function() {
	  $('#midcontent').css('minHeight',$('.box-resize-inner').height() - 20);
	});

  $('#midcontent').css('minHeight',$('.box-resize-inner').height() - 20);
  
  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'}); 

  
  /* initialise query string */
  var url = $(location).attr('href');
    
  query_string = 'uniqueIdentifier=*';
	  
  if(url.indexOf('?') > 0)
  {
	  query_string += "&" + url.substring(url.indexOf('?')+1, url.length);
	  
	  /* Set up filter box */
	  $('.filterToggle').toggle(collapseFilter, expandFilter).fadeIn(1000);	
  }
  else
  {
	  /* Set up filter box */
	  $('.filterToggle').toggle(expandFilter, collapseFilter).fadeIn(1000);	
  }
  
  /* LIST VOCABS */
  $.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
  });
 
  /* Bind click event to reset filter link */
  $('#reset').click(function(evt)
					{
						query_string = 'uniqueIdentifier=*';
						Browse.filterVocabs(query_string);
						evt.preventDefault();
					});
});

function expandFilter()
{
	 $('#vocab_filter').show(1000);
	 
	 $('#tree_cont').animate(
	 { 
		 marginLeft : '220px'
	 } , 1000);
	 
	 $('.filterToggle').attr('src', 'images/arrow-left.gif');
}

function collapseFilter()
{
	 $('#vocab_filter').hide(1000);
	 
	 $('#tree_cont').animate(
	 { 
		 marginLeft : '0px' 
	 } , 1000);
	 
	 $('.filterToggle').attr('src', 'images/arrow-right.gif');
}

/**
 * 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'));
});

