var currentClient;
var scrollTimeout;
var scrollTimeoutFlag;
$(document).ready( function() {
	currentClient = 0;
	scrollTimeoutFlag = true
	$(".clients-window-cover").each(function() {
		for (i=19; i>0; i--) {
			$(this).append("<div style='opacity:"+(i*0.05)+"; filter:alpha(opacity="+(i*5)+")'></div>");
		}
	});
	
	for (i=0; i<clients.length; i++) {
		var clientName = clients[i].name;
		var logo = new Image();
		logo.src = "/images/home/client_logos/"+clientName+".png";
		logo.onload = function() { this.loadComplete = true };
		clients[i].logo = logo;
	}
	
	
	positionClientsSlider();
	
	$(document).bind('cbox_closed', function(){
        startScroll();
	});
	$("#clients-slider").css("display", "block");
	

	$("#clients").mouseover(function () {
		clearTimeout(scrollTimeout);
		scrollTimeoutFlag = false;
	});
	$("#clients").mouseout(function () {
		startScroll();
	});

	
	$(".slide-out-content .header").click(function(e) {
		openCloseContent($(this).parent().parent().attr("id"));
		e.stopPropagation();
	});
	
	$(".slide-out-content .title").click(function(e) {
		openCloseContent($(this).parent().attr("id"));
		e.stopPropagation();
	});
	
	$(".slide-out-content").click(function(e) {
		e.stopPropagation();
	});
	
	$(document).click(function(e) {
		closeAllContentExcept();
	});
	

	var scrptE = document.createElement("script");
	scrptE.setAttribute("type", "text/javascript");
	scrptE.setAttribute("language", "JavaScript");
	scrptE.setAttribute("src", "http://twitter.com/statuses/user_timeline/grio_sf.json?callback=twitterCallback2&count=10");
	document.getElementsByTagName("head")[0].appendChild(scrptE);	
	
	getBlogPosts();
	getNewsPosts();
	
});

function formatDate(dateStr) {
	dateStr = dateStr.substr(0,10);
	var dates = dateStr.split("-");
	
	return dates[1]+"."+dates[2]+"."+dates[0];
}

function getBlogPosts() {
	$.getJSON( "/getBlogPosts.php", function(data) {
		var totalPosts = data.totalResults<13 ? data.totalResults : 12;
		var html = '<a href="http://blog.grio.com/" class="mainlink">[ More ]</a><div class="clear"></div><ul class="blog-list">';
		for (var i=0; i<totalPosts; i++) {
			
			var entry = data.entries[i];
			html += '<li><div class="date">'+formatDate(entry.published)+'</div><a href="'+entry.permalinkUrl+'">'+entry.title+'</a></li>';
		}
		html += "</ul><br/><br/>";
		$("#blog .content-inner").html(html);
	});
}

function getNewsPosts() {
	$.getJSON( "/getBlogPosts.php?category=News", function(data) {
		var totalPosts = data.totalResults<6 ? data.totalResults : 5;
		var html = '<a href="http://blog.grio.com/news/" class="mainlink">[ More ]</a><div class="clear"></div><ul class="blog-list">';
		for (var i=0; i<totalPosts; i++) {
			
			var entry = data.entries[i];
			html += '<li><div class="date">'+formatDate(entry.published)+'</div><div class="news-title"><a href="'+entry.permalinkUrl+'">'+entry.title+'</a></div><div class="news-excerpt">'+entry.excerpt+'</div></li>';
		}
		html += "</ul><br/><br/>";
		$("#news .content-inner").html(html);
	});
}

function openCloseContent(id) {
	
	closeAllContentExcept(id);
	
	if ($("#"+id).hasClass("open")){
		closeContent(id);
	} else {
		openContent(id);
	}
}

function openContent(id){
	var maxHeight = Math.round($(window).height() * 0.7);
	var contentHeight = $("#"+id+" .content-inner").height() + 30;
	var height = contentHeight<maxHeight ? contentHeight : maxHeight;
	$("#"+id).animate({ 
        height: height,
        bottom:"29px"
      }, 400,  "swing", setContentStateOpen );

	$("#"+id+" .wrapper").animate({ 
        opacity:1
      }, 400,  "swing");
}

function closeContent(id) {
	$("#"+id).find(".content").css("overflow-y", "hidden");
	$("#"+id).animate({ 
        height:"28px",
        bottom:"1px"
      }, 400,  "swing", setContentStateClosed);

	$("#"+id+" .wrapper").animate({ 
        opacity:0.8
      }, 400,  "swing");
}

function closeAllContentExcept(id) {
	$(".slide-out-content").each(function() {
		if (this.id != id) {
			closeContent(this.id);
		}
	});
}
var setContentStateOpen = function() {
	$(this).removeClass("closed");
	$(this).addClass("open");
	$(this).find(".content").css("overflow-y", "auto");
	$(this).css("z-index", 50);
}

var setContentStateClosed = function() {
	$(this).removeClass("open");
	$(this).addClass("closed");
	var z=1;
	$(".slide-out-content").each(function() {
		$(this).css("z-index", z);
		z++;
	});
}

function arrayWrap(num) {
	if (num>clients.length-1) {
		num -= clients.length;
	} else if (num<0) {
		num += clients.length;
	}
	return num;
}


var startScroll = function() {
	if ($("#cboxOverlay").css("display") == "none") {
		scrollTimeoutFlag = true;
		setScrollTimeout(scrollClients, 2000);
	}
}

function setScrollTimeout(func, time) {
	if (scrollTimeoutFlag) {
		clearTimeout(scrollTimeout);
		scrollTimeout = setTimeout(func,time);
	}
}

function positionAndAddClientsSlider(inc) {
	currentClient = arrayWrap(currentClient+inc);
	positionClientsSlider();
}

function positionClientsSlider() {
	for (i=0; i<clients.length; i++) {
		if (!clients[i].logo.loadComplete) {
			setTimeout("positionClientsSlider()", 10);
			return;
		}
	}

	
	var width = parseInt($("#clients-window").css("width"));
	var lefts = new Array();
	var rights = new Array();
	
	$("#projects").empty();
	$("#clients-slider").empty();
	
	var i;
	for (i=1; i<Math.ceil(clients.length/2)+1; i++) {
		rights.push(arrayWrap(i+currentClient));
	}
	
	for (; i<clients.length; i++) {
		lefts.push(arrayWrap(i+currentClient));
	}
	
	var leftWidth = 0;
	for(i=0; i<lefts.length; i++) {
		$("#clients-slider").append("<img src='"+clients[lefts[i]].logo.src+"' id='logo_"+lefts[i]+"'/>");
		leftWidth += clients[lefts[i]].logo.width;
	}
	$("#clients-slider").append("<img src='"+clients[currentClient].logo.src+"' id='logo_"+currentClient+"' style='opacity:1; filter:alpha(opacity=100);'/>");
	for(i=0; i<rights.length; i++) {
		$("#clients-slider").append("<img src='"+clients[rights[i]].logo.src+"' id='logo_"+rights[i]+"'/>");
	}

	var left = Math.round(width/2)- leftWidth -(Math.round(clients[currentClient].logo.width/2));
	$("#clients-slider").css("left", left+"px");
	
	if (clients[currentClient].quote) {
		$("#quote").html(clients[currentClient].quote);
		$("#attribution").html("-- "+clients[currentClient].attribution);
		$("#testimonial").css("visibility", "visible");
		//var height = $("#testimonial-content").height() + 20;
		//$("#testimonial").css("top", -height);
		$("#testimonial").animate({
			opacity:1
		}, 200);
	}
	
	if (clients[currentClient].projects) {
		var html = "<table><tr>";
		for (project in clients[currentClient].projects) {
			html += "<td><a href='#' onclick='openProject(\""+project+"\"); return false;'><img src='/images/home/project_thumbs/"+project+".jpg'/></a></td>";
		}
		html += "</tr></table>";
		$("#projects").append(html);
		$("#projects").animate({
			opacity:1
		}, 400);
	}
	
	setScrollTimeout(scrollClients, 4000);
	
	$("#arrow-left").bind("click", function(){
		scrollClients(-1);
	});
	
	$("#arrow-right").bind("click", function(){
		scrollClients(1);
	});
}

function openProject(project) {
	clearTimeout(scrollTimeout);
	scrollTimeoutFlag = false;
	var img = new Image();
	img.src = '/images/home/projects/'+project+'.jpg';
	img.onload = function() {
		var title = "<div id='title-div'>"+clients[currentClient].projects[project].title+"</div>";
		if (clients[currentClient].projects[project].url) {
			title += "<div id='url-div'><a href='"+clients[currentClient].projects[project].url+"' target='_blank'>"+clients[currentClient].projects[project].url+"</a></div>"
		}
		if (clients[currentClient].projects[project].casestudy) {
			title += "<div id='casestudy-div'><a href='' onclick='openCaseStudy(\""+clients[currentClient].projects[project].casestudy+"\"); return false;'>Case Study</a></div>"
		}
		$.fn.colorbox({
			title: title,
			html:   "<img src='/images/home/projects/"+project+".jpg'/>",
			open:   true,
			iframe: false,           
			width:  (this.width+50)+"px",
			height: (this.height+70)+"px"
		});
	};
}

function openCaseStudy(url) {
	$.fn.colorbox({
		href: url,
		width: "650px",
		height: "400px",
		open:   true,
		iframe: false
	});
}

/**
 * @return void
 */
function scrollClients(increment) {
	clearTimeout(scrollTimeout);
	$("#arrow-right").unbind("click");
	$("#arrow-left").unbind("click");
	
	if (!increment) {
		increment=1;
	}
	if (increment>1) {
		increment = 1;
	}
	if (increment<-1) {
		increment = -1;
	}
	
	
	var targetLeft = parseInt($("#clients-slider").css("left")) - (increment * Math.round(clients[currentClient].logo.width/2)) - ( increment * Math.round(clients[arrayWrap(currentClient+increment)].logo.width/2) );
	$("#clients-slider").animate({
			left: targetLeft
	}, 400, "swing", function() {positionAndAddClientsSlider(increment); });
	
	$("#logo_"+arrayWrap(currentClient+increment)).animate({
		opacity:1
	}, 400, "swing");
	
	$("#logo_"+currentClient).animate({
		opacity:.5
	}, 400, "swing");
	
	if ($("#testimonial").css("opacity") > 0) {
		$("#testimonial").animate({
			opacity:0
		}, 200, "swing", hideTestimonial);
	}
	
	if ($("#projects").css("opacity")==1) {
		$("#projects").animate({
			opacity:0
		}, 400);
	}
}

var hideTestimonial = function() {
	$("#testimonial").css("visibility", "hidden");

}