//addthis variables
var addthis_pub="audiodocumentarydotorg";

function toSlug(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  
  // remove accents, swap ñ for n, etc
  var from = "ÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛàáäâèéëêìíïîòóöôùúüûÑñÇç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuuaaaaeeeeiiiioooouuuunncc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from[i], "g"), to[i]);
  }

  str = str.replace(/[^a-zA-Z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .toLowerCase();
  return str;
}

function toDescription(str) {
	str = str.replace(/\<p\>/g, '');
	return str.replace(/\<\/p\>/g, '<br />');
}

function setToolTips() {
	$('[title]').tooltip({
		showURL:false,
		track: true,
		fade:200
	});
}

function hideToolTips(){
	$('#tooltip').hide();
}

function disableRelated() {
	$('div.relatedMain').unbind('click').click(function() {
		return false;
	});
}
function enableRelated() {
	$('div.relatedMain').unbind('click').click(function() {
		hideToolTips(); //disable
		disableRelated();
		var clicked = $(this);
		clicked.css('opacity', .5);
		$('#featuredAudio').css('opacity', .1);
		
		
		var thisH4 = $(this).children()[0];
		var thisA = $(thisH4).children()[0];

		var thisId = $(thisA).attr('id').split('_')[1];
		
		var featuredId = $('#featuredAudio table').attr('id').split('_')[1];
		
		var fl = featured.length;
		var newFeatured = {};
		var oldFeatured = {};
		for (var i=0; i<fl; i++) {
			if (featured[i].id == thisId) {
				newFeatured = featured[i];
			} else if (featured[i].id == featuredId) {
				oldFeatured = featured[i];
			}
		}
		
		var featuredHeight = $('#featuredAudio').height();
		$('#featuredAudio').height(featuredHeight+'px').css('overflow', 'hidden');
		
		//image
		if (newFeatured.filename) {
			$('#featuredImage img').attr('src', root+'img/uploads/med_'+newFeatured.filename).show();
		} else {
			$('#featuredImage img').hide();
		}
		//title
		$('#featuredAudio h3').html('<a target="_blank" href="'+newFeatured.url+'">'+newFeatured.title+'</a>');
		//media
		$('#featuredAudio span.media').html(newFeatured.media_player);
		//description
		$('#featuredAudio p.description').html(toDescription(newFeatured.description));
		//info
		var info = [];
		if (newFeatured.Producer.length && newFeatured.Producer.id) {
			info.push('Producer: <a href="'+root+'audio/producedBy/'+toSlug(newFeatured.Producer.name)+'">'+newFeatured.Producer.name+'</a>');
		}
		if (newFeatured.Program.length && newFeatured.Program.id) {
			info.push('Program: <a href="'+root+'audio/playedOn/'+toSlug(newFeatured.Program.name)+'">'+newFeatured.Program.name+'</a>');
		}
		if (newFeatured.Audio != undefined) {
			var audio = newFeatured.audio;
			if (audio['playtime']) {
				info.push('Playtime: '+audio['playtime']);
			}
			if (audio['date_recorded']) {
				info.push('Date: '+audio['date_recorded']);
			}
		}
		if (info.length) {
			var infoText = '<h4>INFO</h4><p class="info">';
			var il = info.length;
			for (var i = 0; i < il; i++) {
 				infoText += info[i];
				if (i < (il - 1)) {
					infoText += '<br />';
				}
			}
			infoText += '</p>';
			$('#featuredInfo').html(infoText);
		} else {
			$('#featuredInfo').html(' &nbsp;');
		}
		//tags
		var tagLength = newFeatured.Tag.length;
		var tags = '';
		if (tagLength) {
			for (var i=0; i<tagLength; i++) {
				var tag = newFeatured.Tag[i];
				var href = root+'audio/taggedWith/'+toSlug(tag.name);
				tags += '<a class="brown" href="'+href+'">'+tag.name+'</a>, ';
			}
			var strlen = tags.length - 2;
			tags = tags.substr(0, strlen);
			$('#featuredTags').html('<h4>TAGGED WITH</h4><p class="info">'+tags+'</p>');
		} else {
			$('#featuredTags').html(' &nbsp;');
		}
		
		//do the new featured thing...
		var tableHeight = $('#featuredAudio table').height() + 20; //add a little padding
		$('#featuredAudio').animate({'height':tableHeight+'px'}, 500, function() {
			$(this).animate({'opacity':1}, 200);
		}).css('overflow', 'hidden');
		
		//now slide up with the replacement html for what was clicked
		var newhtml = '<h4><a class="related" href="'+root+'audio/view/'+oldFeatured.id+'" id="audio_'+oldFeatured.id+'" title="click to view">'+oldFeatured.title+'</a></h4><p class="description">'+toDescription(oldFeatured.description)+'</p>';
		
		clicked.html(newhtml);
		clicked.css('opacity', 1);	
		clicked.show('slide', {direction:'up'}, 500);
		
		//finally, set the featured audio table id..
		$('#featuredAudio table').attr('id', 'audio_'+thisId);

		enableRelated();
		
		return false;

	});
}

$(function() {
	enableRelated();
	setToolTips();
	//set the #related height to what it is so that when things slide up and down the height doesn't change...
	var relatedHeight = $('#related').height();
	$('#related').css('height',relatedHeight+'px');
	$('#related').children().each(function() {
		if ($(this).attr('id') != 'bottom') {
			$(this).css('height', relatedHeight+'px');
		}
	});
	
	//stuff from the gallery prototype -- json stuff...
	$('#TB_ajaxContent form').ajaxForm({
		success: process
	});

	function showRequest(formData, jqForm, options) { 
	    var queryString = $.param(formData); 
	    alert('About to submit: \n\n' + queryString); 
	    return true; 
	}

	function process(data) {
		if (data.substring(0, 1) == '{') {
			//it validated and we are dealing with json
			var data = eval('('+data+')');
			if (data.success) {
				if(data.update) {
					if (data.newContent) {
						$('#'+data.update).html(data.newContent);
						tb_remove();
					} else {
						//we have to get the content from the onSuccess url that was provided
						updateId(data.update, data.onSuccess);
					}
				} else if (data.alert) {
					//just close the thing
					alert(data.alert);
					tb_remove();
				} else {
					//just remove it...
					tb_remove();
				}
			}
		} else {
			//update the window with the error messages or whatever
			$('#TB_ajaxContent').html(data);
		}
	}
	
	function updateId(update, url) {
		$('#'+update).load(url, function() {
			tb_remove();
		});
	}
});