var blockSize = 49;
var animTime = 95;
$(document).ready(function() {

	document.getElementById("all").checked = true;

	$(window).bind("resize", function() {
								scrollToSelected();	  
									  });
	
	
	setInterval("physics()",animTime);
	
	$("#blockClear").bind("click", function() {
											 $(".block").each(function(i)
												{	$(this).remove();	})
											 });
	

		$('.assetDialog').dialog({
			autoOpen: false,
			show: 'drop',
			hide: 'drop',
			width: 520,
			resizable: false
		});
		

		bindButtons();


	
	$(".bSpawner").draggable({helper:'clone'});
	$("#panelContainer").droppable({	accept: ".bSpawner",
										drop: function(e,ui)
										{
											var t = $(ui.draggable).clone();
											t.attr("class","block");
											t.css(ui.position);
											$(this).append(t);
											t.draggable({ start: function(event, ui) 
														  { 
														  	t.attr("v",0);
															t.attr("drag",0);
														  },
														  stop: function(event, ui)
														  {
															t.attr("drag",1);  
														  }
														});
										}
								   
								   });

	//get all link with class panel
	$('a.nav').click(function() {
		var dest = "#pn_"+$(this).html().toLowerCase();
		setPage(dest);
		$("#panelContainer").scrollTo(dest, 850, {easing:'easeOutBack'} );
		
	});

	$(".panel h1").click(function() {
			$("#panelContainer").scrollTo($(this).parent(), 850, {easing:'easeOutBack'} );					 			setPage('#'+$(this).parent().attr('id'));

								  });
	
	$('#source').quicksand( $('#destination li') );
	scrollToSelected();	 
	
		$('#filter').buttonset();
		
		$("#servicesAccordian").accordion();



});

function bindButtons()
{
	$('#applications li').click(function(e) {
		var dialog = "#dlg"+e.currentTarget.id.substr(3);
		var title = e.currentTarget.children[1].innerHTML;
		$(dialog).dialog('option', 'title', title );
		$(dialog).dialog('open');
		
		return false;
	});
}

function scrollToSelected()
{
	$("#panelContainer").stop();
	if(getPage() != '')
	{
		$("#panelContainer").scrollTo(getPage(), 850, {easing:'easeOutBack'} );	
	} else {
		$("#panelContainer").scrollTo("#pn_play", 850, {easing:'easeOutBack'} );	
		setPage("#pn_play");
	}
}

var options = { path: '/', expires: 10 };

function setPage(page)
{
	$.cookie('page', page, options);
}

function getPage()
{
	return $.cookie('page');
}

function maxHeightBelow(x,y)
{
	var blocks = 0;
	$(".block").each(function(i,v)
	{	
		if(($(v).offset().top > y) && ($(v).offset().top < ($(window).height()-(blocks*(blockSize-1.5)))) )
		{
			if( (x+blockSize)>=$(v).offset().left && x<=($(v).offset().left+blockSize) )
			{
				blocks++;	
			}
		}
	});
	
	return $(window).height()-(blocks*blockSize);
}


function physics()
{
	$(".block").each(function(i)
		{			
			if($(this).attr("drag") != 0)
			{
			
				var bot = $(this).offset().top+blockSize;
				var win = maxHeightBelow($(this).offset().left,$(this).offset().top);
				
				if(bot < win)
				{				
					var tt = $(this).attr("v");
					if (tt == undefined || tt == '' || tt == 0 || tt == NaN)
					{
						tt = 0;	
					}
					
					
					$(this).animate({top:'+='+tt},animTime/1.1);
					
					tt+=2;
					if (tt > blockSize)
					{
						tt = blockSize;	
					}
					$(this).attr("v",parseFloat(tt))
	
				} 
				if (bot > win)
				{
					$(this).animate({top:win-blockSize},animTime/2);
					$(this).attr("v",0)
				}
			}
		  
		});	
}


// Custom sorting plugin
(function($) {
  $.fn.sorted = function(customOptions) {
    var options = {
      reversed: false,
      by: function(a) { return a.text(); }
    };
    $.extend(options, customOptions);
    $data = $(this);
    arr = $data.get();
    arr.sort(function(a, b) {
      var valA = options.by($(a));
      var valB = options.by($(b));
      if (options.reversed) {
        return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
      } else {		
        return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
      }
    });
    return $(arr);
  };
})(jQuery);

// DOMContentLoaded
$(function() {

  // bind radiobuttons in the form
  var $filterType = $('#filter input[name="type"]');
  var $filterSort = $('#filter input[name="sort"]');

  // get the first collection
  var $applications = $('#applications');

  // clone applications to get a second collection
  var $data = $applications.clone();

  // attempt to call Quicksand on every form change
  $filterType.add($filterSort).change(function(e) {
    if ($($filterType+':checked').val() == 'all') {
      var $filteredData = $data.find('li');
    } else {
      var $filteredData = $data.find('li[data-type=' + $($filterType+":checked").val() + ']');
    }

    // if sorted by size
    if ($('#filter input[name="sort"]:checked').val() == "size") {
      var $sortedData = $filteredData.sorted({
        by: function(v) {
          return parseFloat($(v).find('span[data-type=size]').text());
        }
      });
    } else {
      // if sorted by name
      var $sortedData = $filteredData.sorted({
        by: function(v) {
          return $(v).find('strong').text().toLowerCase();
        }
      });
    }   

    // finally, call quicksand
    $applications.quicksand($sortedData, {
      duration: 700,
      easing: 'swing'
    }, function() { bindButtons();});

  });

});
