(function($){

 $.fn.bigClickNYC = function(selector) {
 	var selector = selector || "a";
 	return this.each(function(){
 		$(this).click(function(e){
 			e.preventDefault();
 			if($(this).is(selector))
 				$(window).attr("location", $(this).attr("href"));
 			else if($(this).find(selector).length > 0)
 				$(window).attr("location", $(this).find(selector).attr("href"));
 			else{
 				//do nothing NYC!
 			}
 		});

		$(this).mouseover(function(e){
			$(this).css({"cursor": "pointer"})
		})
 	});
 }

})(jQuery);

(function($){
  $.fn.startLoading = function() {
    return this.each(function(){
      $(this).css({position: 'relative'});
      var loadingDiv = $('<div class="loading"></div>');
      loadingDiv.css({position: 'absolute', top: 0, left: 0, height: $(this).outerHeight(), width: $(this).outerWidth()});
      $(this).append(loadingDiv);
    });
  }
  
  $.fn.stopLoading = function() {
    return this.each(function(){
      $(this).find('.loading').remove();
    })
    
  } 
})(jQuery);

(function($){
  $.fn.present = function(){
    return this.length > 0;
  }
})(jQuery);

$.ajaxSetup({ 
  'beforeSend': function(xhr,settings) {
    if(settings.url.indexOf("format") == -1){
      $.ajax($.extend(this,{
          type: "GET",
          url: settings.url.indexOf("?") != -1 ? settings.url + "&format=js" : settings.url + "?format=js"
        }));
      return false;
    }
  }
});

var ProjectModal = {
  ajaxRefresh: function(url) {
    $('#modal .post_slideshow').cycle('destroy');
    $('#modal').startLoading();
    var beforeHeight = $('#modal').height();
    var beforeLiHeight = $('#modal .post_slideshow').height();
    $.get(url, function(response){
      $('#modal').stopLoading();
      var imageLoaded = false;
      var newModal = $(response).find('#modal_inner');
      $(newModal).find('.post_slideshow').css({height: beforeLiHeight});
      var firstImage = $(response).find('.post_slideshow li:first img');
      firstImage.bind('load', function(e){
        $('#modal .post_slideshow').animate({height: $('#modal .post_slideshow li:first').height()});
          imageLoaded = true;
      });
      $('#modal #modal_inner').replaceWith(newModal);
      $('#modal .post_slideshow').cycle({
        fx: 'scrollLeft',
        next: '#modal .cycle_next',
        before: function(curr, next, opts, flag) {
          var targetHeight = $(next).height();
          if(imageLoaded)
            $(next).parent('.post_slideshow').animate({height: targetHeight});
         },
        after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
          $('#modal .current_photo').html(options.currSlide + 1);
        },
        timeout: 0
      });
    })
  }
}

$(function() {
  
  $('.main_nav > li').hover(function(e){
    $(this).addClass('open');
  },
  function(e){
    $(this).removeClass('open');
  });
  
  //animate project slides on index
  if($('.home #all').present()) {
    var source = $('.home #all');
    var target = $('<ul class="showcase_list" id="target"></ul>');
    source.hide().before(target);
    $('#target').quicksand(source.find('li'));
  }
  
  if($('#project_slideshow').length > 0){
    $('#project_slideshow').cycle({
      fx: 'scrollHorz',
      prev: '#arrow_left',
      timeout: 8000,
      next: '#arrow_right'});
  }
  
  
  $('#modal a[rel="prev"], #modal a[rel="next"]').live('click', function(e){
    e.preventDefault();
    ProjectModal.ajaxRefresh($(e.target).attr('href'));
  });
  
  $(document).bind("keydown", function(e){
    switch(e.keyCode){
      case 37:
        if($('#modal').present() && $('#modal a[rel="prev"]').present())
          ProjectModal.ajaxRefresh($('#modal a[rel="prev"]').attr('href'));
        break;
      case 39:
        if($('#modal').present() && $('#modal a[rel="next"]').present())
          ProjectModal.ajaxRefresh($('#modal a[rel="next"]').attr('href'));
        break;
    }
  });
  
  $('.showcase_list li').live("click", function(e){
    
    e.preventDefault();
    var clickIntent = $(e.target).parents('li:first');
    clickIntent.startLoading();
    $.get($(this).find("a").attr("href"), function(response){
      clickIntent.stopLoading();
      var firstImage = $(response).find('.post_slideshow li:first img');
      var imageLoaded = false;
      firstImage.bind('load', function(e){
        $('#modal .post_slideshow').animate({height: $('#modal .post_slideshow li:first').height()});
          imageLoaded = true;
      });
      
      if($('#modal').present()){
        $('#modal').dialog('destroy');
        $('#modal').replaceWith(response);
      }
      else {
        $('body').append(response);
      }
      
      $("#modal").dialog({
           minHeight: 417,
           resizable: false,
           position: 'center',
           width: 670,
           modal: true,
           open: function(event, ui) {
             $(this).parents('.ui-dialog').animate({top: $(window).scrollTop() + 50});
           },
           close: function(){
             $('.post_slideshow').cycle('destroy');
           }
      });
      
      $('.post_slideshow').cycle({
        fx: 'scrollLeft',
        next: '#modal .cycle_next',
        before: function(curr, next, opts, flag) {
          var targetHeight = $(next).height();
          if(imageLoaded)
            $(next).parent('.post_slideshow').animate({height: targetHeight});
         },
        after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
          $('#modal .current_photo').html(options.currSlide + 1);
        },
        timeout: 0
      });
    })
  });

  $('.ui-widget-overlay').live("click", function(e){
    $("#modal").dialog('close');
  });

  $('.filters').buttonset();

  $('.filters input').live('change', function(e){
    var form = $(e.target).parents('form');
    var action = [form.attr('action'), '?', form.serialize()].join('');
    var selector = '#' + $(e.target).val() + ' li';
    $('#project_data').hide();
    if($('#source').length == 0)
      $('.showcase_list:first').attr('id', 'source');
    if($(selector).length > 0)
      $('#source').quicksand($(selector)); 
    else 
      $.get(action, function(response){
        $('#project_data').append(response);
        $('#source').quicksand($(selector)); 
      });
    })

});