var playcount=0;
var itemWidth="390px";
var currentPage=1;
var filter="all";
var COOKIE_NAME = 'test_cookie';


//http://www.sayhear.org/data/shouts/all.xml?per_page=25&page=2

jQuery().ready(function(){
	
	/*
	
	jQuery.browser 	
	jQuery.browser.version
	
	
	
	*/
	
	var id = parseUri(location.href).queryKey.id
	if(id)
	{
		//showSingleItem(id);
		//return;
	}
	
	$('#welcome').jqm();
	$('#error').jqm();
	$('#about').jqm();
	
	if(!$.cookie(COOKIE_NAME))
	{
		var date = new Date();
		date.setTime(date.getTime() + (10 * 24 * 60 * 60 * 1000));
		$.cookie(COOKIE_NAME, 'test', { path: '/', expires: date });
		$('#welcome').jqmShow();
	}
	
	//$('#dialog').jqmHide(); 
	
	$("#navigation a").click(function(){
		$.blockUI({ message: '' });
	
		var cls = ($(this).attr("class"))?$(this).attr("class"):'';
		
		var xmlURL='';
		switch(cls)
		{
			case 'dem':
				filter='democrat';
				currentPage=1;
				xmlURL='/data/shouts/democrat';
				break;
			case 'repub':
				filter='republican';
				currentPage=1;
				xmlURL='/data/shouts/republican';
				break;
			case 'third':
				filter='thirdparty';
				currentPage=1;
				xmlURL='/data/shouts/thirdparty';
				break;
			case 'undecided':
				filter='undecided';
				currentPage=1;
				xmlURL='/data/shouts/undecided';
				break;
			case 'next':
				currentPage++;
				xmlURL='/data/shouts/'+filter+'/page/'+currentPage;
				break;
			case 'prev':
				currentPage=(currentPage>1)?currentPage-1:1;
				xmlURL='/data/shouts/'+filter+'/page/'+currentPage;
				break;
			case 'reset':
				currentPage=1
				xmlURL='/data/shouts/'+filter+'/page/'+currentPage;
				break;	
			default :
				filter='all';
				currentPage=1;
				break;
		}
		
		
		getContent(xmlURL);
	})
	
	$('#navigation a.democrat').click(function()
	{
		//do something
	})
	
	$("#opinions li").animate({ 
		width:itemWidth
	}, { queue:false, duration:1000, easing:'easeInOutCubic' } );
	
	//initializeElements();
	getContent();
	
	$('#about_project').click(function()
	{
		$('#about').jqmShow();
	});
		 
});

function showSingleItem(id)
{
	//http://www.sayhear.org/data/shouts/get/121
	
	$.ajax({
		url: 'http://www.sayhear.org/data/shouts/'+id,
	    type: 'GET',
	    dataType: 'xml',
	    timeout: 8000,
	    error: function(){
	       getContent();
	    },
	    success: function(xml){
		
			$(this).find("content")
			
	    }
	});	
}


function addItemToList(elem)
{
	$(elem).appendTo("#opinions");
	
	elem.animate({ 
		width:itemWidth
	}, { queue:false, duration:1000, easing:'easeInOutCubic' } );
}

function emphasize()
{
	var bg="#000000";
	if($(this).hasClass("democrat")) bg="#33BFF4";
	else if($(this).hasClass("republican")) bg="#FF3351";
	else if($(this).hasClass("undecided")) bg="#8B8B8B";
	else if($(this).hasClass("thirdparty")) bg="#53C73E";
	
	$(this).animate({backgroundColor:bg},{queue:false, duration:300});
}

function deemphasize()
{
	var bg="#000000";
	if($(this).hasClass("democrat")) bg="#1ba8da";
	else if($(this).hasClass("republican")) bg="#f60f2c";
	else if($(this).hasClass("undecided")) bg="#6d6d6d";
	else if($(this).hasClass("thirdparty")) bg="#40b02c";
	
	$(this).animate({backgroundColor:bg},{queue:false, duration:300});
}

function removeAudioPlayer()
{
	
	if($(".playing").children(".container"))
	{
		$(".playing").children(".container").animate({
			opacity:1
		}, { queue:false, duration:300 })
		$(".audioplayer .controls").remove();
	}
	
	$(".playing").removeClass("playing");
	
	var id=$(this).attr("id")+"audioplayer";
	
	var objects = $("object");

	if(thisMovie(id)) thisMovie(id).destroy();
	var divId = $("object").parent("div").parent("li").attr("id");
	$("object").replaceWith('<div id="'+divId+'flash"></div>');
}

function initializeElements()
{
	
	$("#opinions li").hoverIntent( emphasize, deemphasize);
	
	$("#content li").click(function()
	{		
		var obj = $(this).children("object");
		
		if($(this).children("object").length>0||$(this).hasClass("playing")) return;
		
		/*
		if($(".playing").children(".container"))
		{
			$(".playing").children(".container").animate({
				opacity:1
			}, { queue:false, duration:300 })
			$(".audioplayer .controls").remove();
		}
		
		$(".playing").removeClass("playing");
		
		var id=$(this).attr("id")+"audioplayer";
		
		var objects = $("object");
	
		if(thisMovie(id)) thisMovie(id).destroy();
		var divId = $("object").parent("div").parent("li").attr("id");
		$("object").replaceWith('<div id="'+divId+'flash"></div>');
		*/
		
		removeAudioPlayer();
		var id=$(this).attr("id")+"audioplayer";
		$(this).addClass("playing");
		
		
		$(".ontop").remove(); //hack to remove adblock tab on removed audio player. I'm tempted to remove it on any created swf, but I'll play nicely. :)
		
		var flashvars = {};
		
		flashvars.url = $(this).find(".listen").attr("href");
		
		flashvars.autoplay="true";

		var params = {
			menu: "false",
			wmode: "transparent",
			allowscriptaccess: "always"
		};
		var attributes = {
			id: id,
			name: id
		};
		
		swfobject.embedSWF("swf/SayHearAudioPlayer.swf", $(this).attr("id")+"flash", "290", "60", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	
		$(this).children(".audioplayer").append('<div class="controls"><a class="close">Close</a><a class="permalink" href="'+$(this).find(".listen").attr("href")+'" target="_blank">Link</a></div>');
	
		
		//<a class="permalink" href="'+$(this).find(".listen").attr("href")+'">Link</a></div>
		//<a class="permalink" href="http://sayhear.org?id='+$(this).attr("id").substring(1)+'">Link</a></div>
		/*
		$(this).find(".close").click(function()
		{
			console.log("close click");
			removeAudioPlayer();
		});
		*/
		
		$(this).find(".close").bind("click", function(evt){
				removeAudioPlayer();
		       evt.stopPropagation();
		});
		
		
		$(this).children(".container").animate({
			opacity:0
		}, { queue:false, duration:300 })
	});
}

function removeAll()
{
	
	$("#opinions li").mouseover=null
	$("#opinions li").mouseout=null
	
	$("#opinions li").animate({ 
		width:"0px"
	}, { queue:false, 
		duration:(($("li").index(this))*100)+500, 
		easing:'easeInOutCubic',
		complete:function()
		{
			$(this).remove();
			if($("#opinions li").length==0) 	getContent();
		} 
		});
}

function emptyList()
{
	if($("#opinions li:last").width()==0)
	{
		$("#opinions").empty()
		getContent();
	}
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

function displayLoadError()
{
	$('#error').jqmShow();
}

function addItems(xml)
{
	var itms_per_page = $(xml).find("opinions").attr("per_page");
	var current_page = $(xml).find("opinions").attr("current_page");
	var total = $(xml).find("opinions").attr("total_entries");
	
	var start = ((current_page-1)*itms_per_page)+1;
	var end = (current_page)*itms_per_page;
	if(end>total) end=total;
	
	if(start<total)$("#nav_metadata").html(start+' - '+end+' of '+total);
	
	$(xml).find('opinion').each(function(){
		var item_text = $(this).text();
		
		var container = $('<div class="container"></div>')
		.append($('<div class="content"></div>'));
		
		var content=container.find('.content');
		
		var voting = ($(this).find("votingFor").text()=="Undecided")?"Not Voting":$(this).find("votingFor").text();
		
		content.append($('<h3>'+voting+'</h3>')
		.append()
		);
		
		content.append($('<h5></h5>')
		.append($(this).find("month").text()+"/"+$(this).find("day").text()+"/"+$(this).find("year").text()+" at "+$(this).find("time").text())
		);
		
		var loc = ($(this).find("area_code").text())?'Area Code  '+$(this).find("area_code").text()+', '+$(this).find("state_abbr").text():'Location unknown'
		
		content.append($('<h4></h4>')
		.append(loc)
		);
		
		var listens = '<dl class="metadata">'+
						'<dt>Listens</dt>'+
						'<dd class="listen_count">'+$(this).find("listens").text()+'</dd>'+
						'<dd class="audiotype '+$(this).find("content").attr("type")+'">'+$(this).find("content").attr("type")+'</dd>'+
						'</dl>'; 
						
		var mins = Math.floor(($(this).find("content").attr("duration") % (60*60)) / (60));
		var secs = Math.floor((($(this).find("content").attr("duration") % (60*60)) % (60))); 
		
		if(secs<10) secs='0'+secs;				
		
		container.append($('<dl class="metadata"></dl>')
		.append($('<dt></dt>')
		.text("Length"))
		.append($('<dd class="listen_count"></dd>')
		.append(mins+":"+secs))
		);
		
		//.append($(this).find("listens").text()))
		
		var flash = $('<div class="audioplayer"><div id="t'+$(this).attr('id')+'flash'+'"></div></div>');
		var mp3= $('<a href="'+$(this).find("content").text()+'" class="listen"></a>').text("Click to Listen");
		
		var itm = $('<li class="clearfix"></li>')
		.append(container)
		.append(flash)
		.append(mp3);
			
			//console.log(content);
		itm.addClass($(this).find("votingFor").attr("party"));
		itm.attr({id:"t"+$(this).attr("id")});
		addItemToList(itm)
	});
}

function getContent(xmlurl)
{
	if(!xmlurl) xmlurl='/data/shouts/all';
	$.ajax({
	    //url: 'data/data.xml.php',
		url: xmlurl,
	    type: 'GET',
	    dataType: 'xml',
	    timeout: 16000,
	    error: function(){
	        displayLoadError();
			$.unblockUI();
	    },
	    success: function(xml){
		
			//alert($(xml).find("opinion").length);
			
			var len = $(xml).find("opinion").length;
			
			if(len==0&&currentPage!=1) 
			{
				currentPage=1;
				xmlURL='/data/shouts/'+filter+'/page/'+currentPage;
				getContent(xmlURL);
			} else if(len==0&&currentPage==1)
			{
				currentPage=1;
				xmlURL='/data/shouts/all.xml';
				getContent(xmlURL);
			}

		
		
			if($("#opinions li").length>0)
			{
				$("#opinions li").animate({ 
					width:"0px"
				}, { queue:false, 
					duration:700, 
					easing:'easeInOutCubic',
					complete:function()
					{
						$(this).remove();
						if($("#opinions li").length==0)
						{
							addItems(xml);
							initializeElements();
							$.unblockUI();
						}
					} 
				});
			} else {
				addItems(xml);
				initializeElements();
			}
			
	    }
	});
	
}
