// HERE WE ARE BOYS, SET YOUR STYLE !!
var options = {
		'colWidth' : 160,
		'gutWidth' : 10,
		'maxOpenSize' : 6
		};

$(function(){ 
	var o = false,
		ocount = 0;
	var methods = {
	  		openWidth : function(f) { //WIDTH OPEN ELEMENT
			var openWidth = 0,
				$target = $('.large'),
			    containerSize = $('#container').width(),
				c = options.colWidth,
				g = options.gutWidth,
			    space = Math.max( Math.floor( containerSize / c ),1);	
			if ( space >= options.maxOpenSize) { 
				openWidth = (options.maxOpenSize*c)-g;
			} else { 
				openWidth = (space*c)-g; 
			}
			//RESIZE IFRAME
			var iframeWidth = $('#the_post').find('iframe').attr('width');
			var iframeHeight = $('#the_post').find('iframe').attr('height');
			var fw = (openWidth-20)/iframeWidth;
			if (fw && fw != 1) {
				$('#the_post').find('iframe').attr({'width':openWidth-20, 'height':Math.floor(iframeHeight * fw)});
			}
			$('#the_post').find('.post-img').each(function() {
				var imgWidth = $(this).width();
				var imgHeight = $(this).height();
				var iw = (openWidth-20)/imgWidth;
				$(this).attr({'width':openWidth-20, 'height':Math.floor(imgHeight  * iw)});
			});
			$target.css('width',openWidth , function() {
				$container.isotope('reLayout');
			});
			if (typeof f == "function") f(); else alert('we should not be here');
			
		},
		openHeight : function(f) { //Height OPEN ELEMENT
			var openHeight = $('#the_post').outerHeight(true);
			var fh = Math.ceil((openHeight)/options.colWidth);
				openHeight = options.colWidth*fh;
		$('#the_post').css('height',openHeight-30);
		$('.large').css('height',openHeight-10);
		
		if (typeof f == "function") f(); else alert('we should not be here');
		},
		goThere : function() {
				$container.isotope().find('.element.large').each(function(){
							var position = $(this).data('isotope-item-position');
							//console.log('item position is x: ' + position.x + ', y: ' + position.y  );
							var target = position.y + $('#head').outerHeight(true); 
							$('html,body').animate({scrollTop: target}, 1000);	
					});
		}
	}; //END METHODS
	$.fn.reCalc = function( method ) {
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.reCalc' );
		}    
    };
	var $container = $('#container'),
		$element = $('#container .element'),
		$allLinks = $element.find('a'),
		$projLinks = $('#container > .element.project > a'),
	    $blogLinks = $('#container > .element.blog > a'),
		siteURL = 'http://' + top.location.host.toString(),
		hash = window.location.hash,
		URL = '',
		$el;
		
	$container.isotope({
        itemSelector: '.element',
		itemPositionDataEnabled: true,
		masonry: {
    		columnWidth: options.colWidth,
			gutterWidth: options.gutWidth
		},
		//sortBy: 'random' //YOUR CHOICE
		getSortData : {
			title : function ( $elem ) {
				return $elem.find('.title').text();
			},
			category : function ( $elem ) {
				return $elem.attr('class');
			},
			date : function ( $elem ) {
				return parseInt($elem.attr('data-date'));
			},
			id : function ( $elem ) {
				return $elem.attr('data-id');
			}
		}
      });
	$container.infinitescroll({
        navSelector  : '#page_nav',    // selector for the paged navigation 
        nextSelector : '#page_nav a',  // selector for the NEXT link (to page 2)
        itemSelector : '.element',     // selector for all items you'll retrieve
		loadingText  : "there might be more ... ", 
		donetext     : "... nope, that's it for now" ,
		loadingImg   : 'http://tricky.schnellebuntebilder.de/wp-content/themes/isotopes_win/img/ajax2.gif'
        },
        // call Isotope as a callback
        function( newElements ) {
          $container.isotope( 'appended', $( newElements ) ); 
		  Cufon.refresh();
		  $(this).find('.element > a').find('img').load(function() {    
				$(this).not('.clone').pixastic("desaturate");
			}).each(function(index) {
				var clone = $(this).clone().addClass('clone').css({'position':'absolute','top':0, 'left':0});
			$(this).parent().append(clone);
			});
		  if (o) {
			$container.find('.clone').hide();
		  }
        }
      );	  
	// PIXASTIC DESAT CLONING
	$allLinks.find('img').load(function() {    
			$(this).not('.clone').pixastic("desaturate");
		}).each(function(index) {
			var clone = $(this).clone().addClass('clone').css({'position':'absolute','top':0, 'left':0});
			$(this).parent().append(clone);
	});
	//	
	if (hash) { //we know what we want, the url is not the home page!
	  		hash = hash.substring(1);
			URL = 'http://' + top.location.host + hash;
			var $link = $('a[href="' + URL + '"]'), // find the link of the url
			    $target = $link.parent().find('#content');
			$link.fadeToggle('slow', 'linear', function() {
					$('.clone').hide();
					$allLinks.not($(this)).find('h1.blog').fadeTo('fast', 0.5);
					
					$target.bind('ajaxStop', function () {
						ocount = 0;
					});
					$target.css('visibility', 'hidden').load(URL, function() {
						$target.find('iframe').css('opacity',0);
						ocount++;
						o = true;
						$target.parent().addClass('large');
						$target.reCalc('openWidth', function() {
							$target.reCalc('openHeight', function () {
								$target.css('visibility', 'visible');
								$container.reCalc('goThere');
							});
						});
						$container.isotope('reLayout', function() {
								$target.find('iframe').stop().delay(1000).animate({opacity:1},1000);
							});	
						
					});
					
				});
	}	
	
	$allLinks.each(function() {
			$(this).attr('href', '#' + this.pathname);	
	}).live('mouseover', function () {
		$(this).find('.proj').stop(true,true).fadeTo(0, 0);
		$(this).parent().find('.clone').stop(true).fadeTo(0, 1);
		//$('.serious').not($(this)).css('backgound-color','#555');
		$(this).find('h1').stop(true,true).fadeTo(0, 1);
		if (o) {
			$(this).parent().find('.clone').stop(true,true).fadeTo(0, 1);
			$(this).find('h1').stop(true,true).fadeTo(0, 1);
		} else {
			$allLinks.not($(this)).find('.clone').stop(true).fadeTo(0, 0);
			//$blogLinks.not($(this)).find('h1').stop(true,true).fadeTo(0, 0.5);
			$allLinks.not($(this)).find('h1.blog').stop(true,true).fadeTo(0, 0.5);
		}
	  }).live('mouseout', function () {
		$(this).find('.proj').stop(true,true).delay(200).fadeTo(100, 1);
		if (o) {
			$(this).parent().stop(true,true).find('.clone').delay(200).fadeOut(0);
			$(this).find('h1').stop(true,true).delay(200).fadeTo(100, 0.5);
		} else {
			$allLinks.find('.clone').stop(true).delay(200).fadeTo(100, 1);
			$allLinks.not($(this)).find('h1.blog').stop(true,true).delay(200).fadeTo(100, 1);
		}
	  }).click(function() {
		$el = $(this);
		URL = $el.attr('href').substring(1);
		var $target = $el.parent().find('#content');
		if (o) {
			$container.find('.large').css({width:'',height:''}).removeClass('large').end().find('#content').empty();
			$('#the_post').css({width:'',height:''});	
		}
		$allLinks.not($el).fadeIn('fast', 'linear');
		$el.fadeOut('fast', 'linear', function() {
					$('.clone').hide();
					$blogLinks.not($(this)).find('h1').fadeTo('fast', 0.5);
					$target.bind('ajaxStop', function () {
						ocount = 0;
					});
					$target.css('visibility', 'hidden').load(URL, function() {
						ocount++;
						o = true;

						$target.find('iframe').css('opacity',0);
						o = true;
						if (!$container.find('.large').length) {
							
						$target.parent().addClass('large');
						$target.reCalc('openWidth', function() {
							$target.reCalc('openHeight', function () {
								$target.css('visibility', 'visible');
								
							});
						});
						$container.isotope('reLayout', function() {
								$target.find('iframe').stop().delay(1000).animate({opacity:1},1000);
								$container.reCalc('goThere');
							});
							if (ocount > 1 || $('.large').length > 1) {
								$element.each(function() {
									$(this).stop(true,true).css({width:'',height:''}).removeClass('large').find('#content').empty();
								});
								//alert ('bitch!');
								location.reload();
							}
						} else {
							$element.each(function() {
									$(this).stop(true,true).css({width:'',height:''}).removeClass('large').find('#content').empty();
							});
							//alert ('bitch!');
							location.reload();
						}
					});
				  	
				});
			
	});
		
	


  
});
//DOM READY
 $(document).ready(function() {
	//var width = $('#container').width()-10;
	var width = $('#container').width()+10;
	  $('#head').css('width', width);

// 	  if ($('body').width() <= 320) {
//			$('#head h1').css('font-size','12pt');
//			Cufon.refresh();
//		}

//FILTER
	$('#filters').find('a').click(function(){
		var selector = $(this).attr('data-filter');
			$('#container').isotope({ filter: selector });
		return false;
		});
//SORT
	$('#sort-by').find('a').click(function(){
		var sortName = $(this).attr('href').slice(1);
			$('#container').isotope({ sortBy : sortName });
		return false;
});


	});	  
//DOM READY DONE
//FILTER



/*MASONRY CENTERED BEGIN-----------------------------------------------------------------*/
$.Isotope.prototype._getCenteredMasonryColumns = function() {
		
    this.width = this.element.width();
    var parentWidth = this.element.parent().width();
    var colW = this.options.masonry && this.options.masonry.columnWidth ||
                  this.$filteredAtoms.outerWidth(true) ||
                  parentWidth;
    var cols = Math.floor( parentWidth / colW );
    cols = Math.max( cols, 1 );
    this.masonry.cols = cols;
    this.masonry.columnWidth = colW;
	if ( cols >= options.maxOpenSize) { 
				openWidth = (options.maxOpenSize*colW)-options.gutWidth;
			} else { 
				openWidth = (cols*colW)-options.gutWidth; 
			}
	if (this.masonry.cols <= 2) {
			$('#head h1').css('font-size','12pt');
				Cufon.refresh();
			} else {
			$('#head h1').css('font-size','20pt');
				Cufon.refresh();
			}
	var iframeWidth = $('#the_post').find('iframe').attr('width');
	var iframeHeight = $('#the_post').find('iframe').attr('height');
	var fw = (openWidth-20)/iframeWidth;
	if (fw && fw != 1) {
			$('#the_post').find('iframe').attr({'width':openWidth-20, 'height':Math.floor(iframeHeight * fw)});
	}
	$('#the_post').find('.post-img').each(function() {
			var imgWidth = $(this).width();
			var imgHeight = $(this).height();
			var iw = (openWidth-20)/imgWidth;
			$(this).attr({'width':openWidth-20, 'height':Math.floor(imgHeight  * iw)});
	});
	$('.large').css('width',openWidth);
	$('#the_post').css('height','');
	
	var openHeight = $('#the_post').outerHeight(true);
	var fh = Math.ceil((openHeight)/colW);
		openHeight = colW*fh;
			$('#the_post').css('height',openHeight-30);
			$('.large').css('height',openHeight-10);
  };
  
  $.Isotope.prototype._masonryReset = function() {
    this.masonry = {};
    this._getCenteredMasonryColumns();
    var i = this.masonry.cols;
    this.masonry.colYs = [];
    while (i--) {
      this.masonry.colYs.push( 0 );
    }
  };

  $.Isotope.prototype._masonryResizeChanged = function() {
    var prevColCount = this.masonry.cols;
    this._getCenteredMasonryColumns();
	$('#the_post').find('iframe').css('opacity',0).delay(1500).animate({opacity:1},300);
    return ( this.masonry.cols !== prevColCount );
	
  };
  
  $.Isotope.prototype._masonryGetContainerSize = function() {
    var itemsTotalWidth = 0;
    this.$filteredAtoms.each(function(){
      itemsTotalWidth += $(this).outerWidth(true);
    });
    var layoutWidth = this.masonry.cols * this.masonry.columnWidth,
        size = {
          height : Math.max.apply( Math, this.masonry.colYs ),
          width : Math.min(layoutWidth, itemsTotalWidth )
        };
		//$('#head').css('width', size.width-options.gutWidth);
		$('#head').css('width', size.width+10);
    return size;
  };
/*MASONRY CENTERED END-------------------------------------------------------------------*/
