$(function() {
  $('html').addClass('jsEnabled');
  popsicleRiot.setup();
});

var popsicleRiot = {
  'ie6lt': $.browser.msie && $.browser.version < 7,
  'ie7lt': $.browser.msie && $.browser.version < 8,
  'ie8lt': $.browser.msie && $.browser.version < 9,
  arrayMax: function(array) {
    return Math.max.apply(Math, array);
  },
  arrayMin: function() {
    return Math.min.apply(Math, array);
  },
  'setup': function() {
    //setup home
    $('#home-work article').mouseenter(function() {
      $(this).find('div.header').stop().animate({
        'background-position': '-306px -117px',
        'padding-left': '89px'
      }, 250);
    }).mouseleave(function() {
      $(this).find('div.header').stop().animate({
        'background-position': '-374px -117px',
        'padding-left': '21px'
      }, 250);
    });
    $('#home-loot article').mouseenter(function() {
      $(this).find('a').stop().animate({
        'margin-top': '-162px'
      }, 350);
    }).mouseleave(function() {
      $(this).find('a').stop().animate({
        'margin-top': '0px'
      }, 350);
    });
    
    if (popsicleRiot.ie6lt) {
      $('#home-loot article p.more, #home-work article').hover();
    }
    
    //setup work
    if ($('#work')[0]) {
      $('#work').append('<div class="work-top"><a href="#top">Back to the top</a></div>');
      $('#work .work-top a').click(function() {
        $('html, body').animate({'scrollTop': 0}, 250);
        return false;
      });
    }
    if ($('#work-detail')[0]) {
      $('#work-detail-images.web:not(.no) img, #work-detail-images.yes img').after('<div class="work-top"><a href="#top">Back to the top</a></div>');
      $('#work-detail-images.print:not(.yes) img:last, #work-detail-images.identity:not(.yes) img:last, #work-detail-images.no img:last').after('<div class="work-top"><a href="#top">Back to the top</a></div>');
      $('#work-detail-images .work-top a').click(function() {
        $('html, body').animate({'scrollTop': 0}, 250);
        return false;
      });
    }
    $('#work-nav, #work-nav-repeat').each(function() {
      var maxNavCount = 0;
      $(this).find('>ul>li').each(function() {
        if (maxNavCount < $(this).find('li').length) {
          maxNavCount = $(this).find('li').length;
        }
      });
      
      $(this).find('>ul>li').each(function() {
        $(this).find('ul').addClass('left');
        $(this).append('<ul class="right"></ul>');
        var curL = $(this).find('ul.left li').length - 1;
        for (var i = 0; i <= curL - Math.ceil(maxNavCount/2); i++) {
          $(this).find('li').eq($(this).find('ul.left li').length-1).prependTo($(this).find('ul.right'));
        }
      });
    });
    /*$('#work-detail #work-nav').each(function() {
      $(this).find('li.work-nav-category ul').hide();
      $(this).find('li>strong').click(function() {
        $(this).parents('#work-nav').find('li.work-nav-category ul').toggle();
      }).mouseenter(function() {
        $(this).addClass('hover');
      }).mouseleave(function() {
        $(this).removeClass('hover');
      });
    });*/
    $('#work ul.projects li a').mouseenter(function() {
      $(this).find('strong span').stop().animate({
        'background-position': '-337px -155px',
        'padding-left': '56px'
      }, 250);
    }).mouseleave(function() {
      $(this).find('strong span').stop().animate({
        'background-position': '-377px -155px',
        'padding-left': '16px'
      }, 250);
    });
    $('#work section.work-content-category').each(function() {
      var numItems = $(this).find('ul.projects li').length;
      if (numItems > 3) {
        $(this).find('h2').after('<p class="expander expander-closed"><a href="#">view all <strong>' + numItems + '</strong> projects</a></p>');
        $(this).append('<div class="projects-hidden"></div>');
        $(this).find('ul.projects:not(:first)').appendTo($(this).find('div.projects-hidden'));
        $(this).find('div.projects-hidden').hide();
      }
    }).find('p.expander a').click(function() {
      var el = $(this).parents('section.work-content-category').find('div.projects-hidden');
      if ($(this).parent().hasClass('expander-closed')) {
        if (popsicleRiot.ie7lt) {
          el.show();
          $('#work section').hide().show();
        } else {
          el.slideDown(500);
        }
        $(this).html('collapse projects<span></span>');
        $('html, body').animate({scrollTop: $(this).parent().prev().offset().top}, 500);
      } else {
        if (popsicleRiot.ie7lt) {
          el.hide();
          $('#work section').hide().show();
        } else {
          el.slideUp(500);
        }
        $(this).html('view all <strong>' + el.parent().find('ul.projects li').length + '</strong> projects');
      }
      $(this).parent().toggleClass('expander-closed');
      return false;
    });
    /*$('#work-detail-meta').each(function() {
      that = $(this);
      $(window).load(function() {
        var width = that.width();
        that.css('margin-left', Math.floor((1014 - width) / 2));
      });
    });*/
        
    //setup about
    $('#about').each(function() {
      $(this).after('<div id="about-contact-container"><a href="mailto:info@popsicleriot.com">info@popsicleriot.com</a></div>');
    });
    
    //setup loot
    $('#loot article div.images ul').each(function() {
      var heights = [];
      $(this).find('img').each(function() {
        heights[heights.length] = $(this).height();
      });
      if ($(this).find('img').length > 0) {
        $(this).parents('article').find('footer').prepend('<div class="images-nav"><nav><a href="#" class="images-nav-prev images-nav-prev-disabled">Previous</a> <a href="#" class="images-nav-next">Next</a></nav><p>image <span>1</span> of ' + $(this).find('img').length + '</p></div>');
        if ($(this).find('img').length < 2) {
          $(this).parents('article').find('footer a.images-nav-next').addClass('images-nav-next-disabled');
        }
        $(this).width(($(this).find('img').length * 449) + 'px').height(popsicleRiot.arrayMax(heights) + 'px');
      }
    });
    $('#loot article a.images-nav-prev').click(function() {
      if ($(this).hasClass('images-nav-prev-disabled')) {
        return false;
      }
      $(this).next().removeClass('images-nav-next-disabled');
      var curIndex = parseInt($.trim($(this).parents('div.images-nav').find('p span').text()), 10);
      
      $(this).parents('article').find('div.images').animate({scrollLeft: ((curIndex-2) * 449) + 'px'}, 250);
      
      $(this).parents('div.images-nav').find('p span').text(curIndex - 1);
      
      if ((curIndex-1) === 1) {
        $(this).addClass('images-nav-prev-disabled');
        return false;
      }
      
      return false;
    });
    $('#loot article a.images-nav-next').click(function() {
      if ($(this).hasClass('images-nav-next-disabled')) {
        return false;
      }
      $(this).prev().removeClass('images-nav-prev-disabled');
      var curIndex = parseInt($.trim($(this).parents('div.images-nav').find('p span').text()), 10);
      
      $(this).parents('article').find('div.images').animate({scrollLeft: (curIndex * 449) + 'px'}, 250);
      
      $(this).parents('div.images-nav').find('p span').text(curIndex + 1);
      
      if ((curIndex+1) === $(this).parents('article').find('div.images img').length) {
        $(this).addClass('images-nav-next-disabled');
        return false;
      }
      
      return false;
    });
    
    if ($('#loot')[0]) {
      $(window).load(function() {
        if ($('#loot article').length === 1) {
          var sidebarHeight = $('#sidebar').height() + 15;
          var articleHeight = $('#loot article').height() + 68;
          if (sidebarHeight > articleHeight) {
            $('#loot article .images ul').height($('#loot article').height() + (sidebarHeight - articleHeight));
          }
        }
        $('#loot article').each(function() {
          var heightDiff = $(this).find('.images').height() - ($(this).find('.content').height() + 35);
          if (heightDiff > 1) {
            $(this).find('.images-nav').css({
              'padding-top': Math.floor(heightDiff/2 + 16) + 'px',
              'padding-bottom': Math.floor(heightDiff/2 + 16) + 'px'
            });
            $(this).find('.images-nav a').css({
              'top': Math.floor(heightDiff/2 + 18) + 'px'
            });
            $(this).css('width', 'auto').css('width', $(this).width());
          }
        });
      });
    }
    
    $('#loot article p.permalink a').click(function() {
      var elRef = $(this).parent();
      $(this).after('<input type="text" value="' + $(this).attr('href') + '" />').hide();
      elRef.find('input').focus().blur(function() {
       $(this).prev().show().end().remove();
      });
      return false;
    });
    
    if ($('#articles-pagination')[0]) {
      $('#loot article').after('<div class="loot-top"><a href="#top">Back to the top</a></div>');
      $('#loot #articles .loot-top a').click(function() {
        $('html, body').animate({'scrollTop': 0}, 250);
        return false;
      });
    }
    $('#loot #articles-pagination ul').each(function() {
      $(this).css('margin-left', ($(this).parent().width() - $(this).width())/2 + 'px');
    });
    
    //brooklyn 'watermark'
    if ($('#about')[0]) {
      $('header').filter('.primary').append('<div id="wm-brooklyn-about"></div>');
    } else if ($('#home')[0]) {
      $('header').filter('.primary').append('<div id="wm-brooklyn"></div>');
    } else {
      $('header').filter('.primary').append('<div id="wm-brooklyn-light"></div>');
    }
    
    //footer realign
    var footer = $('footer').filter('.primary');
    var tFooter = false;

    var footerRealign = function() {
      if ($(window).height() <= $('body').height() - 10) {
        footer.addClass('noborder');
      } else {
        footer.removeClass('noborder');
      }
    };
    
    footerRealign();
    $(window).load(function() {
      footerRealign();
    });
    $(window).resize(function() {
      window.clearTimeout(tFooter);
      tFooter = window.setTimeout(function() {
        footerRealign();
      }, 100);
    });
  }
};

if (popsicleRiot.ie8lt) {
  (function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(',');for(var i=0;i<e.length;i++){document.createElement(e[i])}})();
}

(function($) {
  $.fn.hover = function() {
    $(this).mouseenter(function() {
      $(this).addClass('hover');
    }).mouseleave(function() {
      $(this).removeClass('hover');
    });
  };
})(jQuery);

// @author Alexander Farkas
// v. 1.21
(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);
