(function($) {
  $.fn.oembed.getPhotoCode = function (url, oembedData) {
      var code, alt = oembedData.title ? oembedData.title : '';
      alt += oembedData.author_name ? ' - ' + oembedData.author_name : '';
      alt += oembedData.provider_name ? ' - ' + oembedData.provider_name : '';
      code = '<a href="' + url + '" target=\'_blank\'><span class="rollover"></span><img style="width:'+oembedData.width+'px;height:'+oembedData.height+'px;" width="'+oembedData.width+'" height="'+oembedData.height+'" src="' + oembedData.url + '" alt="' + alt + '"/></a>';
      if (oembedData.html)
          code += "<div>" + oembedData.html + "</div>";
      return code;
  };
  
  var fetchedImages = [], wh, dh, images = [], pagenumber = 2, imagesPerPage = 3, noMoreImages = false;
  
  window.jsonFlickrFeed = function(data) {
    fetchedImages = fetchedImages.concat(data.items);
    
    $("#main").trigger("imagesFetched");
    
  }
  
  function waitLoadAndAnimate() {
    var $img = $(this).find("img"),
        img = $img[0];
    images.push($img);
    $img.data({offset_top: $img.offset().top});
    if(!img) {
      $(this).remove();
      return;
    }
    if(img.complete || img.readyState == "complete") {
      animateImg.call(img);
      return;
    }
    $img.load(animateImg).bind("readystatechange",function() {
      if(this.readyState == "complete") {
        animateImg.call(this);
      }
    });
  }
  
  function animateImg() {
    var img = $(this).unbind("load readystatechange");
    img.closest("article.item").removeClass("loading transparent").stop(true,true).css({opacity: 1});
    /*
    var width = $(this).attr("width"),
        height = $(this).attr("height");
    $(this).closest(".item").css({width:width,height:height});
    $(this).css({width:0,height:0}).animate({
      opacity:1,
      width: width,
      height: height,
      marginTop: -height/2,
      marginLeft: -width/2
    },{
      duration: 500,
      easing: "easeOutBack",
      specialEasing: {
        opacity: "easeOutQuad"
      }
    });
    */
    if(img.data().offset_top>(wh+$(window).scrollTop())) {
		detectOnBottom();
      return;
    }
    if($("html").hasClass("csstransitions")) {
      img.transition({opacity:1},1000,'cubic-bezier(0.250, 0.460, 0.450, 0.940)');
    } else {
      img.animate({opacity:1},{easing:"easeOutQuad",duration:1000});
    }
	detectOnBottom();
  }
  
  function fetchImages(num) {	
    $("#main").unbind("imagesFetched").bind("imagesFetched",function() {
      renderImages(num);
    });
    $.ajax({
      url: '/wp-admin/admin-ajax.php?action=getindexposts&pagenumber='+pagenumber,
      success: function(data) {
        if(!data) {
          noMoreImages = true;
          $("#main").trigger("imagesFetched");
          return;
        }
        pagenumber++;
        fetchedImages = fetchedImages.concat($(data).filter("article").get());
        $("#main").trigger("imagesFetched");
      }
    });
    /*$.ajax({
      url : "http://api.flickr.com/services/feeds/photos_public.gne?format=json",
      dataType: "jsonp",
      jsonp: false,
      jsonpCallbackString: "jsonFlickrFeed"
    });*/
  }
  
  function renderImages(num) {
    if(fetchedImages.length<num && !noMoreImages) {
      fetchImages(imagesPerPage);
      return;
    }
    var index = 0;
    while(index++<num && fetchedImages.length) {
      var data = $(fetchedImages.shift());
          //div = $("<article class='loading item'>"),
          //link = $(data.description).find("a").eq(1),
          //img = link.prepend("<span class='rollover'>").find("img"),
          //w = img.attr("width"),
          //h = img.attr("height");
      /*
      if(w==240) {
        img.width(500).attr("width",500);
        img.height(Math.round(h*500/240)).attr("height",Math.round(h*500/240));
      } else {
        img.height(500).attr("height",500);
        img.width(Math.round(w*500/240)).attr("width",Math.round(w*500/240));
      }
      img.attr("src",img.attr("src").replace(/_m/,""));
      link.appendTo(div);
      */
      data.addClass("loading").appendTo("#main section");
      if(!$("html").hasClass("csstransitions")) {
        bindRollOverNoTransition(data);
      }  
      pulseBackground(data);
      waitLoadAndAnimate.call(data.find("a").get());
      dh = $(document).height();
    }
    fetching = false;
  }
  
  function pulseBackground(div) {
    var loop_func = function(next) {
      var self = $(this);
      if(self.hasClass("loading")) {
        if($("html").hasClass("csstransitions")) {
          self.toggleClass("transparent").delay(1000).queue(loop_func);
        } else {
          self.animate({opacity:div.css("opacity")==1?0.5:1},{easing:"easeOutQuad",duration:1000});        
        }
        self.queue(loop_func);
      } else {
        self.css({opacity: 1});
      }
      next();
    }
    if($("html").hasClass("csstransitions")) {
      div.toggleClass("transparent").delay(1000);
    } else {
      div.animate({opacity:div.css("opacity")==1?0.5:1},{easing:"easeOutQuad",duration:1000});
    }
    div.queue(loop_func);
  }
  
  var fetching = false;
  function detectOnBottom(e) {
    while(images.length) {
      var top = images[0].data().offset_top;
      if(top<=(wh+$(window).scrollTop()) && !images[0].closest(".item").hasClass("loading")) {
        var img = images.shift();
        if($("html").hasClass("csstransitions")) {
          img.transition({opacity:1},1000,'cubic-bezier(0.250, 0.460, 0.450, 0.940)');
        } else {
          img.animate({opacity:1},{easing:"easeOutQuad",duration:1000});
        }
      } else {
        break;
      }
    }
    if(!fetching && wh+$(window).scrollTop()>(dh-600)) {
      fetching = true;
      renderImages(imagesPerPage);
    }
  }
  
  
  function bindRollOverNoTransition(item) {
    item.find("a").hover(function() {
      $(this).find("span.rollover").css({opacity: 0}).animate({opacity:1},{easing:"easeOutQuad",duration:1000});
    }, function() {
      $(this).find("span.rollover").animate({opacity:0},{easing:"easeOutQuad",duration:1000});      
    });  
  }
  
  function bindHomeActions() {
    //renderImages(15);
    wh = $(window).height();
    dh = $(document).height();
    $("article.item").each(function() {
      pulseBackground($(this));
      waitLoadAndAnimate.call(this);
    });
    $(window).scroll(detectOnBottom).resize(function() {
      wh = $(window).height();
    });
    if(!$("html").hasClass("csstransitions")) {
      bindRollOverNoTransition($("article.item"));
    }  
  }
  
  function slideIntoView($new,$old) {
    var wrapper = $new.find("div.imageWrapper").css({opacity: 0}),
        img = $new.find("img").css({opacity: 0});
    $new.find('div.comments').css({opacity: 0});
    $new.find('h1,div.imageOnly_headings h2,h3,ul.imageTags').css({opacity: 0});
    $("#wrapper").closest("section").scrollTo($old,{axis: "x"})
    .scrollTo($new,{axis: "x", easing:"easeOutQuad", duration: 1000, onAfter: function() {
      $new.find('div.comments,h1,div.imageOnly_headings h2,h3,ul.imageTags').fadeTo('fast',1);
      sliding = false;
    }});
    if($("html").hasClass("csstransitions")) {
      wrapper.transition({opacity:1},1000,'cubic-bezier(0.250, 0.460, 0.450, 0.940)',function() {
        img.transition({opacity:1},1000,'cubic-bezier(0.250, 0.460, 0.450, 0.940)');
        if (window.showTagsOnFrontendImage && loadedImage)
			    showTagsOnFrontendImage();
      });
    } else {
      wrapper.animate({opacity:1},{easing:"easeOutQuad",duration:1000,complete:function() {
        img.animate({opacity:1},{easing:"easeOutQuad",duration:1000});
        if (window.showTagsOnFrontendImage && loadedImage)
			    showTagsOnFrontendImage();
      }});
    }
    updateSocialUrl($new.data("permalink"));
  }
  
  var loadedImage = false;
  function loadContributorPost(index, oldindex, addMethod) {
    var $art = $('#wrapper article[data-currentcatindex="'+index+'"]')
        $oldPost = $('#wrapper article[data-currentcatindex="'+oldindex+'"]');
    addMethod = addMethod || "append";
    if(!$art.length) {
      loadedImage = true;
      $.ajax({
        url: "/wp-admin/admin-ajax.php?action=getnthpostincategory&categoryid="+wp_post_category_id+"&postnumber="+index,
        success: function(data) {
          var $data = $(data);
          $("#wrapper")[addMethod]($data);
          $data.find('input, textarea').placeholder();
          slideIntoView($data,$oldPost);
        }
      });
    } else {
      loadedImage = false;
      addMethod = (addMethod == "append")?"insertAfter":"insertBefore";
      $art[addMethod]($oldPost);
      slideIntoView($art,$oldPost);
    }
  }

  function updateSocialUrl(url) {
    var iframe = $("aside div.fb-like iframe"),
        src = iframe.attr("src"),
        new_src = src.replace(/href=[^&]+/,"href="+encodeURIComponent(url));
    iframe.attr("src",new_src);
    
    iframe = $("aside iframe.twitter-share-button");
    src = iframe.attr("src");
    if(src.match(/url=[^&]+/)) {
      new_src = src.replace(/url=[^&]+/,"url="+encodeURIComponent(url));
    } else {
      new_src = src+"?url="+encodeURIComponent(url);
    }
    iframe.attr("src","").attr("src",new_src);
  }
  
  function prepareSliding(oldIndex,postIndex,method) {
    var $art = $('article[data-currentcatindex="'+oldIndex+'"]');
    $art.find('h1,div.imageOnly_headings h2,h3,ul.imageTags,div.comments').fadeTo('fast',0).promise().done(function() {
      loadContributorPost(postIndex, oldIndex, method);
      $("#currentCatIndex").text(postIndex);      
    });  
  }
  
  var sliding = false;
  function bindContributorActions() {
    //wp_post_category_id
    var postIndex, oldIndex,
        postCount = parseInt($("#currentCatCount").text());
    $("#wrapper").closest("section").scrollTo(0);
    $("#prev").click(function() {
      if(postCount==1 || sliding) return false;
      sliding = true;
      oldIndex = parseInt($("#currentCatIndex").text());
      if(oldIndex==1) {
        postIndex = postCount;
      } else {
        postIndex = oldIndex-1;
      }
      prepareSliding(oldIndex,postIndex,"prepend");
      return false;
    });
    $("#next").click(function() {
      if(postCount==1 || sliding) return false;
      sliding = true;
      oldIndex = parseInt($("#currentCatIndex").text());
      if(oldIndex==postCount) {
        postIndex = 1;
      } else {
        postIndex = oldIndex+1;
      }
      prepareSliding(oldIndex,postIndex,"append");
      return false;
    });
  }
  
  $(function() {
    if($("body").hasClass("home")) {
      bindHomeActions();
    } else if ($("body").hasClass("single") || $("body").hasClass("category")) {
      bindContributorActions();
    }

    $('div.text div.image iframe').each(function() { 
    
      var youtubeStart = 'http://www.youtube.com/';
      var iframeURL = $(this).attr('src');
      
      if (iframeURL.substr(0, youtubeStart.length) === youtubeStart)
        $(this).attr('src', iframeURL + '&wmode=transparent');
  
    });
	
    $('#searchForm').hover(function() {
      $('html:not(.oldie) #search_submit').fadeIn();
      $('html.oldie #search_submit').show();
      $('#searchBg').css({opacity:1, background: '#FFF'});
      $(this).find('input.placeholder').css({color: '#000'});
    }, function() {
      $('html:not(.oldie) #search_submit').fadeOut();
      $('html.oldie #search_submit').hide();
      $('#searchBg').css({opacity:0.2, background: '#C4C4C4'});
      $(this).find('input.placeholder').css({color: '#FFF'});
    });
    $('#search_submit_link').click(function() {
      $('#searchform').submit();
    });
    
    $('h4.commentsAreaTitle a.commentBox').live('click', function() {
      var comment = $(this).closest("div.comments").find("div.commentsArea");
      if (comment.css('display') === 'none')
        comment.fadeIn();
      else
        comment.fadeOut();
        
      return false;
    });

	$('h4.commentsAreaTitle .comments_addinfo a').live('click', function() {
		
		var comment = $(this).closest("div.comments").find("div.commentsArea");
		
		if (comment.css('display') === 'none')
	        comment.fadeIn();
	
		return true;
	});
	
	  $('input, textarea').placeholder();
	  
	  $.ifixpng(window.pixel);

		if (window.showTagsOnFrontendImage)
			showTagsOnFrontendImage();

	  $('hgroup').ifixpng();
	  
	  $("a.out").attr("target","_blank");
  });

	//$(window).load(function() {
		// show image tags on collection image
	//});
	
	window.validateAndSubmitForm = function (postID)
	{
		if (postID.length < 1)
			return;
			
		$('div.respond p.errorMessage').remove();
			
		// validation
		// ...
		var validated = true;
		var name = $('#author-' + postID).val();
		var email = $('#email-' + postID).val();
		var comment = $('#comment-text-' + postID).val();
		
		function isValidEmailAddress(email)
		{
			if (email.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) != -1)
				return true;
			else
				return false;
		}
		
		if (comment.length < 1)
		{
			// append message
			$('#comment-text-' + postID).after('<p class="errorMessage">Please type in a comment.</p>');
			
			validated = false;
		}
		
		if (name.length < 1)
		{
			// append message
			$('#author-' + postID).after('<p class="errorMessage">Please insert your name.</p>');
			
			validated = false;
		}
		
		if (email.length < 1)
		{
			// append message
			$('#email-' + postID).after('<p class="errorMessage">Please insert your email address.</p>');
			
			validated = false;
		}
		else {
			
			// email address validation
			if (!isValidEmailAddress(email))
			{
				// append message
				$('#email-' + postID).after('<p class="errorMessage">Invalid email address.</p>');

				validated = false;
			}
		}
		
		// submit
		if (validated)
			$('#submit-' + postID).click();
	}
  
})(jQuery);
