$(function() {
  //get the last city and see whether is null or not
  var kc = storage.get('KC');
  var city;
  if (kc && kc.length && (city = kc[0][1])) {
    $("#search-location").val(city);
  } else {
    $.getJSON('/ip-2-city/', function(o) {
      $("#search-location").val(o.city);
    });
  }

  //get the last 5 records and display
  if (kc && kc.length) {
    $("#recent-searches").show();
    var list = $('<ul class="searched-list">');
    list.prependTo($("#recent-searches .content"));

    // json: [[111, 'php', 'beijing'], [222, 'java']]
    $.getJSON(
      $("#search-form").attr('action').replace(
        "/search-submit/", 
        "/search-history/?_=" + (+new Date())
      ), 
      function(data) {
        $.each(data, function(i, v) {
          var li = $("<li/>");
          var anchor = $("<a/>");
          var emailAnchor = $("<a/>");
          emailAnchor.addClass("icon email");
          var wrap = $("<span/>");
          wrap.addClass("ml-20");

          if (v[2]) { // has city
            anchor.attr(
              "href", 
              $("#search-form").attr("action").replace(
                "/search-submit/", 
                "/search/" + encodeURIComponent(v[1]) + "/?location=" + v[2]
              )
            ).text(__(
              '%job% in %location% ', 
              { '%job%': v[1], '%location%': v[2] }
            ));
          } else { // no city
            anchor.attr(
              "href", 
              $("#search-form").attr("action").replace(
                "/search-submit/", 
                "/search/" + encodeURIComponent(v[1]) + '/'
              )
            ).text(v[1]);
          }

          emailAnchor.attr(
            "href", 
            $("#search-form").attr("action").replace(
              "/search-submit/",
              "/my/subscription/new?job=" + encodeURIComponent(v[1]) 
            )
          ).text(__('Get email job alerts'));

          v[2] && emailAnchor.attr(
            "href", 
            emailAnchor.attr("href") + '&location=' + v[2]
          );

          wrap.append(emailAnchor);
          li.append(__('%cnt% Jobs for', { "%cnt%": v[0] }));
          li.append(' ');
          li.append(anchor);
          li.append(wrap);
          list.append(li);
        });
      }
    );
  } else {
    $("#hot-jobs").show();
  }

  //clear cookie 'keyAndCity'
  $(".content .delete").bind("click", function(e) {
    $(".content .searched-list").empty();
    $("#recent-searches").hide();
    $("#hot-jobs").show();
    storage.set('KC', null);
    e.preventDefault();
  })
});
