$(document).ready(function() {
  var position;
  var new_id;
  var hash;
  var fade = false;

  $("img[id^='thumb_']").bind("click", function() {
    if (position != 0 && position != 1) {
      position = 0;
    } else if (position == 0) {
      position = 1;
    } else {
      position = 0;
    }

    var id = $(this).attr("id").replace('thumb_', '');
    var to_replace_id = $("img", $("div.header_split").children("div").eq(position)).attr("id").replace('large_', '');

    $.ajax({
      type: "POST",
      dataType: "json",
      data: 'id='+ id,
      url: "/ajax/site-get-image2/",
      success: function(req) {
        if (req.image) {
          if (req.id != to_replace_id) {
            $("div.header_split").children("div").eq(position).find("img").attr("src", "");
            $("div.header_split").children("div").eq(position).find("img").hide();

            fade = true;
          }

          new_id = req.id;
          hash = req.image;

          process();

        }
      }
    });
  });

  function process() {
    if (fade) {
      $("span.loading", $("div.header_split").children("div").eq(position)).remove();

      $("img", $("div.header_split").children("div").eq(position)).attr("id", new_id);
      $("img", $("div.header_split").children("div").eq(position)).attr("src", hash);

      $("img", $("div.header_split").children("div").eq(position)).one("load", function() {
        $("img", $("div.header_split").children("div").eq(position)).fadeIn(1500);
      });
    }
  }

  /* COLLECTION SLIDER */
  var div = document.getElementById('images');
  var totalWidth = div.scrollWidth;

  $("div.previous").bind("click", function() {
    slideLeft();
  });

  $("div.next").bind("click", function() {
    slideRight();
  });

  function slideLeft() {
    div.scrollLeft -= 137;
  }

  function slideRight() {
    div.scrollLeft += 137;
  }

});