var defaultSearchText;

$(document).ready(function() {
  defaultSearchText = "";

  MAMASWAP.handleIncompletePurchase();

  // Set default search box state
  if($("#searchbox").val() == "" || $("#searchbox").val() == defaultSearchText) {
    $("#searchbox").val(defaultSearchText);
    $("#searchbox").addClass("default-search");
  } else {
    $("#searchbox").addClass("selected-search");
  }
  
  // Show selected items as selected
  $(".listing-container").each(function() {
    if($.inArray($(this).attr("id").replace("thumb_", ""), $.savedListings()) > -1) {
      $(this).addClass("listing-marked");
    }
  });
  
  // Search box events
  $("#searchbox").blur(function(event) {
    if($(this).val() == "") {
      $(this).addClass("default-search");
      $(this).removeClass("selected-search");
      $(this).val(defaultSearchText); }
  });

  $("#searchbox").focus(function(event) {
    if($(this).val() == defaultSearchText) {
      $(this).addClass("selected-search");
      $(this).removeClass("default-search");
      $(this).val("");
    }
  });
  
  $("#searchbox").keypress(function(e) {
    if(e.which == 13) {
      submitSearchForm();
    }
          
  });
  
  $(".listing-container-mark").click(function() {
    MAMASWAP.handleContainerToggle($(this));
    return false;
  });
  
  // filter dropdown
  $(".filterLink").hover(function() {
    $("#filterPop").show();
    return false;
  });
  
  $("#filterPop #inner").hover(function() {
  
  },function () {
    $("#filterPop").hide();
    return false;
  });
  
  // let's get rid of the pagination if there are no results
  if ($(".pagination").text() == "")
  {
    $(".apple_pagination").addClass("paginationGhost");
    $(".apple_pagination").removeClass("apple_pagination");
  }
  

  // selecting rather than dog-earing
  $(".listing-container").click(function() {
    // shift down if necessary
    if ($(window).scrollTop() > 180)
    {
      $("#detailViewWrapper").animate({ 
        top: $(window).scrollTop()-150
      }, 500 );
       
    }else{
     
      $("#detailViewWrapper").animate({ 
        top: $(window).scrollTop()-17
      }, 500 );
    }

    // only one thing should be visible at a time
    $(".listing-container").removeClass("listing-selected");
    $(this).addClass("listing-selected");
    // console.log('let us color');
  });

  $(".markIt").click(function() {
    // only one thing should be visible at a time
    $(".listing-selected").toggleClass("listing-selected");
  });

  // on first load, pre-select an item
  $("#fresh a:first").click();
});

jQuery.savedListings = function(id, remove) {
  if(typeof remove != 'undefined') { // remove saved listing id from cookie
    var c = $.cookie(cookiename);
    var savedIds = c == null ? [] : c.split(",");
    var id_index = $.inArray(id, savedIds);
    if(id_index > -1) {
      savedIds.splice(id_index,1);
    }
    if(savedIds.length > 0) {
      $.cookie(cookiename, savedIds.join(","), {expires: cookieexpire, path: '/'});
    } else {
      $.cookie(cookiename, null, {path: '/'});
    }
    return savedIds;
  } else if (typeof id != 'undefined') { // add saved listing id to cookie
    c = $.cookie(cookiename);
    savedIds = c == null ? [] : c.split(",");
    if($.inArray(id, savedIds) < 0)
    {
      $.merge(savedIds, [id]);
    }
    $.cookie(cookiename, savedIds.join(","), {expires: cookieexpire, path: '/'});
    return savedIds;
  } else { // return listing ids
    c = $.cookie(cookiename);
    return c == null ? [] : c.split(",");
  }
};

var MAMASWAP = function() {
  var myPhrases = [
    "fetching!",
    "grabbing!",
    "loading!",
    "hang on a sec...",
    "ready in 3...2...1...",
    "here goes!",
    "kazam!",
    "please wait...",
    "stand by...",
    "ready in two shakes of a stick!",
    "patience is a virtue",
    "if you're happy and you know it, clap your hands!"
  ];

  function updateAllSelectedCount() {
    $('.update-me').each(function() {
      $(this).text(selectedCount);
    });
  }
  
  function toggleMarked(mark, listingId) {
    if(mark) {
      $.savedListings(listingId, true);
      selectedCount -= 1;
    } else {
      $.savedListings(listingId);
      selectedCount += 1;
    }
  }

  function clearIncompletePurchaseCookie() {
    $.cookie("incomplete_purchase", null, {path: '/'});
  }
  

  
  return {
    throwCuteMessage: function() {
      randNum = Math.floor(Math.random() * myPhrases.length);
      $("#currentItem").text(myPhrases[randNum]);
      $("#currentItem").addClass("loading");
      $("#currentItem").removeClass("salmon");
    },
    
    hideCuteMessage: function() {
     $("#currentItem").removeClass("loading");
     $("#currentItem").addClass("salmon");
    },
    
    hackyHover: function(that) {
      // I couldn't get the buttons to register jquery's hover state, so I'm hand-crafting the function. bah.
      if (that.src.indexOf('_h.png') !=-1)
      {
        that.src = that.src.replace( /_h\.png$/, '.png' );
      }else{
        that.src = that.src.replace( /\.png$/, '_h.png' );
      }
    },

    handleMarkToggle: function(that) {
      that = $(that);
      var keyId = that.parent().attr("id").replace("listing_", "");
      var relatedThumb = $("#thumb_" + keyId);

      toggleMarked(
        ($.inArray(keyId, $.savedListings()) > -1),
        keyId
      );
      
      if ($("#saveForLater").attr("src").indexOf("save") != -1)
      {
        // console.log("true - found save");
        $("#saveForLater").attr("src", "/images/button_unmark_h.png");
      } else {
        // console.log("false - no save");
        $("#saveForLater").attr("src", "/images/button_saveForLater_h.png");
      }
      
      // console.log($("#saveForLater").attr("src"));
      
      relatedThumb.toggleClass("listing-marked");
      updateAllSelectedCount();
    },
    
    handleContainerToggle: function(that) {
      var keyParent = that.parent();
      var id = keyParent.attr("id").replace("thumb_", "");

      toggleMarked(
        keyParent.hasClass("listing-marked"),
        id
        );

      keyParent.toggleClass("listing-marked");
      updateAllSelectedCount();
    },

    showBuyConfirmation: function(listingTitle, listingCost, listingId) {
      $("#buy_confirm_dialog_listing_title").html(listingTitle);
      $("#buy_confirm_dialog_listing_price").html(listingCost);
      $("#buy_confirm_dialog").dialog("open");
      $("#buy_confirm_dialog_listing_token").text(listingId);
    },

    makePurchase: function(email, title, token, price, returnUrl) {
      $("#pp_business").val(email);
      $("#pp_item_name").val(title);
      $("#pp_item_number").val(token);
      $("#pp_item_amount").val(price);
      $("#pp_return_url").val(returnUrl);
      /* Set a cookie to track that the user has been sent to PP but has not yet completed the purchase.
       * This will get cleared on the purchase completion page. */
      $.cookie("incomplete_purchase", token, {expires: cookieexpire, path: '/'});
      document.getElementById("purchase_form").submit();
    },
    
    redirectorSubmit: function(form) {
      $("#purchase_form").submit();
    },

    handleIncompletePurchase: function() {
      var token = $.cookie("incomplete_purchase");
      if(document.location.pathname.indexOf("complete_purchase") > 0) {
        clearIncompletePurchaseCookie();
      } else {
        if(token && token.length > 0) {
          var message = "It looks like you haven't quite completed your recent purchase.  Please click ";
          message += "<a href=\"/complete_purchase/" + token + "\">here</a>";
          message += " to finish your last step.";
          $(".main-content").prepend("<div class='flash-notice'>" + message + "</div>");
          /* clearIncompletePurchaseCookie(); */	
        }
      }
    },

    clearIncompletePurchase: function() {
      clearIncompletePurchaseCookie();
    }
  };
}();
