var debug = true;
function log(msg) {
  if (debug && console && console.log) {
    console.log(msg);
  }
}

function HashState() {
}

HashState.prototype = {
    load : function(hash) {
      if (hash == null) {
        hash = document.location.hash
      }
      if (hash[0] == '#') {
        hash = hash.substring(1);
      }
      if (hash.length > 0) {
        var parts = hash.split("/");
        var method = parts.shift();
        window[method].apply(null, parts);
      }
    },
    call : function(fn, args) {
      var name = fn.toString().match("function ([^\(]*)")[1];
      document.location.hash = name;
      $.each(args, function(k, v) {
        document.location.hash += "/" + v.toString();
      });
      fn.apply(null, args);
    },
    hasState : function(hash) {
      if (hash == null) {
        hash = document.location.hash
      }
      if (hash[0] == '#') {
        hash = hash.substring(1);
      }
      return hash.length > 0;
    }
};

var state = new HashState();

function cornerThings($) {
  $('.noselect').live('selectstart dragstart', function(evt) {
    evt.preventDefault();
    return false;
  });

  $("#send_options li:first, #duration_options li:first, #receive_options li:first")
    .each(function() {
      $(this).click(function() {
        $(this).parent().toggleTop({
          height : 'auto'
        }, function() {
          $(this).fixBoxModel();
        });
      }).parent().fixBoxModel().corner();
    });
}

function setupSlider(state) {
  // ///////////////////////////////////////////////////////////////////////////
  // The slider -- Should be obvious
  $('#slider').slider({
      value : 150,
      min : 50,
      max : 2000,
      step : 5,
      slide : function(event, ui) {
        // Bind to the element
        $("#amount").val("$" + ui.value);
        getProductsFor();
      }
  });
  // Bind to the element on load
  $("#amount").css({
      textAlign : 'center',
      fontSize : "1.5em"
  });
  $("#amount").change(function() {
    $("#slider").slider("value", $(this).val().substring(1));
    getProductsFor();
  });

  $("#amount").css({
      border : "none",
      width : "100%"
  });
  $("#amount_container").css({
      border : " 3px inset #CCC",
      width : "10em",
      margin : ".3em"
  }).corner("keep");
  $("#amount").val("$" + $("#slider").slider("value"));
}
// ///////////////////////////////////////////////////////////////////////////
// from drop down
function setupFrom(state) {
  var $ul = $("#src_country");

  $ul.mousedown(function() {
    $ul.css({
      background : "#786A60"
    });
    return false;
  });
  $ul.mouseup(function() {
    $ul.css({
      background : "#FFF"
    })
  });
  $ul.css({
      listStyle : "none",
      fontSize : "12pt",
      border : "3px inset #EEE",
      color : "#333",
      padding : "1 10",
      margin : 0,
      width : 200,
      overflow : "hidden"
  }).height("1.5em").fixBoxModel();
  $ul
    .click(function() {
      var parent = $ul.parent();
      var pos = $ul.position();
      var $cp = $ul.clone(true, true);
      $cp.css({
          display : "block",
          position : "absolute",
          width : $ul.width(),
          height : "auto",
          left : pos.left,
          top : pos.top,
          margin : 0,
          overflow : "visible"
      });
      var $chi = $cp.find("li");
      $chi.mouseenter(function() {
        $(this).css("background", "#999");
      });
      $chi.mouseout(function() {
        $(this).css("background", "#FFF");
      });
      $chi
        .click(function() {
          var $this = $(this);
          $ul
            .data("country_id", $this.attr('class').match(/country_id-(\d+)/)[1]);
          $ul.data("currency_id", $this.attr('class')
            .match(/currency_id-(\d+)/)[1]);
          // And destroy the selector
          $cp.remove();
          $ul.show();
          // Run the query for dst options
          getProductsFor();
        });
      $ul.after($cp);
      $ul.hide();
    });
  // Rounding
  $ul.corner("keep");

  // INITIAL DST OPTIONS!
  // Here we are setting the data to the first option.
  if (!state.hasState()) {
    getProductsFor();
  }
}

// ///////////////////////////////////////////////////////////////////////////
// to drop down
function setupTo(state) {
  var $ul = $("#dst_country");
  $ul.mousedown(function() {
    $ul.css({
      background : "#786A60"
    });
    return false;
  });
  $ul.mouseup(function() {
    $ul.css({
      background : "#FFF"
    })
  });
  $ul.css({
      listStyle : "none",
      border : "3px inset #EEE",
      color : "#333",
      padding : "1 10",
      margin : 0,
      width : 200,
      overflow : "hidden",
      position : 'relative'
  }).height("1.5em").fixBoxModel();
  $ul
    .click(function() {
      var parent = $ul.parent();
      var pos = $ul.position();
      var $cp = $ul.clone(true, true);
      $cp.css({
          display : "block",
          position : "absolute",
          width : $ul.width(),
          height : "auto",
          left : pos.left,
          top : pos.top,
          margin : 0,
          overflow : "visible"
      });
      var $chi = $cp.find("li");
      $chi.mouseenter(function() {
        $(this).css("background", "#999");
      });
      $chi.mouseout(function() {
        $(this).css("background", "#FFF");
      });
      $chi
        .click(function() {
          var $this = $(this);
          // Data
          $ul
            .data("country_id", $this.attr('class').match(/country_id-(\d+)/)[1]);
          $ul.data("currency_id", $this.attr('class')
            .match(/currency_id-(\d+)/)[1]);
          $cp.remove();
          $ul.css({
            visibility : "visible"
          });

          getProductsFor();
        });
      $ul.css({
        visibility : "hidden"
      });
      $ul.after($cp);
    });
  // Rounding
  $ul.corner("keep");
}

/**
 * This function pretty much does everything... Set the slider to the desired
 * amount if it's not set, or read it from the slider if it's null.
 * 
 * Sets the src country/currency id's if not set.
 */
function getProductsFor(src_country_id, src_currency_id, dst_country_id, dst_currency_id, amount, fn) {

  // Ensure a proper slider value
  if (amount == null) {
    // Grab slider value
    amount = $('#amount').val();
  } else if ($('#amount').val() != amount) {
    // Make sure slider is in the correct position.
    $('#amount').val(amount);
    $("#slider").slider("value", amount.substring(1));
  }

  // Ensure a proper src_country/currency value
  var $src_country = $('#src_country');
  if (src_country_id == null || src_currency_id == null) {
    // Grab the existing value
    src_country_id = $src_country.data('country_id');
    src_currency_id = $src_country.data('currency_id');
    if (src_country_id == null || src_currency_id == null) {
      var $src_country_first = $src_country.find("li:first");
      src_country_id = $src_country_first.attr('class')
        .match(/country_id-(\d+)/)[1]
      src_currency_id = $src_country_first.attr('class')
        .match(/currency_id-(\d+)/)[1]
    }
  } else {
    $src_country.data('country_id', src_country_id);
    $src_country.data('currency_id', src_currency_id);
  }

  // Make sure that the value is properly selected...
  var $src_country_selected = $src_country
    .find(".country_id-" + src_country_id + ".currency_id-" + src_currency_id);
  var src_country_scrollto = $src_country_selected.position().top - $src_country
    .offset().top;
  log("Moving source country: " + src_country_scrollto);
  $src_country.animate({
    scrollTop : src_country_scrollto
  }, 500);

  // Ensure a proper dst_country/currency value
  var $dst_country = $('#dst_country');

  if (dst_country_id == null || dst_currency_id == null) {
    // Grab the existing value
    dst_country_id = $dst_country.data('country_id');
    dst_currency_id = $dst_country.data('currency_id');
    if (dst_country_id == null || dst_currency_id == null) {
      log("Picking up dst data from first option or the philippenes");
      var $dst_country_first = $dst_country
        .find('.country_id-169:last, li:first').last();
      var dst_country_first_class = $dst_country_first.attr('class');
      if (dst_country_first_class) {
        dst_country_id = dst_country_first_class.match(/country_id-(\d+)/)[1]
        dst_currency_id = dst_country_first_class.match(/currency_id-(\d+)/)[1]
      }
    }
  } else {
    $dst_country.data('country_id', dst_country_id);
    $dst_country.data('currency_id', dst_currency_id);
  }

  var $dst_country_selected = $dst_country
    .find(".country_id-" + dst_country_id + ".currency_id-" + dst_currency_id);

  if ($dst_country_selected.size() == 0) {
    // Crap -- we have to load the source country options
    console
      .log("Getting dst options for " + src_country_id + " : " + src_currency_id);
    $
      .get("/getDstOptionsFor/" + src_country_id + "/" + src_currency_id, function(r) {
        $dst_country.html(r);
        getProductsFor(src_country_id, src_currency_id, dst_country_id, dst_currency_id, amount, fn);
      });
    return;
  }

  // Make sure that the value is properly selected
  var dst_country_scrollto = $dst_country_selected.position().top + $dst_country
    .scrollTop();
  log("Moving dst country: " + dst_country_scrollto);
  $dst_country.animate({
    scrollTop : dst_country_scrollto
  }, 500);

  log("getProductsFor(" + src_country_id + "," + src_currency_id + "," + dst_country_id + "," + dst_currency_id + "," + amount + ")");
  // Load products
  $
    .get("/getProductsFor/" + src_country_id + "/" + src_currency_id + "/" + dst_country_id + "/" + dst_currency_id + "/" + amount, function(r) {
      var $next = $(".products_next");
      $next.append($next.html(r).find("li").sorted({
        by : function(v) {
          return -$(v).attr("data-sort");
        }
      }).detach());
      var max = parseFloat($next.find(".product_col_received:first").text());
      $next.find("li").each(function() {
        var $this = $(this);
        var cur = parseFloat($this.find(".product_col_received").text());
        $this.find(".product_col_received").prepend(Math
          .round((cur / max) * 10000)/100 + "%<br/>");
      });

      $(".products").quicksand($(".products_next > li"), {});
      $(".products_next").html("");

    });
}

function load($) {
  setupSlider(state);
  setupFrom(state);
  setupTo(state);

  cornerThings($);
  state.load();
}
jQuery(load);

