/**
 * My list singleton class 
 */
var MyList = new function() {

   this.content = new Array();
   
   /***** Public methods *****/
   this.compare = function() {
      if(this.content.length > 0) {
         var result = "";
         for (var i = 0; i < this.content.length && i < 3; i++) {
            if (i > 0) result += '|';
            result += this.content[i].start_nbr + "|" + this.content[i].event;
         }
         window.location.href = 'compare.php?r=' + result;
      } else {
         alert("Lägg till minst ett resultat i Min Lista först");
      }
   };
   this.add = function(inp_event, inp_start_nbr) {
      $(document).trigger("mylist.loading");
      $(document).trigger("mylist.add");
      $.getJSON("do.php", {event: inp_event, action: 'mylist_add', start_nbr: inp_start_nbr},MyList.load);
   };
   
   this.remove = function(inp_index) {
      $(document).trigger("mylist.loading");
      $(document).trigger("mylist.remove");
      $.getJSON("do.php", {action: 'mylist_remove', start_nbr: inp_index},MyList.load);
   };
   
   this.load = function() {
      $.getJSON("do.php", 
                {action: 'mylist_get'},
                function(data) {
                  if (data) {
                     MyList.content = new Array();
                     if(data.count > 0){
                        $.each(data.data, function (i, entry){
                           MyList.content.push(entry);
                        });
                     }
                  }
                  $(document).trigger("mylist.loaded");
                });
   };
   
   this.addClassic = function() {
      $(document).trigger("mylist.loading");
      // Verify number of events
      if(this.content.length != 4) {
         $('#mylist_wait').removeClass("active");
         alert("En Svensk Klassiker består utav fyra delresultat utförda inom loppet av ett år: Vasaloppet/Öppet Spår, Vätternrundan, Vansbrosimningen och Lidingöloppet. " +
               "\n\nLägg till delresultaten i Min Lista först och välj sedan Registrera Klassiker");
         return false;
      }
      // Try to add results
      $.getJSON("classic.php", 
                {action: 'add_classic', 
                 event0: this.content[0].event, id0: this.content[0].start_nbr,
                 event1: this.content[1].event, id1: this.content[1].start_nbr,
                 event2: this.content[2].event, id2: this.content[2].start_nbr,
                 event3: this.content[3].event, id3: this.content[3].start_nbr},
                function(data) {
                   $(document).trigger("mylist.loaded");
                   alert(data.message);
                });
   };
};

$(document).bind("mylist.load", MyList.load);
$(document).ready(function() { $(document).trigger("mylist.ready"); });


