// Set document.domain to betfair.com:
try {
  document.domain = "betfair.com";
} catch(error) {
  if (window.console) { console.warn("Could not set document.domain"); }
}

jQuery.noConflict(); // Disable $ variable in global namespace.

var Zone = function() {
  var $ = jQuery,                   // jQuery shortcut

      MarketTimestamps      = {},   // Update timestamps for individual markets
      
      UpdateDelay           = 15,   // Interval at which to update home page (seconds)
      
      MainHash              = null, // Hash based on markets column
      MoreHash              = null, // Hash based on more events column
	  embedded              = true;
      
  
  // Prevent IE from caching AJAX requests.
  $.ajaxSetup({cache: false});
  
  // Log the given message at the given logLevel. Looks for a console
  // object to send the log messages to - if that object does not exist,
  // messages are ignored.
  var logger = function(logLevel, message) {
    if (window.console) { console[logLevel](message); }
  };
  
  // Assign the given argument text to the innerHTML property of the given
  // element. If text evaluates to null, a non breaking space will be assigned
  // to the element instead.
  var updateDOMText = function(element, text) {
    // Coerce to string, but only if text is not null:
    if (text !== null) { text = text + ""; }
    
    element.innerHTML = text || "&nbsp;";
  };
  
  // Update the given element with the given text (using the updateDOMText function),
  // but only if the current contents of the element differ from the given text.
  // 
  // Returns a boolean value based on whether an update occurred.
  var updateIfChanged = function(element, text) {
    var textToMatch = $.trim(element.innerHTML).replace('&nbsp;', '');
    
    if (text == null) { text = ''; }
    
    if (text != textToMatch) {
      updateDOMText(element, text);
      return true;
    } else {
      return false;
    }
  };
  
  // Functions that persist the users minimised/maximised market settings to a cookie.
  var minimisedMarkets = {
    cookieName: 'minimised',
    cookieSettings:  {'expires': 14, 'path': '/'},
    
    // Mark the market identified by bfMktId as minimised.
    add: function(bfMktId) {
      var current = minimisedMarkets.readCookie();
      
      bfMktId = bfMktId + '';
      
      if ($.inArray(bfMktId, current) < 0) { current.push(bfMktId); }
      
      // Don't store more than 30 items at a time:
      if (current.length > 30) { current.shift(); }
      
      minimisedMarkets.writeCookie(current);
    },
    
    // Mark the market identified by bfMktId as not minimised.
    remove: function(bfMktId) {
      var current = minimisedMarkets.readCookie(),
          index;
      
      bfMktId = bfMktId + '';
      
      index = $.inArray(bfMktId, current);
      
      if (index >= 0) { current.splice(index, 1); }
      
      minimisedMarkets.writeCookie(current);
    },
    
    readCookie: function() {
      var cookie = $.cookie(minimisedMarkets.cookieName) || '';
      
      if (cookie.length > 0) {
        return cookie.split('-');
      } else {
        return [];
      }
    },
    
    writeCookie: function(array) {
      $.cookie(minimisedMarkets.cookieName, array.join('-'), minimisedMarkets.cookieSettings);
    }
  };
  
  // Functions that show or hide lay prices based on the status of the "Back & Lay" checkbox.
  // This setting is persisted across page views using a cookie.
  var hideLayColumns = {
    cookieName: "hideLayColumns",
    cookieSettings:  {'expires': 365, 'path': '/'},
    
    // Set up event handlers and remove lay prices from the page if necessary.
    init: function() {
      // Store a reference to the checkbox. I will assume that the DOM has loaded
      // at the point this function is being executed, so this should be safe.
      this.checkbox = $("#hide_lay_column");
      
      this.addEventHandler();
      
      if (this.shouldHide() == "true") {
        this.checkbox[0].checked = false;
        
        // Call the event handler without triggering the onClick event:
        this.eventHandler();
      }
    },
    
    // Add an event handler to the "Back & Lay" checkbox.
    addEventHandler: function() {
      this.checkbox.click(hideLayColumns.eventHandler);
    },
    
    // The actual event handler. It's defined seperately so that it can 
    // be called without triggering the onClick event.
    eventHandler: function() {
      if (this.checked) {
        $("table.market").removeClass("market_without_lay_column");
        hideLayColumns.writeCookie(false);
      } else {
        $("table.market").addClass("market_without_lay_column");
        hideLayColumns.writeCookie(true);
      }
    },
    
    // Returns true or false depending on whether or not lay columns should be hidden.
    shouldHide: function() {
      return $.cookie(hideLayColumns.cookieName);
    },
    
    // Write the given value to a cookie.
    writeCookie: function(value) {
      $.cookie(this.cookieName, value, this.cookieSettings);
    }
  };
  
  // Apply a highlight effect to the given element.
  var highlight = function(element) {
    var color = '#FFFF99';
    
    element = $(element);
    
    // Record the original background colour as a custom attribute:
    if (!element.attr('originalBgColor')) {
      element.attr({'originalBgColor' : element.css('backgroundColor')});
    }
    
    element.css('backgroundColor', color);
    element.animate({backgroundColor: element.attr('originalBgColor')}, 800, "swing");
  };
  
  // Minimise or maximises a market.
  var toggleMarket = function(toggleElement) {
    var icon = $(toggleElement).find("span:first"),
        bfMktId = toggleElement.id.match(/\d+/);
    
    if (icon.is(".minimise_icon")) {
      icon.removeClass("minimise_icon").addClass("maximise_icon");
      $("#market_contents_" + bfMktId).hide();
      minimisedMarkets.add(bfMktId);
    } else {
      icon.removeClass("maximise_icon").addClass("minimise_icon");
      $("#market_contents_" + bfMktId).show();
      minimisedMarkets.remove(bfMktId);
    }
  };
  
  // Update the DOM based on the given marketData object.
  var updateMarket = function(market) {
    
    if (market.now) {
      marketTimestamps[market.bf_mkt_id] = market.now;
    }
    
    var marketContents = $("#market_contents_" + market.bf_mkt_id);
    if (marketContents.length) {
      
      if (market.status === "S") {
        marketContents.attr("class", "suspended_market");
      } else if (market.status === "C") {
        marketContents.attr("class", "closed_market");
      } else {
        marketContents.attr("class", "active_market");
        
        var runnersLength = market.runners.length;
 //	    console.warn("updating " + runnersLength + " runners for market "+market.bf_mkt_id)
        for (var i = 0; i < runnersLength; i++) {
          var runner      = market.runners[i],
              //mktRunnerId = runner.bf_mkt_id + "_" + runner.bf_seln_id
              mktRunnerId = runner.bf_mkt_seln_id
              backPrice   = runner.back
              layPrice    = runner.lay
              backElement = document.getElementById("mkt_runner_" + mktRunnerId + "_back_price"),
              layElement  = document.getElementById("mkt_runner_" + mktRunnerId + "_lay_price"),
              button      = null;
          
          if (backElement) {
// 		    console.warn("updating back "+runner.back)
            if (updateIfChanged(backElement, backPrice)) {
              button = $(backElement).parent().parent();
              highlight(button);
            }
          }
          
          if (layElement)  {
// 		    console.warn("updating lay "+runner.lay)
            if (updateIfChanged(layElement, layPrice)) {
              button = $(layElement).parent().parent();
              highlight(button);
            }
          }
        }
      }
      
      // The start_time attribute is not guarenteed to be present, so check
      // that it is defined:
      if (market.start_time) {
        var startTimeElement = document.getElementById("market_start_time_" + market.bf_mkt_id);
        
        updateIfChanged(startTimeElement, market.start_time);
      }

      if (market.chart) {
        var marketChart = $("#market_chart_" + market.bf_mkt_id);
        marketChart.html(market.chart);
      }
    }
  };
  
  var updateMarkets = function(marketDataArray) {
    var marketsLength = marketDataArray.length;
    for (var i = 0; i < marketsLength; i++) {
      updateMarket(marketDataArray[i]);
    }
  };
  
  // Add event handlers to a market grid. This needs to be done when the page
  // is loaded, but also whenever the grid is reloaded.
  var addGridEventHandlers = function() {
    // Register event handler for market refresh:
    $("a.market_refresh").click(function() {
      var re = /refresh_(\d+)$/;
      var m = re.exec(this.id);
      var mkt_id = parseInt(m[1]);
      var href = this.href + "&timestamp=" + marketTimestamps[mkt_id];
      $.getJSON(href, function(data) {
        if (data) { updateMarket(data); }
      });
      
      return false;
    });
  };
  
  // Public functions:
  return {
    init: function() {
      addGridEventHandlers();
      this.initMultiplesLink();
    },
    
    // Add the multiples link event handler.
    initMultiplesLink: function() {
      // Send the browser to the multiples thing (relies on the presence of the "menu"
      // frame, and the function switchTab being defined in that frame).
      $("#multiples_link").click(function() {
        if (parent["menu"]) { parent["menu"].switchTab(3); }
      });
    },
    
    
    // Initialise home page data updates.
    initMarketUpdate: function(updatedTimestamp, marketListEnc) {
      
      var updateFunction = function() {
        var newHash = null,
            params = {
              "action"     : "update_all"
            };
        
        $.getJSON(Config.AS_URL, params, function(data) {
          // Update the markets grid if the grid_hash value indicates that it
          // has been changed.
          if (data.main_hash) {
            if (MainHash !== data.main_hash) {
              var newHashF = data.main_hash;
              
              $.get(Config.AS_URL, {"action" : "main_frag"}, function(data) {
                var marketsGrid = $("#markets_grid");
                
                marketsGrid.replaceWith(data);
                
                // Store the updated hash value:
                MainHash = newHashF;
                
                // Add event handlers when the DOM is ready:
                marketsGrid.ready(function() { addGridEventHandlers(); });
              });
            }
          }
          
          // Update the more events column if the event_hash value indicates
          // that it has been changed.
          if (data.more_hash) {
            if (MoreHash !== data.more_hash) {
              var newHashM = data.more_hash;
              
              $.get(Config.AS_URL, {"action" : "more_frag"}, function(data) {
                $("#more_events").replaceWith(data);
                
                // Store the updated hash value:
                MoreHash = newHashM;
              });
            }
          }
          
          if (data.markets) {
            // Push market data to the DOM:
            updateMarkets(data.markets);
          }
        });
      };
      
      setInterval(updateFunction, UpdateDelay * 1000);
    },

    initHashes: function(main_hash, more_hash) {
      MainHash = main_hash;
      MoreHash = more_hash;
    },
    
    // Initialise minimised markets functionality.
    initMinimise: function() {
      // Add toggle market event handler:
      $("a.toggle_market").click(function() { toggleMarket(this); });
      
      var minimised = minimisedMarkets.readCookie();
      
      for (var i = 0; i < minimised.length; i++) {
        var toggleElement = document.getElementById("market_toggle_" + minimised[i]);
        
        if (toggleElement) {
          $(toggleElement).find("span").removeClass("minimise_icon").addClass("maximise_icon");
          $("#market_contents_" + minimised[i]).hide();
        }
      }
    },
    
    // Initialise "Back & Lay" checkbox functionality.
    initHideLay: function() { hideLayColumns.init(); },

    initBetfairMenu: function() {
      if (window.location.href.indexOf("origin=LHM") == -1) {
        if (parent['menu']) {
          if (parent['menu'].goMenu) { parent['menu'].goMenu(2839625); }
        }
      }

    }
  };
}();

function fmt(msg, params) {
    if (params == null) { params = []; }

    for (var i = 0; i < params.length; i++)
        if (params[i]) {
            msg = msg.replace('%s', params[i], '');
        } else {
            msg = msg.replace('%s', '', '');
        }

    return msg;
}
if (parent['menu']) {
	var embedded = true;
} else {
	var embedded = false;
}

function bf_mkt_link(mkt_id, exch_id, seln_id) {

	if (embedded) {
		var url = fmt("http://%s/betting/MarketView.do?mi=%s&amp;ex=%s&amp;rfr=3925",
             	[Config.BF2_URL, mkt_id, exch_id]);
		location.href = url;

	} else {

    	var url = fmt("http://%s/Index.do?mi=%s&ex=%s&rfr=3925suid=3925&bspi=3925",
				[Config.BF_URL, mkt_id, exch_id]);
    	
		window.open(url, '_blank');
	}
}

function bf_stats_link(mkt_id, exch_id, seln_id) {
    
	if (exch_id == 2) {
		var exchange = "au"
	} else {
		var exchange = "uk"
	}
	
	var url = fmt("http://%s.%s/betting/LoadRunnerInfoAction.do?marketId=%s&selectionId=%s&rfr=3925",
              [exchange, Config.BF2_URL, mkt_id, seln_id]);

    window.open(url, '_blank', 'width=700,height=554,toolbar=0,resizable=0');
}

function big_chart(mkt_id, exch_id, pcts, mkt_name) {

	if (pcts == -1) {
		var f = document.forms["chart_opts_" + mkt_id];
		if (f) {
			var el = f.elements['radio_chart_'+mkt_id]
			for (var i = 0; i < el.length; i++) {
				if (el[i].checked) {
					pcts = el[i].value;
					break;
				}
			}
		}

		if (pcts == -1) {
			pcts = 1;
		}
	}


	var url = fmt("%s?action=large_chart&exch_id=%s&mkt_id=%s&pcts=%s",
              [Config.APP_URL, exch_id, mkt_id, pcts]);

    window.open(url, mkt_id, 'top=50, left=50, width=450, height=460');
}

function inverse_axis(cb, mkt_id) {

	var pct_img = document.getElementById("chart_pcts_" + mkt_id);
	var prc_img = document.getElementById("chart_prcs_" + mkt_id);
	
	if (cb.value == 1) {
		jQuery(pct_img).removeClass('chart_hidden');
		jQuery(prc_img).addClass('chart_hidden');
	} else {
		jQuery(prc_img).removeClass('chart_hidden');
		jQuery(pct_img).addClass('chart_hidden');
	}
}


jQuery(document).ready(function() { Zone.init();});


