$.extend($.expr[':'], {
  inView: function (a) {
    var st = (document.documentElement.scrollTop || document.body.scrollTop),
      ot = $(a).offset().top,
      wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
    return (ot > st || ot + 544 > st) && (ot < st + wh);
  }
});

function lazyLoad () {
  // $("div.image:empty:inView").each(function(){
  $("div.image:empty").each(function(){
    $(this).siblings("div.right, div.desc").click();
  });
}

var myScrollTimer;
function scrollEventHandler(e){
  clearTimeout(myScrollTimer);
  myScrollTimer = setTimeout(lazyLoad, 500);
  //cancel the event if desired using
  //something like this below
  if (window.event) {
    window.event.returnValue = false;
    window.event.cancelBubble = true;
  } else if (e && e.preventDefault && e.stopPropagation) {
    e.preventDefault();
    e.stopPropagation();
  }
}

function prepare(){
  $("div.white-box, div.info").each(function(){
    var p = $(this), left = $("div.left", p), right = $("div.right", p), count = $("div.image", p).data("images").count;
    p.mouseover(function(){
      if ($("div.image", p).data("images").active > 1) {
        left.stop().animate({left: "-1px"}, 50);
      }
      if (!$("div.image", p).is(":empty") && $("div.image", p).data("images").active < count) {
        right.stop().animate({right: "-1px"}, 50);
      }
      
      if (count > 1 && $("div.image", p).data("images").active < count && !$("div.image", p).is(":empty") && right.css("right") === "-54px") {
        right.stop().animate({right: "-1px"}, 50, "linear");
      }

    }).mouseout(function(){
        left.stop().animate({left: "-54px"}, 50, "linear");
        right.stop().animate({right: "-54px"}, 50, "linear");
    });
  });

  $("div.image").each(function(){
    var d = $(this), obj = d.data("images"), i = obj.count || 0;
    obj.active = 0;
    obj.items = 0;
    d.width(1190 * i);
  });
}


// window.onscroll = function (evt) {
//   scrollEventHandler();
// };

$(window).load(function(){

	function scrollTo(el, f){
		try {
			var offset = $(el).offset().top;
			var tag = self.navigator.userAgent.toLowerCase().match("safari") ? "html, body" : "html";
			$(tag).scrollTop() === offset ? $(f) : $(tag).animate({ scrollTop: offset }, 1000, f);
		} catch(e) {}
		return false;
	}


  $("#menu a, #top-container a").hover(function(){
			$("span", this).fadeIn("fast");
		}, function(){
      $("span", this).fadeOut("fast");
	});


	$("#menu a:not(.noscroll)").click(function(){
		var a = $(this);
		if (a.attr("href") && a.attr("itemprop")) {
			if ($("#" + a.attr("itemprop")).hasClass("box") && $("#" + a.attr("itemprop")).length) {
					scrollTo("#" + a.attr("itemprop"));
			} else {
				$.ajax({
					url: a.attr("href"),
          type: 'post',
          beforeSend: function(){
						$("#main").prepend("<p id='preload'><img src='gfx/layout/preload2.gif' alt='' /></p>");
						$("#preload").show();
					},
					success: function(re){
            var div = $("#main div.container:first");
            div.height(div.outerHeight());
            div.attr("id", a.attr("itemprop")).html($("<div>", {
							css: {
								display: "none"
							},
							html: re,
							id: "container-ajax"
							})
						);

						$("#container-ajax").fadeIn(function(){
              $(this).children().unwrap();
						});
						$("#preload").fadeOut(function(){
							$(this).remove();
							scrollTo("#" + a.attr("itemprop"));
						});
						prepare();
						lazyLoad();
						div.height("auto");

					},
					error: function(){
						$("#preload").remove();
						alert("Wystąpił problem w połączeniu z serwerem.\nSpróbuj później.");
					}
				});
			}
		} else if (a.is("[href^=#]") && !a.attr("itemprop")) {
			scrollTo(a.attr("href"));
		}
		return false;
	});


	if ($.fn.validate && $("form").length) {
		$("#kontakt form, #comments form").validate({
			rules: {
			  name: "required",
			  email: {
					required: true,
					email: true
				},
				message: "required",
				comment: "required"
			},
			errorPlacement:	function(error, element) {
     		$("#ajax").remove();
        return false;
  		},
  		unhighlight: function(element, errorClass) {
        $(element).removeClass("error");
  		},
  		submitHandler: function(form){
				var f = $(form);
				$.ajax({
					url: f.attr("action"),
					data: f.serialize(),
          type: 'post',
					beforeSend: function(){
						$("#ajax", f).remove();
					},
					success: function(re){
						$(":text, textarea", f).val("");
						$("#submit", f).prepend($("<div>", {
							id: "ajax",
							html: re
							})
						);
						$("#ajax", f).fadeIn();
					},
					error: function(){
						alert("Wystąpił problem w połączeniu z serwerem.\nSpróbuj później.");
					}
				});
				return false;
			}
		});
	}


  $("div.left").live("click", function(){
    var div = $(this).siblings("div.image"), obj = div.data("images");
    div.data("busy", true);

    if ((obj.items && obj.active) > 1) {
      div.children().hide();
      obj.active = obj.active - 1;
      div.children().eq(obj.active - 1).fadeIn();


      if (obj.active > 1) {
        div.prev().prev().html("<p><</p><span>" + (obj.active - 1) + "/" + obj.count + "</span>");
      }

      div.prev().html("<p>></p><span>" + (obj.active + 1) + "/" + obj.count + "</span>");

      if (obj.active === 1) {
        div.prev().prev().stop().animate({left: "-54px"}, 50, "linear");
      } else if (obj.active < obj.count || div.prev().css("right") === "-54px") {
        div.prev().stop().animate({right: "-1px"}, 50, "linear");
      }

    }
    div.data("busy", false);
  });

  $("div.right").live("click",function(){
    var div = $(this).siblings("div.image"), obj = div.data("images");
    if (div.data("busy") === true || obj.active === obj.count) {
      return false;
    }
    div.data("busy", true);

    var path = "gfx/projects/" + obj.year + "/" + obj.name + "/";

    div.children().hide();
    if (obj.items === obj.count) {
      div.children().eq(obj.active).fadeIn();
      obj.active = obj.active + 1;

      div.prev().prev().html("<p><</p><span>" + (obj.active - 1) + "/" + obj.count + "</span>"); // left
      if (obj.active < obj.count) {
        div.prev().html("<p>></p><span>" + (obj.active + 1) + "/" + obj.count + "</span>");  // right
      }

      if (obj.active === obj.count) {
        div.prev().stop().animate({right: "-54px"}, 50, "linear");
      } else if (obj.active > 1 && div.prev().prev().css("left") === "-54px") {
        div.prev().prev().stop().animate({left: "-1px"}, 50, "linear");
      }

      div.data("busy", false);
    } else {
      div.closest(".white-box").removeClass("ok");
      var img = new Image();
      $(img).load(function(){
        div.closest(".white-box").addClass("ok");
        div.append(this);
        $(this).fadeIn();
        if (!div.siblings("div.info").length) {
          div.next(":not(:visible)").fadeIn();
        }
        obj.items = obj.items + 1;
        obj.active = obj.active + 1;

        div.prev().prev().html("<p><</p><span>" + (obj.active - 1) + "/" + obj.count + "</span>"); // left
        if (obj.active < obj.count) {
          div.prev().html("<p>></p><span>" + (obj.active + 1) + "/" + obj.count + "</span>");  // right
        }

        if (obj.active === obj.count) {
          div.prev().stop().animate({right: "-54px"}, 50, "linear");
        } else if (obj.active > 1 && div.prev().prev().css("left") === "-54px") {
          div.prev().prev().stop().animate({left: "-1px"}, 50, "linear");
        }

        div.data("busy", false);
      }).attr("src", path + (obj.active + 1) + ".jpg");
    }
    
  });
  
  $("div.desc").live("click", function(){
    var div = $(this).prev(), obj = div.data("images");
    $(this)
      .hide().after('<div class="info"><h3>' + obj.title + '</h3><p>' + obj.desc + '</p><img src="gfx/layout/bg-info-close.png" class="info-close" alt="" /></div>')
      .next().fadeIn();
  });

  $("img.info-close").live("click", function(){
    var desc = $(this).parent().prev();
    $(this).parent().remove();
    desc.fadeIn();
  });
  

  prepare();
  lazyLoad();

});
