if(typeof console === "undefined") {
  console = { log: function() { } };
}

var videos_array = new Array();

$(document).ready(function() { 
  $.getJSON(
    "/watch_games.cgi?what=get_videos_for_user",
    function(data) { 		
    
      console.log("just got my data back.");
                                
      videos_array = data;
                                  
      populate_advanced_search_options( data );
      
      $("#sport_ddl, #state_ddl, #school_ddl").change(function() { 
        populate_advanced_search_options( videos_array, $(this).attr('id') );
      });
      
      var query_string = parse_querystring();
      if (typeof(query_string) != 'undefined' ) { 
        console.log("qs: sport=%s, state=%s, school=%s", 
          query_string['state'], query_string['sport'], query_string['school'] 
        );
      
        if( query_string['sport'] != "" ) 
          $("#sport_ddl").val( query_string['sport'] );
      
        if( query_string['state'] != "" ) 
          $("#state_ddl").val( query_string['state'] );
      
        if( query_string['school'] != "" ) 
          $("#school_ddl").val( query_string['school'] );
      }
      
    }
  );			
});


function populate_advanced_search_options( data, trigger ) { 

  console.log("populate_advanced_search_options: triggered by %s", trigger );

  var my_videos = videos_array;
      
  var sports = new Array();
  var states = new Array();
  var schools = new Array();
  
  if (trigger == 'sport_ddl') { 
    $("#state_ddl").val("");
    $("#school_ddl").val("");
  }
  else if (trigger == 'state_ddl') { 
    $("#school_ddl").val("");
  }
  
  var selected_sport  = $("#sport_ddl  option:selected").val();
  var selected_state  = $("#state_ddl  option:selected").val();
  var selected_school = $("#school_ddl option:selected").val();
                      
  // weed out videos that don't match currently selected filters		
  //alert("before filter, my_videos.length = " + my_videos.length );
  
  console.log("About to filter videos: trigger=%s, selected_sport=%s, selected_state=%s, selected_school=%s", trigger, selected_sport, selected_state, selected_school );
  
  my_videos = $.grep( my_videos, function(n,i) { 
    console.log("this video: sport=%s, state=%s, school=%s", n.sportID, n.state, n.school );
      
      
    //if( trigger == '' || trigger == 'sport_ddl' ) { 										
      if( selected_sport && n.sportID != selected_sport ) { 
        console.log("filtering out title:", n.title, " because its sportID:", n.sportID, " does not match the selected Sport:", selected_sport );
        return false;
      }
    //}
    
     
    //if( trigger == '' || trigger == 'sport_ddl' || trigger == 'state_ddl' ) { 
      if( selected_state && n.state != selected_state ) {
        console.log("filtering out title:", n.title, " because its state:", n.state, " does not match the selected State:", selected_state );
        return false;
      }
    //}
              
    //if( selected_school && n.school != selected_school ) {
      if( selected_school && n.school != selected_school ) {
        console.log("filtering out title:", n.title, " because its school:", n.school, " does not match the selected School:", selected_school );
        return false;
      }
    //}        
              
    return true;
    
  });			
  
  //alert("after filter, my_videos.length = " + my_videos.length );
  
  $.each( my_videos, function() { 
                                    
    // populate arrays
    if( ! sports[this.sportID] ) { 
      sports[this.sportID] = new Array();
      sports[this.sportID]["name"] = this.sportName;
      sports[this.sportID]["count"] = 1;
    }
    else {
      sports[this.sportID]["count"]++;
    }
    
    if( ! states[this.state] ) { 
      states[this.state] = new Array();
      states[this.state]["count"] = 1;
    } 
    else { 
      states[this.state]["count"]++;
    }
    
    if( ! schools[this.school] ) { 
      schools[this.school] = new Array();
      schools[this.school]["count"] = 1;
    } 
    else { 
      schools[this.school]["count"]++;
    }
                                        
  });
  
  var sport_options = '<option value="">CHOOSE A SPORT</option>';
  for( var i in sports ) { 
    //sport_options += "<option value='" + i + "'>" + sports[i]["name"] + " (" + sports[i]["count"] + ")</option>";
    sport_options += "<option value='" + i + "'>" + sports[i]["name"] + "</option>";
  }
  $("#sport_ddl").find("option").remove().end().append( sport_options );			
  $("#sport_ddl").val( selected_sport );
  

  var state_options = '<option value="">CHOOSE A STATE</option>';
  for( var i in states ) { 
    //state_options += "<option value='" + i + "'>" + i + " (" + states[i]["count"] + ")</option>";
    state_options += "<option value='" + i + "'>" + i + "</option>";
  }
  $("#state_ddl").find("option").remove().end().append( state_options );
  $("#state_ddl").val( selected_state );
  
  var school_options = '<option value="">CHOOSE A SCHOOL</option>';
  for( var i in schools ) { 
    //school_options += "<option value='" + i + "'>" + i + " (" + schools[i]["count"] + ")</option>";
    school_options += "<option value='" + i + "'>" + i + "</option>";
  }
  $("#school_ddl").find("option").remove().end().append( school_options );
  $("#school_ddl").val( selected_school );    
}

function parse_querystring() { 
  var q = location.href;
    
  q = q.split('?')[1];
  
  if( typeof(q) == 'undefined' ) { 
    return;
  }
  
  console.log("q:%s", q);
  q = q.replace(/\+/g, " ");
  console.log("q:%s", q);
  
  var qs = [];
  
  var pairs = q.split('&');  
  for( i in pairs ) {   
    var key = pairs[i].split('=')[0];
    var val = pairs[i].split('=')[1];
    console.log("key=%s, val=%s", key, val );
    qs[ key ] = val;
  }
  return qs;
}

