/****************************
 *      search object       *
 ***************************/

/**
 * Object to hold voc id and name within an authority (to avoid huge nesting of arrays)
 */ 
function VocArray(vocs) {
  this.length = 0;
  this.arr    = new Object();

  for (var m in vocs) {
    this.length++;
    this.arr[m]=vocs[m];
  } 
}


/**
 * Search page functionality object
 */ 
var Search = new Object({
  // object to remember previous radio button selected (to keep or reset auth & voc drop down selections)
  prev_input : 'all',

  // object to remember last selected term type
  prev_tt : new Array('all'),

  // object to remember last selected field
  prev_field : new Array('all'),


  // list of the vocabs in various auths (and also list of all vocs in system under 'all')
  auth_vocs : new Object(),

  /**
   * Adds the list of vocs to the Search objects auth_vocs object.
   * These lists of vocs are used to populate the vocab drop down when a user switches their selection of authority
   */
  populateVoc : function(auth, vocs) {
    this.auth_vocs[auth] = vocs;

    if (this.auth_vocs['all']==null) { 
      this.auth_vocs['all']    = [];
      this.auth_vocs['all'][0] = vocs; 
    } else {
      this.auth_vocs['all'][this.auth_vocs['all'].length] = vocs;
    }
  },


  /**
   * Switches the contents of the term vocab dropdown box to contain the vocabs in the newly selected vocab
   */
  switchVocs : function() {
    // dont switch if 'search by' radio is 'all'
    if ($('#vocabularyRadio').attr('checked')!=true) {
      var auth = $('#auth').val();
      // if list auth contains vocs
      if (this.auth_vocs[auth]!=null && this.auth_vocs[auth].length > 0) {
        // add 'all' and separator options to drop down
        $('#termVocId').html('<option value="all">'+VAR_LANG_ALL+'</option>');
        $('#termVocId').append('<option disabled="disabled">---</option>');

        // add all vocs to the select
        if (auth=='all') {
          for (var i=0; i<this.auth_vocs['all'].length; i++) {
            var voc = this.auth_vocs['all'][i].arr;
            for (var id in voc) {
              $('#termVocId').append('<option value="'+id+'">'+voc[id]+'</option>');
            }
          }

       // or add auth specific vocs to select
       } else {
          var arr = this.auth_vocs[auth].arr;
          for (var id in arr) {
            $('#termVocId').append('<option value="'+id+'">'+arr[id]+'</option>');
          }
        } 
        // enable the select
        $('#termVocId').removeAttr('disabled');

      // otherwise disable the select and inform user that the auth contains no vocs
      } else {
        $('#termVocId').attr('disabled', 'disabled');
        $('#termVocId').html('<option value="">'+VAR_LANG_NOVOC+'</option>');
      }
    }
  },


  /**
   * Sets the page hidden input and submits the form.
   */
  gotoPage : function(page) {
    $('#currentPage').val(page);
    $('#searchBtn').click();
  },

 
  /**
   * Enables or disables parts of the form depending on what the user wants to searhc against, terms, vocs or both
   */
  changeInputs : function(type) {
    this.enableFormInput('searchtext');
    var enable = false;

    if (type=='term' && $('#searchTerms').attr('checked')==true) {
      enable = true;
    } else if (type=='voc' && $('#searchVocs').attr('checked')==true) {
      enable = true;
    }
 
    if (type=='term') {
      if (enable) {
        if ($('#termVocId option:selected').val()!='') {
          this.enableFormInput('termVocId');
        }
        this.enableFormInput('searchTermTypes');
      } else {
        this.disableFormInput('termVocId');
        this.disableFormInput('searchTermTypes');
      }
      if (this.prev_input=='voc') $('#auth').change();
    }

    this.prev_input = type;
  },


  /**
   * Enable the forum element with given id and set its border colour to blue.
   */
  enableFormInput : function(id) {
    $('#'+id).removeAttr('disabled');
    $('#'+id).addClass('bordered');
  },


  /**
   * Disable the form element with given id and remove its blue coloured border (reset to grey)
   */
  disableFormInput : function(id) {
    $('#'+id).attr('disabled', 'disabled');
    $('#'+id).removeClass('bordered');
  },


  /** 
   * Bind an event to the term type selection box options.
   * Ensure that a valid selection of term types is made... either 'all' or any combination of the other choices.
   */
  termTypeOptionEvent : function(evt) {
    var sel = $('#searchTermTypes option:selected');

    if (sel.length>1) {
      var curr_opts = $('#searchTermTypes').val()+"";
     curr_opts = curr_opts.split('\,');
      var curr_opt = '';
      for (var i=0;i<curr_opts.length;i++) {
        if (Util.arrayContains(this.prev_tt, curr_opts[i])==false) {
          curr_opt = curr_opts[i];
        }
      }
      this.prev_tt = curr_opts;

      if (sel.val().substring(0,4)=='all') {
        sel.each(function() {
          if (this.selected==true) {
            if (this.value!='all' && curr_opt=='all') {
              this.selected=false;

            } else if (this.value=='all' && curr_opt!='all') {
              this.selected=false;
            }
          }
        });
      }
    } else {
      this.prev_tt = new Array(sel.val());
    }
  },
 

  /** 
   * Bind an event to the term type selection box options.
   * Ensure that a valid selection of term types is made... either 'all' or any combination of the other choices.
   */
  fieldOptionEvent : function(evt) {
    var sel = $('#searchIn option:selected');

    if (sel.length>1) {
      var curr_opts = $('#searchIn').val()+"";
      curr_opts = curr_opts.split('\,');
      var curr_opt = ''; 
      for (var i=0;i<curr_opts.length;i++) {
        if (Util.arrayContains(this.prev_field, curr_opts[i])==false) {
          curr_opt = curr_opts[i];
        }
      }   
      this.prev_field = curr_opts;

      if (sel.val().substring(0,4)=='all') {
        sel.each(function() {
          if (this.selected==true) {
            if (this.value!='all' && curr_opt=='all') {
              this.selected=false;

            } else if (this.value=='all' && curr_opt!='all') {
              this.selected=false;
            }
          }
        });
      }   
    } else {
      this.prev_field = new Array(sel.val());
    }   
  },
 


  showErrorColours : function() {
    if ($('#searchText').val()=='') {
      if ($('#searchTerms').attr('checked')==false && $('#searchVocs').attr('checked')==false) {
        $('label[for="searchTerms"]').addClass('redborder');
        $('label[for="searchVocs"]').addClass('redborder');
      }
      $('#searchText').addClass('redborder');
      $('#auth').addClass('redborder');
      $('#searchTermTypes').addClass('redborder');
      $('#termVocId').addClass('redborder');
          
      this.setError(VAR_FORM_NOVAL);    
    }
  },

  
   setError : function() {
	 var search_box = $('#midcontent form');
	 var search_box_html = $('#midcontent form').html();
     $('#midcontent').html('');
     $('#midcontent').append(search_box);
     $('#midcontent form').html(search_box_html);
     $('#midcontent').append('<p id="infoNotes">'+VAR_FORM_NOVAL+'</p>');
  },


  /** 
   * Bind an event to the form submit to stop the search executing if 'all' search by is chosen and no params have been selected
   * as this would essentially retrieve the whole index and lucene won't allow a null query!
   */
  formSubmitEvent : function() {
    this.clearErrorColours();
    var both_true  = ($('#searchTerms').attr('checked')==true && $('#searchVocs').attr('checked')==true);
    var both_false = ($('#searchTerms').attr('checked')==false && $('#searchVocs').attr('checked')==false);

    if (both_false) {
      this.showErrorColours();
      return false;

    } else if (both_true) {
      // if no auth selected (all = no filter)
      if ($('#auth option:selected').val()=='all') {
        // if no term voc id selected (all = no filter)
        if ($('#termVocId option:selected').val()=="" || $('#termVocId option:selected').val()=='all') {
          // if no term type selected (all = no filter)
          if ($('#searchTermTypes option:selected').val()==null || $('#searchTermTypes option:selected').val()=='all') {
            // if no values in term name/id or voc name/id
            if ($('#searchText').val()=='') {
              this.showErrorColours();
              return false;
            }
          }
        }
      }   
    }

    return true;
  },


  updateToolTip : function(evt) {
    evt.target.title  = evt.target.options[evt.target.selectedIndex].text;
  },


  clearErrorColours : function() {
    // reset border colours if they're red
    $('#auth').removeClass('redborder');
    $('label[for=searchTerms]').removeClass('redborder');
    $('label[for=searchVocs]').removeClass('redborder');
    $('#searchTermTypes').removeClass('redborder');
    $('#termVocId').removeClass('redborder');
    $('#searchText').removeClass('redborder');
    $('#infoNotes').text('');
  },


  toggleFilterTable : function(img) {
    if ($('#tabWrap').css('display')=='none') {
      $('#showFilter').val('true');
    } else {
      $('#showFilter').val('false');
    }
    $('#tabWrap').slideToggle('fast');
    Util.switchImage(img);
  }
});


/**
 * Bind events method called after document is ready.
 */
$(document).ready(function() {
  Util.sizeUpBoxes(['midcontent', 'maincontent']);

  $('form').submit(function() { return Search.formSubmitEvent(); });

  $('#searchTermTypes').change(function(evt) { Search.termTypeOptionEvent(evt); });
  $('#searchIn').change(function(evt) { Search.fieldOptionEvent(evt); });
  $('#auth').change(function(evt) { Search.updateToolTip(evt); });
  $('#termVocId').change(function(evt) { Search.updateToolTip(evt); });

  $('#searchTerms').change(function() { Search.changeInputs('term'); });
  $('#searchVocs').change(function() { Search.changeInputs('voc'); });
  $('#auth').change(function() { Search.switchVocs(); });

  $('form input').change(function() { Search.clearErrorColours(); });
  $('form select').change(function(evt) { Search.clearErrorColours(); });
});

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


