var DM = window.DM || {};
$.fn.searchField = function(settings) {
	 $.fn.fancybox.defaults = {
   	activeColor: "" //pickup the default color
   };
  settings = $.extend({}, $.fn.fancybox.defaults, settings);
  return this.each(function () {
    var label = $(this).find('label').text();
		var field = $(this).find('input:text');
		var inactiveColor = $(this).css("color");
		if(settings.activeColor === ""){
			settings.activeColor = inactiveColor;
		}
		field.val(label).css("color", inactiveColor)
		/*.keyup(function(){
			$(this).val("");
		})*/
		.focus(function(){
      $(this).val("").css("color", settings.activeColor);
    })
		.blur(function(){
      $(this).val(label).css("color", inactiveColor);
    });
  });
};

$(function(){
	/*image switch in overlay*/
	$.fn.setImages = function() { 
		var imgs = $('#fancy_content .images img');
		if(imgs.size() > 1){
			var currClass = ' class="first on"';
			var pager = '<div id="pager">';
			for (i = 0; i < imgs.size(); i++) {
				pager += '<a'+currClass+' href="#'+(i)+'">'+(i+1)+'</a>';
				currClass = '';
			}
			pager += '</div>';
			var cont = $('#fancy_content .images').append(pager);
			$('#fancy_content #pager a').click(function () {
				var currI = $(this).html()-1;
			  var imgs = $('#fancy_content .images img');//.each(function(){$(this).removeClass('first')});
			  for (i=0;i <imgs.size();i++){
			  	if (i == currI) {
					$(imgs[i]).show('slow').parent().css({'text-align':'center'});
				} else {
					$(imgs[i]).hide('slow').parent().css({'text-align':'center'});
				}
			  }
			  $('a',this.parentNode).each(function(){$(this).removeClass('on');});
		      $(this).addClass("on");
			  return false;
		    });
		}
	};
	$.fn.outerHTML = function() { 
		return $('<div></div>').append( this.clone() ).html(); 
	};

	// navigation
	$("#mainNav span.bg").css("opacity","0");
	$("#mainNav span.nav").hover(
		function () {
			// animate opacity to full
			$(this).prev().stop().animate({opacity: 1}, "slow");
		},
		// on mouse out
		function () {
			// animate opacity to nill
			$(this).prev().stop().animate({opacity: 0}, "slow");
		});

	/*$('#hooha li').page();*/
	$("#hooha a.person").each(function(i){
		this.href = this.href + '/mode/ajax';
		showOverlay(this);
	});

	$("#people .person a, #partners .partner a:first-child").each(function(i){
		this.href = this.href + '/mode/ajax';
		if($(this).parent().hasClass('partner')){
			showOverlay(this, null, 'partner');
		} else {
			showOverlay(this, null, 'person');
		}
	});
	
	$("#work .project:not(.infobox) a").each(function(i){
		this.href = this.href + '/mode/ajax';
		showOverlay(this,$.fn.setImages);
		}); 
	//alert(jQuery.support.boxModel);
	
	$("a.infobox, .project a.infobox").each(function(i){
		this.href = this.href + '/mode/ajax';
		showOverlay(this);
	});
	
	function printPage(){
		if(this.itemArray){
			$('#fancy_wrap a.printLk').click(function(){window.print();});
		}
	}
	
	function showOverlay(link,fn, behavior, w, h, startFn){
		//alert(link);
		var behave = "";
		var check = true;
		var dims = {width: 380, height: 500, padding:30};
		var callback = null;
		var callbackStart = null;
		if(behavior){
			behave = behavior;
		}
		if(w) {
			dims.width = w;
			check = false;
		}
		if (h) {
			dims.height = h;
			check = false;
		}
		if (fn) {
			callback = fn;
		}
		if (startFn) {
			callbackStart = startFn;
		}
		if (check) {
			dims = getOverlayDimensions(link, behave, dims);
			if(!fn){
				if ($(link).hasClass('print')){
					callback = printPage;
				}
			}
		}
		/*if(!jQuery.support.cssFloat){winWidth = winWidth - 0;winHeight = winHeight - 0;}*/ /*IE 6/7 padding*/
		$(link).fancybox({
			'hideOnContentClick': false,
			'frameWidth':dims.width,
			'frameHeight':dims.height,
			'padding':dims.padding,
			'overlayShow':false,
			'callbackOnShow': callback,
			'callbackOnStart':function(){
				var dim = getOverlayDimensions(link);
				if (dim) {
					$.fn.fancybox.resize(dim.width, dim.height);
				}
			}
		});
	}
	
	$.fn.showOverlay = function(settings){
	  $.fn.showOverlay.defaults = {
	    after: null
	  };
		settings = $.extend({}, $.fn.showOverlay.defaults, settings);
		return $(this).each(function(i){
			showOverlay(this, settings.after);
			return true;
		});
	};
	
	function getOverlayDimensions(link, behavior, dimensions){
		var dims = {width: 380, height: 500, padding:30};
		var behave = behavior;
		if(behavior){
			behave = behavior;
		}
		if(dimensions){
			dims = dimensions;
		} else {
			if(link.className == '' && !behave){return;}
		}
		if ($(link).hasClass('tall') || behave == 'tall') {
			dims.width = 450;
			dims.height = 500;
		} else if ($(link).hasClass('wide') || behave == 'wide') {
			dims.width = 750;
			dims.height = 400;
		} else if ($(link).hasClass('big') || behave == 'big') {
			dims.width = 750;
			dims.height = 485;
		} else if ($(link).hasClass('partner') || behave == 'partner') {
			dims.width = 380;
			dims.height = 500;
		} else if ($(link).hasClass('person') || behave == 'person' || $(link).hasClass('team') || behave == 'team') {
			dims.width = 360;
			dims.height = 370;
		} else if ($(link).hasClass('medium') || behave == 'medium') {
			dims.width = 650;
			dims.height = 480;
		}
		/*IE6 sets w/h smaller*/
		if(/msie|MSIE 6/.test(navigator.userAgent)){
			dims.width = dims.width + dims.padding + dims.padding/2 + 2;
			dims.height = dims.height + dims.padding*2;
		}
		return dims;
	}

	
	/* popups */
	//$('#partners .partner').pop();
	$('#p-home #partners').mtBubble({showAbove: false, distances: [0], hideDelays:[500], leftShifts: [20], bubbleTimes: [500], bubbleWidths: [230], bubbleImagesPath: 'skin/js/mtbubble/images/skins/classic', msieFix : true});
	$('#p-about #partners').mtBubble({showAbove: false, distances: [0], hideDelays:[500], leftShifts: [110], bubbleTimes: [500], bubbleWidths: [250], bubbleImagesPath: 'skin/js/mtbubble/images/skins/classic', msieFix : true});
	$('#work .project, #seeourwork .project').mthover({startPos: '-59px'});
	$('#people .person').mthover({startPos: '-34px',endBgColor: '#696969'});
	
	/* toggle */
	$('a.i-toggle').click(function(){
		var tar = this.href.replace(DM.root,"");
		//alert(tar);
		if(tar.indexOf('#') < 0){ return true;}
		tar = tar.substring(tar.indexOf('#'))
		if($(tar).is(':visible')){
			$(tar).removeClass('i-down').slideUp();
		} else {
			$(tar).slideDown().addClass('i-down');
		}
		return false;
	});
	
	/* news */
	function initRotatingList() {
		function rotate() {
			$("#newsticker li:first").fadeOut("slow",function (){
				$("#newsticker li:first").insertAfter("#newsticker li:last");
				$("#newsticker li:last").show('fast');
			});
		};
		var newsTimer = setInterval(function(){
            rotate();
        }, 5000);
		//rotate();
	}
	initRotatingList();
});

DM.mtRandGrid = function(){
	var $grid;
	var $spots;
	var queque;
	var currItem = -1;
	var spotAdded = false;
	var currQueque = -1;
	var reloadTimer;
	var maxSpots = 1;
	var loadOrder = [0,23,25,17,22,10,30,11,15,26,2,20,29,6,12,3,16,19,8,27,31,18,28,4,1,9,5,21,24,14,7,13]
	function initialize(container, containee, addDataUrl){
		$grid = $(container);
		if($grid.length == 0){
			return;
		}
		$spots = $(containee, $grid).css({opacity:0});
		$.getJSON(DM.root+addDataUrl+'/mode/ajax', function(data, textStatus){startLoading(data, textStatus);});
	};
	function startLoading(data, status){
		queque = data;
		$spots.each(function(i) {
			var obj = this;
			currQueque += 1;
			var qItem = queque.people[currQueque];
			$(obj).find('a').addClass(qItem.type).get(0).href=qItem.url;
			$(obj).find('.teaser').html(qItem.teaser);
			$(obj).find('img').replaceWith(qItem.img);
			$(obj).toggleClass("partner", qItem.type == 'partner');
		});		
		function loader(i, obj){
			function doLoad() {
				$(obj).animate({opacity:1},'slow');
				if(i == 31){start()}
			}
			setTimeout(doLoad, 200*i);
		}
		var initLoadOrder = [0,1,4,2,5,8,3,6,9,12,7,10,13,16,11,14,17,20,15,18,21,24,19,22,25,28,23,26,29,27,30,31]
		for (var i = 0; i < initLoadOrder.length; i++) {
			loader(i, $spots.get(initLoadOrder[i]));
		}
		currQueque = 31;
	};

	function start(data, status){
		reloadTimer = setInterval(function(){
            switchSpot();
        }, 4000);
	};

	function switchSpot(){
		currItem = currItem + 1;
		if(currItem == loadOrder.length){currItem = 0;}
		var currSpot = loadOrder[currItem];
		//var currSpot = Math.round(Math.random()*$spots.length);
		if (currQueque < queque.count-1){
			currQueque += 1;
		} else {
			currQueque = 0;
		}
		$spots.eq(currSpot).fadeOut('slow', function(){
			var qItem = queque.people[currQueque];
			$(this).find('a').toggleClass("partner", qItem.type == 'partner').toggleClass("team", qItem.type == 'team').get(0).href=qItem.url;
			$(this).find('.teaser').html(qItem.teaser);
			$(this).find('img').replaceWith(qItem.img);
			$(this).toggleClass("partner", qItem.type == 'partner');
			$(this).fadeIn('slow');
		});
	}
	
	return {
		init : initialize
	};
}();
$(function(){
	DM.mtRandGrid.init('#p-people #people', '.person', '/morepeople');
});

// Force all External Links to a New Window/Tab/Page
$(function(){
	$("a[rel$='external']").click(function(){
	  this.target = "_blank";
	});
});

//Card stack - ED
var CardStack = (function (window, document, undefined) {
	var cards,
		count,
		currentIndex,
		newIndex,
		animating,
		currentCard,
		newCard,
		t,
		stopped = false,
		config = {
				'animationDuration' : 800,
				'rotationDuration' : 7000,
				'outCSS' : {left:'-300px'},
				'inCSS' : {left:'0'}
				};
	
	function nextCard() {
		newIndex = (currentIndex + 1) % count;
		currentCard = cards.eq(currentIndex)
		newCard = cards.eq(newIndex);
		animating = true;
		currentCard.animate(config.outCSS, config.animationDuration, function() { showCardCallBack(true); });
	}

	function previousCard() {
		newIndex = (currentIndex - 1) % count;
		currentCard = cards.eq(currentIndex),
		newCard = cards.eq(newIndex);
		animating = true;
		newCard.animate(config.outCSS, config.animationDuration, function() { showCardCallBack(false); });
	}

	function showCardCallBack(forward) {
		newCard.css('z-index', 3);
		if (forward) {
			currentCard.css('z-index', 1);
			cards.eq((newIndex + 1) % count).css('z-index', 2);
			currentCard.animate(config.inCSS, config.animationDuration, function() { animating = false; });
		}
		else {
			cards.eq((currentIndex + 1) % count).css('z-index', 1);
			currentCard.css('z-index', 2);
			newCard.animate(config.inCSS, config.animationDuration, function() { animating = false; });
		}
		currentIndex = newIndex;
		if (!stopped) {
			clearTimeout(t);
			t = setTimeout(nextCard, config.rotationDuration);
		}
	}
	
	function _initialize() {
		cards = $('#cardStack li');
		currentIndex = 0;
		count = cards.size();
		animating = false;
		currentCard = cards.eq(currentIndex);
		cards.eq(currentIndex + 1).css('z-index', 2);
		$('.card-pagination .btn-back', cards).click(function() {
			if (!animating) {
				previousCard();
				clearTimeout(t);
				stopped = true;
			}
			return false;
		});
		$('.card-pagination .btn-forward', cards).click(function() {
			if (!animating) {
				nextCard();
				clearTimeout(t);
				stopped = true;
			}
			return false;
		});
		t = setTimeout(nextCard, config.rotationDuration);
	}
	
	return { initialize: _initialize };
})(this, this.document);

$(document).ready(function() {
	CardStack.initialize();
});
