//  Interested in looking at our code?  Maybe you should work for us !!!

//  If you understand most of what is going on below this message and you have a real passion 
//  for working somewhere which breaks into new opportunites and CAN'T STAND red tape you may 
//  be right for the job.  Oh.. you need to know a bit about horse racing!
//  Drop us an email: info@puntersparadise.com.au

  function OCHandler()
  {
    this.currentEvents = new Array();
    this.upcomingSubscribed = false;
    this.lastRanSubscribed = new Date()-1000000;
    this.subscribedLayout = 0;
  }

  function EventDetails()
  {
    this.eventID = null;
  }

  //The page calls this event to subscribe to the odds refresh. It doesn't matter if the page already has a div which contains the field or not as the subscription service detects what is missing and picks up from there.
  OCHandler.prototype.subscribeEvent = function(eventID,layout)
  {
    if (!ocph.eventExists(eventID) && eventID > 0)
    {
      var newEvent = new EventDetails();
      var now = new Date();
      newEvent.eventID = eventID;
      newEvent.lastRan = now - 1000000; //Expire the event so the odds come in straight up
      newEvent.expiry = 1000;           //Default is every 1 second.  The times will adjust when the first feed arrives
      newEvent.state = 1;               //0 = Closed, 1 = Open
      newEvent.locked = 0;              //0 = Not locked, 1 = Locked
      newEvent.layout = layout;
      ocph.currentEvents.push(newEvent);
    }
  }

  OCHandler.prototype.unsubscribeEvent = function(eventID)
  {
    //Remove the DIV, remove the event object
    if (eventID > 0)
    {
      $("#ocEvent_"+eventID).remove();
      for(var j = ocph.currentEvents.length-1; j >= 0; j--)
      {
        if (ocph.currentEvents[j].eventID == eventID)
        {
          ocph.currentEvents.splice(j, 1);
          return true;
        }
      }
    }
    return false;
  }

  OCHandler.prototype.subscribeUpcoming = function(layout)
  {
    //Subscribes to the upcoming events.  So, poll the GetEventID's, checking if they exist.  If they don't exist, subscribe, if we have orphaned events - unsubscribe them
    ocph.upcomingSubscribed = true;
    ocph.subscribedLayout = layout;
  }

  OCHandler.prototype.eventExists = function(eventID)
  {
    for(var j = ocph.currentEvents.length-1; j >= 0; j--)
    {
      if (ocph.currentEvents[j].eventID == eventID)
      {
        return true;
      }
    }
    return false;
  }

  OCHandler.prototype.OCTimeLoop = function()
  {
    var now = new Date();
    if (ocph.upcomingSubscribed == true && (now-ocph.lastRanSubscribed) > 120000)  //2 minutes
    {
      ocph.lastRanSubscribed = now;
      ocph.updateSubscribes();
    }
    else
    {
      for(var j = ocph.currentEvents.length-1; j >= 0; j--)
      {
        if ((now-ocph.currentEvents[j].lastRan) > ocph.currentEvents[j].expiry && ocph.currentEvents[j].locked == 0)
        {
          ocph.currentEvents[j].locked = 1;
          //Which event do we fire off? The action to load the whole even completely or the action to load the market odds only
          if ($('#ocEvent_' + ocph.currentEvents[j].eventID).length == 0)
          {
            ocph.renderMarket(ocph.currentEvents[j].eventID,ocph.currentEvents[j].layout);
          }
          else
            ocph.updateMarket(ocph.currentEvents[j].eventID,ocph.currentEvents[j].layout);
        }
      }
    }
    $.timezones();
    ocph.runTimer();
  }

  OCHandler.prototype.renderMarket = function(eventID,layout)
  {
    //Pull the new market from the server
    $.post('/OC_RenderMarket.php',{e: eventID,l: layout},function (data,state) { 
      $(".ocContainer").append(data);
      for(var j = ocph.currentEvents.length-1; j >= 0; j--)
      {
        if (ocph.currentEvents[j].eventID == eventID)
        {
          var now = new Date();
          ocph.currentEvents[j].locked = 0;   
          ocph.currentEvents[j].lastRan = now;
        }
      }
      if (ocph.currentEvents.length >= 2)
      {
        //Re sort as a new market has appeared
        $(".ocContainer div").tsort("span.gmt", {order:"asc"});
      }
    });
  }

OCHandler.prototype.updateSubscribes = function()
  {
    //Pull the new market from the server
    var randomnumber=Math.floor(Math.random()*10000);
    $.getJSON( "/OC_EventsUpcoming.php?rnd="+randomnumber, 
      function(json)
      {
        //Loop through events, remove any that don't exist in the response
        for(var j = ocph.currentEvents.length-1; j >= 0; j--)
        {
          var inlist = false;
          for(var i = 0; i < json.EventIDs.length; i++)
          {
            if (json.EventIDs[i] == ocph.currentEvents[j].eventID)
            {
              inlist = true;
            }
          }
          if (inlist == false)
          {
            ocph.unsubscribeEvent(ocph.currentEvents[j].eventID);
          }
        }
        //Subscribe and render if needed
        for(var i = 0; i < json.EventIDs.length; i++)
        {
          ocph.subscribeEvent(json.EventIDs[i],ocph.subscribedLayout);
        }
      }
    );
  }

  OCHandler.prototype.updateMarket = function(eventID,layout)
  {
    //Pull the new market from the server
    var randomnumber=Math.floor(Math.random()*10000);

    $.getJSON( "/OC_UpdateMarket.php?e=" + eventID + "&rnd="+randomnumber+"&l="+layout, 
      function(json)
      { 
        for(var j = ocph.currentEvents.length-1; j >= 0; j--)
        {
          if (ocph.currentEvents[j].eventID == json.EventID)
          {
            var marketMover = null;
            var totalSportingbet = 0;
            for(var i = 0; i < json.Selections.length; i++)
            {
              if (ocph.currentEvents[j].layout == 1)  //Market mover is not on the home page
              {
                if ((json.Selections[i].Sportingbet) != 'undefined' && (json.Selections[i].SportingbetOpen) != 'undefined' && json.Selections[i].SportingbetOpen > 0 && json.Selections[i].Sportingbet > 0)
                {
                  var newMovement = Math.round(100-(((json.Selections[i].Sportingbet-1)/(json.Selections[i].SportingbetOpen-1))*100),0);
                  if (marketMover == null || newMovement > Math.round(100-(((marketMover.Sportingbet-1)/(marketMover.SportingbetOpen-1))*100),0))
                    marketMover = json.Selections[i];
                }
              }

              var bigbetsOdds = 0;
              if (json.Selections[i].STab > 0 || json.Selections[i].NSWTAB > 0 || json.Selections[i].UNiTAB > 0)
              {
                if (parseFloat(json.Selections[i].NSWTAB) > bigbetsOdds)
                  bigbetsOdds = parseFloat(json.Selections[i].NSWTAB);
                if (parseFloat(json.Selections[i].STab) > bigbetsOdds)
                  bigbetsOdds = parseFloat(json.Selections[i].STab);
                if (parseFloat(json.Selections[i].UNiTAB) > bigbetsOdds)
                  bigbetsOdds = parseFloat(json.Selections[i].UNiTAB);
                bigbetsOdds = (bigbetsOdds+.05);
              }
              var bestOdds = 0;
              if (ocph.currentEvents[j].layout == 2 || ocph.currentEvents[j].layout == 3)  //The home page layout has TAB odds
              {
                if (typeof(json.Selections[i].UNiTAB) != 'undefined' && parseFloat(json.Selections[i].UNiTAB) > bestOdds)
                  bestOdds = parseFloat(json.Selections[i].UNiTAB);
                if (typeof(json.Selections[i].NSWTAB) != 'undefined' && parseFloat(json.Selections[i].NSWTAB) > bestOdds)
                  bestOdds = parseFloat(json.Selections[i].NSWTAB);
                if (typeof(json.Selections[i].STab) != 'undefined' && parseFloat(json.Selections[i].STab) > bestOdds)
                  bestOdds = parseFloat(json.Selections[i].STab);
                if (typeof(bigbetsOdds) != 'undefined' && bigbetsOdds > bestOdds)
                  bestOdds = bigbetsOdds;
              }
              if (typeof(json.Selections[i].Centrebet) != 'undefined' && parseFloat(json.Selections[i].Centrebet) > bestOdds)
                bestOdds = json.Selections[i].Centrebet;
              if (typeof(json.Selections[i].Sportsbet) != 'undefined' && parseFloat(json.Selections[i].Sportsbet) > bestOdds)
                bestOdds = json.Selections[i].Sportsbet;
              if (typeof(json.Selections[i].Sportingbet) != 'undefined' && parseFloat(json.Selections[i].Sportingbet) > bestOdds)
                bestOdds = json.Selections[i].Sportingbet;
              if (typeof(json.Selections[i].BetfairW) != 'undefined' && parseFloat(json.Selections[i].BetfairW) > bestOdds)
                bestOdds = json.Selections[i].BetfairW;

              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"BetfairL",json.Selections[i].BetfairL,false,i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"UNiTAB",json.Selections[i].UNiTAB,(json.Selections[i].UNiTAB == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"NSWTAB",json.Selections[i].NSWTAB,(json.Selections[i].NSWTAB == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"STab",json.Selections[i].STab,(json.Selections[i].STab == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"Centrebet",json.Selections[i].Centrebet,(json.Selections[i].Centrebet == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"Sportsbet",json.Selections[i].Sportsbet,(json.Selections[i].Sportsbet == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"Sportingbet",json.Selections[i].Sportingbet,(json.Selections[i].Sportingbet == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"BetfairW",json.Selections[i].BetfairW,(json.Selections[i].BetfairW == bestOdds),i);
              updateCellOdds(json.EventID,json.Selections[i].SelectionID,"BigBets",bigbetsOdds,(bigbetsOdds == bestOdds),i);
              
              if (ocph.currentEvents[j].layout == 3 && typeof(json.Selections[i].Sportingbet) != 'undefined' && typeof(json.Selections[i].SportingbetOpen) != 'undefined' && parseFloat(json.Selections[i].Sportingbet) > 0 && parseFloat(json.Selections[i].SportingbetOpen) > 0)  //The full OC
              {
                if (json.Selections[i].Sportingbet > 0)
                {
                  totalSportingbet = totalSportingbet + (100/parseFloat(json.Selections[i].Sportingbet));
                }
                var movement = Math.round(100-(((parseFloat(json.Selections[i].Sportingbet)-1)/(parseFloat(json.Selections[i].SportingbetOpen)-1))*100),0);
                var movementClass = '';
                if (movement > 0)
                  movementClass = 'in';
                else if (movement < 0)
                {
                  movementClass = 'out';
                  movement = movement * -1;
                }
                $("#ocSelection_" + json.Selections[i].SelectionID + "Move").html('<span class="' + movementClass + '">' + movement + "%</span>");
                $("#ocSelection_" + json.Selections[i].SelectionID + "Open").html(parseFloat(json.Selections[i].SportingbetOpen));
                if (parseFloat(json.Selections[i].SportingbetFluc1))
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Fluc1").html(parseFloat(json.Selections[i].SportingbetFluc1));
                else
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Fluc1").html('');
                if (parseFloat(json.Selections[i].SportingbetFluc2))
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Fluc2").html(parseFloat(json.Selections[i].SportingbetFluc2));
                else
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Fluc2").html('');
                if (parseFloat(json.Selections[i].SportingbetFluc1) < parseFloat(json.Selections[i].SportingbetFluc2))
                {
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Pointer").html('<img src="http://images.puntersparadise.com.au/betting/oddsComparision/up.gif"/>');
                }
                else if (parseFloat(json.Selections[i].SportingbetFluc1) > parseFloat(json.Selections[i].SportingbetFluc2))
                {
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Pointer").html('<img src="http://images.puntersparadise.com.au/betting/oddsComparision/down.gif"/>');
                }
                else
                {
                  $("#ocSelection_" + json.Selections[i].SelectionID + "Pointer").html('');
                }
              }
            }
            if (ocph.currentEvents[j].layout == 3 && totalSportingbet > 0)  //The full OC
            {
              $("#ocEvent_" + json.EventID + " .marketStats").html('<a href="/link/5/" target="_blank">Sportingbet</a> Market ' + Math.floor(totalSportingbet)+'%');
            }
            if (marketMover != null)
            {
              var movement = Math.round(100-(((marketMover.Sportingbet-1)/(marketMover.SportingbetOpen-1))*100),0);
              if (movement > 0)
                $("#ocEvent_" + json.EventID + " .mover").html('<span class="runner">' + $("#ocSelection_" + marketMover.SelectionID+ " td.name div.name").html() + '</span><br/><span class="odds">$'+marketMover.SportingbetOpen+' into $'+marketMover.Sportingbet+' <span>' + movement + '%</span></span>');
              else
                $("#ocEvent_" + json.EventID + " .mover").html('MARKET MOVER<br/>NOT AVAILABLE');
            }
            else
              $("#ocEvent_" + json.EventID + " .mover").html('MARKET MOVER<br/>NOT AVAILABLE');

            var now = new Date();
            ocph.currentEvents[j].locked = 0;     //Unlock it!
            ocph.currentEvents[j].lastRan = now;
            ocph.currentEvents[j].expiry = json.Expiry;
          }
        }
      }
    );
  }

  function updateCellOdds(eventID,selectionID,agencyName,newOdds,isBestOdds,index)
  {
    if (newOdds > 100)
    {
      newOdds = Math.round(newOdds);  //no decimals
    }
    else if (newOdds > 10)
    {
      newOdds = Math.round(newOdds*10)/10;  //one decimal place
    }
    else if (newOdds > 0)
    {
      newOdds = Math.round(newOdds*100)/100;  //two decimal places
    }
    var cell = $("#ocSelection_" + selectionID + agencyName);
    var oddsContainer = cell;
    if (cell.children("a").length == 0)
    {
      var currentOdds = cell.html();  //Save the odds
      var agencyLink = $("#ocEvent_" + eventID + agencyName + "Link").attr("href");
      //Put the odds around an A tag
      if (agencyLink != null && agencyLink.length > 0)
      {
        var aTag = $('<a href="' + agencyLink + '" target="_blank">' + cell.html() + "</a>");
        cell.html(aTag);
        oddsContainer = aTag;
      }
    }
    else
    {
      var oddsContainer = cell.children("a");
      var currentOdds = oddsContainer.html();
    }
    if (currentOdds != '-' && currentOdds != '' && currentOdds != newOdds)
    {
      var currentOddsNum = parseFloat(currentOdds);
      //fade odds in
      if (cell.colorBlend)
      {
        if (currentOddsNum > newOdds)
        {
          if (index % 2 == 1)
            cell.colorBlend([{param:"background-color",fromColor:"#FBFBFB",toColor:"#dfffd7",duration:5000,cycles:1}]); //Odds are coming in
          else
            cell.colorBlend([{param:"background-color",fromColor:"#ffffff",toColor:"#dfffd7",duration:5000,cycles:1}]); //Odds are coming in
        }
        else
        {
          if (index % 2 == 1)
            cell.colorBlend([{param:"background-color",fromColor:"#FBFBFB",toColor:"#ffd7d7",duration:5000,cycles:1}]);
          else
            cell.colorBlend([{param:"background-color",fromColor:"#ffffff",toColor:"#ffd7d7",duration:5000,cycles:1}]);
        }
      }
    }
    
    if (newOdds != currentOdds)
    {
      oddsContainer.html(newOdds);
    }
    if (isBestOdds == true)
      cell.addClass("bestOdds");
    else
      cell.removeClass("bestOdds");
  }

  OCHandler.prototype.runTimer = function()
  {
    window.setTimeout(function() { ocph.OCTimeLoop(); }, 4000); //4 seconds.  The smaller this number the more chance the OC doesn't keep loading OC's at the same time - i.e. the refreshes start spreading out
  }

  var ocph = new OCHandler();

  $(document).ready(function() 
  {
    ocph.OCTimeLoop();
  });