var ie6;
if($.browser.msie && $.browser.version=="6.0"){
	ie6 = true;
}

// AddThis Configuration:
var addthis_config = {
	ui_click: true,
	ui_hover_direction: 1,
	ui_offset_top: -4
}

function carousel_itemLoadCallback(carousel, state)
{
	var currentIndex = carousel.currentIndex();
	
    if (!carousel.has(carousel.first, carousel.last)) {
		$.get(
			'/feeds/case_data/' + currentIndex + '/',
			{},
			function(data) {
				carousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
			},
			'json'
		);
    }
    //
    // Load item to the Left:
	if (currentIndex != 1 && !ie6){
    	var leftNum = currentIndex - 1;

    	if (!carousel.has(leftNum, leftNum)) {
			//alert("leftNum: " + leftNum + ", curent:" + currentIndex);
			$.get(
				'/feeds/case_data/' + leftNum + '/',
				{},
				function(data) {
					carousel_itemAddCallback(carousel, carousel.first, carousel.last, data, leftNum);
				},
				'json'
			);
		}
	}
    
    // Load item to the Right:
    if (currentIndex != carousel.size() && !ie6){
    	var rightNum = parseInt(currentIndex) + 1;
    	
    	if (!carousel.has(rightNum, rightNum)) {
    		//alert("rightNum: " + rightNum + ", curent:" + currentIndex);
			$.get(
				'/feeds/case_data/' + rightNum + '/',
				{},
				function(data) {
					carousel_itemAddCallback(carousel, carousel.first, carousel.last, data, rightNum);
				},
				'json'
			);
		}
    }
    
};

function carousel_itemAddCallback(carousel, first, last, data, numToLoad)
{
	if(numToLoad == undefined){
		idx = carousel.currentIndex();
	} else {
		idx = numToLoad
	}
	//alert(carousel + ", " + first + ", " + last + ", " + data + ", " + numToLoad);

	
	var item = carousel.add(idx, buildCard(idx, data));

	//Add This Button
	//var addThisButton = $(".addthis_button", item);
	addthis.button(".addthis_button");

	$(".case_card", item).fadeIn("def");


	if(firstload){
		firstload = false;

		$(".case_thumb", "#carousel_thumbs").bind("click", function(e){
			carousel.scroll(parseInt(this.rel));
			return false;
		});

		loadBioModules(carousel);
	}

};

function buildCard(idx, json)
{
	var html = "<div class='case_card'>";
	html += "<div class='column_1'>";
	html += "<a href='/case/" + json[0].pk + "'><h1>" + carousel_decodeEntities(json[0].fields['title']) + "<\/h1><\/a>";
	html += "<h2>" + carousel_decodeEntities(json[0].fields['description']) + "<\/h2>";
	html += "<a href='/case/" + json[0].pk + "' class='case_details'><span>Continue Reading...<\/span><\/a>";
	html += "<\/div>";
	html += "<div class='card_foot'>";
	html += "<a class='addthis_button'><img src='/site_media/images/icon_share_card.gif' /></a>";
	html += "<a href='http://www.twitter.com/edelsonmcguire' target='_blank' class='discuss_on_twitter'><img src='/site_media/images/icon_discuss_card.gif' /></a>";
	html += "<a href='#' onclick='javascript: window.print();' class='print_button'><img src='/site_media/images/icon_print_card.gif' /></a>";
	html += "<\/div>";
	html += "<\/div>";

	return html;
}

function hideAllModules(carousel, current, b, c, d){
	//alert("hideAllModules");
	//alert(carousel + ", " + current + ", " + b + ", " + c + ", " + d);
	$(current).addClass("selected");
	$(".module .content", "#module_containers").hide();
	$(".module", "#module_containers").addClass("loading");
}

function loadBioModules(carousel, last, lastNum, c, d){
	if(firstload){return;}
	
	//alert(carousel.currentIndex() + " | " + carousel + " | " + last + " | " + lastNum);
	location.hash = "#page_" + carousel.currentIndex();
	
	$("#case_thumb_" + lastNum, "#carousel_thumbs").removeClass("selected");
	$("#case_thumb_" + carousel.currentIndex(), "#carousel_thumbs").addClass("selected");
	var hash = $("#case_thumb_" + carousel.currentIndex(), "#carousel_thumbs").attr("href");
	
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);

	
	$(last).removeClass("selected");

	

    $.get(
        '/feeds/case_tags/' + carousel.currentIndex() + '/',
        {},
        function(data) {
			pullTweets(data);
        },
        'json'
    );

	$.get(
		'/feeds/case_relevant_blogs/' + carousel.currentIndex() + '/',
		{},
		function(data) {
			pullRelevantBlogs(data);
		},
		'json'
	);
}

// Pull Tweets
function pullTweets(data){
	var caseTags = data;
	var removeSpaces = caseTags.replace(/ /g, "+");
	var removeHash = removeSpaces.replace(/#/g, "%23");
	var removeAt = removeHash.replace(/@/g, "%40");
	
	var tagArray = removeAt.split(",");
	//var tagArray = caseTags.split(",");
	//for (i=0; i<tagArray.length; i++){
		//tagArray[i] = "'"+tagArray[i]+"'";
	//}
	var tagArrayStr = tagArray.toString().replace(/,/g, "+OR+");

	var tweetAmt = 5;
	var TweetHTML = ""; 
	var tweeturl = "http://search.twitter.com/search.json?callback=?&rpp=5&q=" + tagArrayStr;
	//alert(tweeturl);
	$.ajax({
		url: tweeturl,
		cache: false,
		dataType: "json",
		timeout: 5000,
		success: function(d){
			if(!d.results){
				$("#aggr_tweets .content").html("<h2>Nobody seems to be discussing this topic on Twitter. <a href='http://www.twitter.com/kamberedelson'>Start the discussion<\/a><\/h2>");
				$("#aggr_tweets").removeClass("loading");
				$("#aggr_tweets .content").fadeIn();
				return;
			}
			if(d.results.length > 0){
				TweetHTML += "<ul>";
				$.each(d.results, function(i, tweet){
					TweetHTML += "<li>";
					TweetHTML += "<img border='0' width='48' height='48' class='photo' src='" + tweet.profile_image_url + "' \/>";
					TweetHTML += "<span class='text'>" + tweet.text + "<\/span>";
					TweetHTML += "<span class='date'>" + relative_time(tweet.created_at) + "<\/span>";
					TweetHTML += "<div class='clear'><\/div>";
					//TweetHTML += "<span class='date'>" + tweet.created_at + "<\/span>";
					TweetHTML += "<\/li>";
				});
				
				TweetHTML += "<\/ul>";
				$("#aggr_tweets .content").html(TweetHTML);
				$("#aggr_tweets").removeClass("loading");
				$("#aggr_tweets .content").fadeIn();
			} else {
				$("#aggr_tweets .content").html("<h2>Nobody seems to be discussing this topic on Twitter. <a href='http://www.twitter.com/kamberedelson'>Start the discussion<\/a><\/h2>");
				$("#aggr_tweets").removeClass("loading");
				$("#aggr_tweets .content").fadeIn();
			}
		},
		error: function(XHR, textStatus, errorThrown){
			TweetHTML += "<h2>Twitter is DOWN :( " + textStatus + ", " + errorThrown +"<\/h2>";
			$("#aggr_tweets .content").html(TweetHTML);
			$("#aggr_tweets").removeClass("loading");
			$("#aggr_tweets .content").fadeIn();
        }		
	});
}
/*
function isUrl(s) {
ÊÊ Êvar regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
Ê   return regexp.test(s);
}
*/

function pullRelevantBlogs(json){
	var html = "<div class='resultset'>";
	for(var i=0; i<json.length; i++){
		html += "<div class='result'>";
		html += "<img src='/site_media/" + json[i].fields['icon'] + "' width='97' height='89' />";
		html += "<a href='" + json[i].fields['url'] + "' class='title'>" + json[i].fields['title'] + "<\/a>";
		html += "<p class='content'>" + json[i].fields['content'] + "<\/p>";
		html += "<p class='source'><em>Source:<\/em> <a href='" + json[i].fields['url'] + "' class='link'>" + json[i].fields['visibleUrl'] + "<\/a><\/p>";
		html += "<\/div>";
	}
	html += "<\/div>";
	$("#aggr_blogs .content").html(html);
	$("#aggr_blogs").removeClass("loading");
	$("#aggr_blogs .content").fadeIn();
}


function historyCallBack(hash){
	if(hash){
		var currentPageNum = hash.split("_")[1];
		locationHash = parseInt(currentPageNum);
	}
}


$(document).ready(function(){
	$.get(
		'/feeds/cases/',
		{},
		function(items) {
			
			var thumbsHTML = "<table cellspacing='0' cellpadding='0' border='0'><tr>";
			for(var i=1; i<=items[0].size; i++){
				thumbsHTML += "<td><a href='#page_" + i + "' class='case_thumb' id='case_thumb_" + i + "' rel='" + i + "' title='" + abbrString(items[0].fields[i], 20) + "'></a></td>";
			}
			thumbsHTML += "</tr></table>";
			$("#carousel_thumbs").html(thumbsHTML);
			$("a[title]", "#carousel_thumbs").qtip({
				style: {
					name: 'kestyle',
					tip: true
				},
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				}
			});

			// Initialize history plugin.
			// The callback is called at once by present location.hash. 
			$.historyInit(historyCallBack);
			
			glob_carousel = $('#carousel_cases').jcarousel({
				scroll: 1,
				//wrap: "circular",
				start: locationHash,
				size: items[0].size,
				initCallback: carousel_initCallback,
				itemLoadCallback: carousel_itemLoadCallback,
				itemVisibleInCallback: hideAllModules,
				itemVisibleOutCallback: loadBioModules,
				buttonNextHTML: "<a href='#' onclick='javascript: return false;'></a>",
				buttonPrevHTML: "<a href='#' onclick='javascript: return false;'></a>"

			});
			
		},
		'json'
	);
	
});




