// ===========
// = Globals =
// ===========
var search_results = new Search();

// ==================
// = Document Ready =
// ==================
$(function(){
  // ============
  // = Per Page =
  // ============
  $('select#per_page').change(function(){
    search_results.current_page = 1;
    search_results.per_page = parseInt($(this).val());
    search_results.search();
  });
  
  // ==============
  // = Pagination =
  // ==============
  $('.next_page').click(function(){search_results.get_next_page();});
  $('.previous_page').click(function(){search_results.get_previous_page();});
  
  // ===========
  // = Sorting =
  // ===========
  $('#search_results th.sortable').click(function(){
    if($(this).hasClass('sorting_asc')){
      $(this).removeClass('sorting_asc');
      $(this).addClass('sorting_desc');
      search_results.order = $(this).attr('rel') + " DESC";
    }else{
      $('#search_results th').removeClass('sorting_asc').removeClass('sorting_desc');
      $(this).addClass('sorting_asc');
      search_results.order = $(this).attr('rel') + " ASC";
    }
    search_results.search();
  });
});

// ==========
// = Models =
// ==========
function Search(xml){
  // ==============
  // = Attributes =
  // ==============
  this.xml = xml;
  this.current_page = 1;
  this.per_page = 10;
  this.order = "Wsongs.songtitle ASC";
  this.features = {};
  
  // ================
  // = Associations =
  // ================
  this.songs = new Array();
  $(xml).find('song').each(function(){
    this.songs.push(new Song($(this)));
  });
  
  // ====================
  // = Instance Methods =
  // ====================
  this.toggle_back_to_results = function(){
    if(no_search_params()){}else{toggle_siblings($("#search_reset .back_to_results"));}
  }
  
  this.song_count = function(){return parseInt($(this.xml).find('count:first').text())};
  this.total_songs = function(){return this.song_count()};
 
  this.page_count = function(){
    return Math.ceil(this.song_count()/this.per_page);
  }
  this.total_pages = function(){
    return this.page_count();
  }
  
  this.previous_page = function(){
    if(this.current_page <= 1){
      return null
    }else{
      return this.current_page - 1;
    }
  };
  this.next_page = function(){
    if(this.current_page >= this.total_pages()){
      return null
    }else{
      return this.current_page + 1;
    }
  };
  
  this.startingRow = function(){return (this.current_page - 1) * this.per_page;}
  
  this.url_options = function(){
    return {
      order:this.order,
      totalrows:this.per_page, 
      startingRow:this.startingRow(), 
      userID:get_user_id(), 
      len:3, 
      UserLabel:'guest'//,
      // songsAndInstrumentals:$('input[name=songs_and_instrumentals]:checked').val()
    };
  }
  
  this.build_features = function(options){
    var options = options || {};
    
    this.features = {};
    
    $.each(options, function(k,v){
      this.features[k] = v;
    });

    var array = new Array;

    // keywords
    $.each(keywords, function(k, v){
      if(v['value']){array.push(k + ':' + v['value'])}
    });

    // features
    $.each(features, function(k, v){
      array.push(v);
    });

    // build querystring
    for(i = 0; i < array.length; i = i + 1){
      this.features['f' + i] = array[i];
    }
    this.features['songsAndInstrumentals'] = $('input[name=songs_and_instrumentals]:checked').val();
    
  }
  
  this.search_url = function(options){    
    var options = options || {};
    var url_options = this.url_options();
    
    $.each(this.features, function(k,v){
      url_options[k] = v;
    });
    
    var new_url = $.param.querystring(this.uri, url_options);
    return new_url;
    
  };
  
  this.search_cd = function(cd){
    if(!cd && current_song){var cd = current_song.cdnum};
    if(cd){
      this.search_individual("cd:" + cd, {order:"Wsongs.trknum"});
    }else{
      alert('Please select a cd.');
    };
  }
  
  this.search_individual = function(feature, options){
    var options = options || {};
    var uri = options['uri'] || sendback_url;
    var order = options.order || "Wsongs.songtitle";
    
    this.toggle_back_to_results();
    this.features = {f0:feature}
    this.new_search(uri, {order:order});
  }
  
  this.main_search = function(){
    if(no_search_params()){
      table_reset();
      return false;
    }
    
    toggle_siblings($("#search_reset .reset"));
    this.build_features();
    this.new_search();
  }
  
  this.new_search = function(uri, options){
    var options = options || {};
    var default_order = options['default_order'] == null ? true : options['default_order'];
    
    this.order = options.order || "Wsongs.songtitle";
    this.current_page = 1;
    this.uri = uri || sendback_url;
    
    $('#search_results th').removeClass('sorting_asc').removeClass('sorting_desc');
    // if(default_order){
    //   $('#search_results th:first').addClass('sorting_asc');
    //   search_results.order = $('#search_results th:first').attr('rel') + " ASC";
    // }
    
    this.search();
  }
  
  this.search = function(url){    
    var me = this;


    var url = url || this.search_url();

    if($.mask){$.mask.close();}
    var search_results = $('#center .search_results:first');
    if(search_results.css('display') == 'none'){toggle_siblings(search_results)};
    $('#search_status').text('Loading...');
    var results_array = new Array();
    $.ajax({
      url: url, 
      type: 'GET',
      beforeSend: function(){loading_cursor('show')},
      success: function(xml){
        loading_table();
        me.xml = xml;
        $('#current_page').html(me.current_page);
        $('#total_pages').html(me.total_pages());
        $('#total_songs').html(me.total_songs());
        
        songs_xml = xml;
        set_results_table();
      },
      error: function(response, status, error){alert(status + ": " + error);},
      complete: function(){
        $('#search_status').text('Done.');
        loading_cursor('hide');
      }
    });
    return songs_xml;
  }
  
  this.get_next_page = function(){
    if(this.next_page()){
      this.current_page = this.next_page();
      this.search();
    }
  }
  
  this.get_previous_page = function(){
    if(this.previous_page()){
      this.current_page = this.previous_page();
      this.search();
    }
  }
  
  // =======================
  // = Keyboard Navigation =
  // =======================
  this.navigate = function(item, action){
    if(current_song){
      var col_song = $('#search_results .col_song[rel=' + current_song.id + ']:first');
      if(col_song.length > 0){
        if(item == 'next'){
          var tr = col_song.parents('tr:first').next();
          if(tr.length == 0){tr = false}
        }else if(item == 'previous'){
          var tr = col_song.parents('tr:first').prev();
          if(tr.length == 0){tr = false}
        }
      }else{
        var tr = $('#search_results tbody tr:first');
      }
    }else{
      var tr = $('#search_results tbody tr:first');
    }
    if(tr){
      switch(action){
        case 'view': activate_search_result(tr); break;
        case 'play': play_search_result(tr); break;
      }
    }
  }  
}