var g_ALFRESCO_BASE_URL = "http://www.just-a-minute.org/alfresco";
var g_ALFRESCO_QUERY_URL = g_ALFRESCO_BASE_URL + "/service/mediastream/list?guest=true&format=json&site=jam";
var g_AUDIO_PLAYER = "/flash/player.swf";
var g_FLOWPLAYER = "/flash/flowplayer-3.1.3.swf";

$(document).ready(function(){
	$("div.tab a").each( function(tab){
		$("div.tab a").click(function(){
			$("div.tab").removeClass( 'selected_tab' );
			$(this).parent().addClass( 'selected_tab' );
			var linkid = $(this).attr("id");
			var linkrep = linkid.replace('_link', '_tab');
			$("div.tab-item").css("display","none");
			$("#"+linkrep).css("display","block");
		});
		if($(this).parent().attr("class").indexOf("selected_tab") > -1)
			$(this).click();
	});
	 //Hide and Show Text
	$('.more').each(function() {
		$(this).css("display","none");
	});
	$(".read-more_btn").click(function(){
		var div = '';
		div = $(this).parent();
		if($(this).html()=="read more") {
			$(div).prev().css("display","block");
			$(this).html("read less");
		}
		else if($(this).html()=="read less") {
			$(div).prev().css("display","none");
			$(this).html("read more")
		}
	});
});
var subTabs = {
	init: function() {
		$(".subtabs .subtab a").each( function(i) {
			$(this).click(function() {
				$(".subtabs .subtab a").removeClass("selected_subtab");
				$(this).addClass("selected_subtab");
				$(".subtab-panels div").css("display", "none");
				$(".subtab-panels div").eq(i).css("display", "block");
				var tableId = $(".media-table", $(".subtab-panels div").eq(i)).attr("id");
				if (tableId != null)
					mediaTable.buildAudio(tableId, tableId);
			});
		});
		$(".subtabs .subtab a").eq(0).addClass("selected_subtab");
		$(".subtab-panels div").css("display", "none");
		$(".subtab-panels div").eq(0).css("display", "block");
	}
};
var mediaTable = {
		startRow: 0,
		limit: 100,
		appContext: '',
		// Build media table
		buildAudio: function(tag, tableId) {
	        if ($("#" + tableId + " tbody").children().size() > 0)
	        	return;
	        var ctx = this.appContext;
		    var url = g_ALFRESCO_QUERY_URL + "&type=audio&start=" + this.startRow + "&limit=" + this.limit + "&ctg=" + tag + "&alf_callback=?";
		    $.getJSON(url, function(json) {
                    //    $.get(url, function(json1) {
                    //        json = eval('(' + json1 + ')');
		        for (var i = 0; i < json.list.length; i++) {
		        	var str = '';
			        var overlay = '';
		            var file = json.list[i];
		            //TODO: Make configurable
		            str += '<tr>' + 
		                    '<td class="media-name first-col">' + file.title + '<br/><span>By ' + file.author + '</span></td>' +
		                    '<td class="media-player flash"><a href="' + g_ALFRESCO_BASE_URL + file.downloadUrl + "\"><img src=\"" + ctx + "/images/download.gif\" title=\"Download with background music\" alt=\"Download with background music\"/></a>&nbsp;" + '<a href="' + g_ALFRESCO_BASE_URL + file.downloadUrl + "\" class=\"audio-link\">&nbsp;</a>" +
		                    "</td>";
		            if (file.relatedFiles.length > 0) {
		            	for (n = 0; n < file.relatedFiles.length; n++) {
		            		if (file.relatedFiles[n].mimetype == "audio/x-mpeg") {
		            			str += '<td class="media-player flash"><a href="' + g_ALFRESCO_BASE_URL + file.relatedFiles[n].downloadUrl + "\"><img src=\"" + ctx + "/images/download.gif\" title=\"Download without background music\" alt=\"Download without background music\"/></a>&nbsp;" + '<a href="' + g_ALFRESCO_BASE_URL + file.relatedFiles[n].downloadUrl + "\" class=\"audio-link\">Play audio</a>" +
		            				   "</td>";
		            		}
		            		else
		            			str += '<td class="media-player">Not available</td>';
		            	}
		            }
		            else
		            	str += '<td class="media-player">Not available</td>';
		            if (file.description == null || jQuery.trim(file.description) == "")
		            	str += '<td>&nbsp;</td>';
		            else {
		            	str += "<td class=\"last-col\"><a rel=\"#overlay_" + tableId + i + '" class="media-text" href="javascript:void(0)">&nbsp;</a></td>';
		            	overlay += '<div class="overlay" id="overlay_' + tableId + i + '"><h3>' + file.title + '</h3><div class="overlay-content">' + file.description + '</div></div>';
		            }
		            str += "</td></tr>";
		            $("#" + tableId + " tbody").append(str);
			        $("body").append(overlay);
		        }
		        mediaTable.update(tableId);
		    });
		},
		randomAudio: function() {
			var overlay = $("#random_audio").children(":not(.close)").remove();
			var randomnumber=Math.floor(Math.random()*42);
			var url = g_ALFRESCO_QUERY_URL + "&type=audio&start=" + randomnumber + "&limit=1&ctg=7steps&alf_callback=?";
			var ctx = this.appContext;
			$.getJSON(url, function(json) {
                        //$.get(url, function(json1) {
                        //    json = eval('(' + json1 + ')');
				if (json.list.length > 0) {
					var meditation = json.list[0];
					var overlayStr = 
								  "<h3>" + meditation.title + " <span>By " + meditation.author + "</span></h3>" +
								  "<div class=\"player\"><a href=\"" + g_ALFRESCO_BASE_URL + meditation.downloadUrl + "\" class=\"audio-link\">Download meditation</a></div>" +
								  "<div class=\"next\"><a href=\"javascript:void(0)\">Next meditation &gt;&gt;</a></div>" +
								  "<div class=\"clear\"><!-- Collapse fix --></div>" +
								  "<div class=\"overlay-content\">" + meditation.description + "</div>";
					$("#random_audio").append(overlayStr);
					var flashAnchor = $("#random_audio a.audio-link");
					flashAnchor.css('display', 'none');
					flashAnchor.flash(
	        		{ src: ctx + g_AUDIO_PLAYER, height: 22, width:210, id: 'audio' + mediaPlayer.id, wmode: 'transparent'},
					{ version: 7 },
					function(htmlOptions) {
						htmlOptions.flashvars.soundFile = flashAnchor.attr('href');
						htmlOptions.flashvars.track = '0xFBFAFA';
						htmlOptions.flashvars.playerID = mediaPlayer.id;
						htmlOptions.flashvars.autostart = 'yes';
						flashAnchor.before($.fn.flash.transform(htmlOptions));						
					}); 
					$("#random_audio div.next a").click(function() {
						mediaTable.randomAudio();
					});
					$("#strapline a").overlay({
	                      effect: 'apple',
	                      closeOnClick: false,
	                      expose: '#123448',
	                      api: true
	                  }).load();
				}
			});
		},
		randomVideo: function() {
			var overlay = $("#random_video").children(":not(.close)").remove();
			var randomnumber=Math.floor(Math.random()*6);
			var url = g_ALFRESCO_QUERY_URL + "&type=video&start=" + randomnumber + "&limit=1&ctg=testimonial&alf_callback=?";
			var ctx = this.appContext;
			$.getJSON(url, function(json) {
                        //$.get(url, function(json1) {
                        //    json = eval('(' + json1 + ')');
				if (json.list.length > 0) {
					var video = json.list[0];
					var overlayStr = "<h3>" + video.title + "</h3>" +
									     "<div class=\"overlay-content\">" +
									       video.description +
									       "<a href=\"" + g_ALFRESCO_BASE_URL + video.downloadUrl + "\" class=\"player\" id=\"video_player99\" style=\"display:block;width:440px;height:330px\">&nbsp;</a>" +
									     "</div>";
					$("#random_video").append(overlayStr);
					$("#random_video div.overlay-content").css("height", "374px");
				}
				flowplayer("video_player99", ctx + g_FLOWPLAYER);
				$("#random_video").overlay({
                    effect: 'apple',
                    closeOnClick: false,
                    expose: '#123448',
                    api: true,
                    onLoad: function() {
            		    var p = this.getContent().find("a.player");
            		    if (p.attr("id") && p.attr("id").indexOf("video") >= 0)
            		    	p.flowplayer(0).load();
	                }
                }).load();
			});
		},
		buildVideo: function() {
			if ($("#testimonials_tab .testimonial-box").size() > 0)
				return;
			var url = g_ALFRESCO_QUERY_URL + "&type=video&start=" + this.startRow + "&limit=" + this.limit + "&ctg=testimonial&alf_callback=?";
			var ctx = this.appContext;
		    $.getJSON(url, function(json) {
                    //    $.get(url, function(json1) {
                    //        json = eval('(' + json1 + ')');
		    	for (var i = json.list.length - 1; i >= 0; i--) {
		    		var str = '';
			        var overlay = '';
		    		var video = json.list[i];
		    		if (i % 5  == 0)
		    			str = str + "<div class=\"testimonial-box first_testimonial\">";
		    		else
		    			str = str + "<div class=\"testimonial-box\">";
		    		str = str + "<a rel=\"#video_overlay" + i + "\" href=\"" + g_ALFRESCO_BASE_URL + video.downloadUrl + "\" title=\""+ video.title + "\" class=\"video_title\">";
		    		if (video.overlayImage != "") 
					    str = str + "<img src=\"" + g_ALFRESCO_BASE_URL + getGuestDownloadUrl(video.overlayImage, false) + "\"/>";
		            else 
		                str = str + "<img src=\"" + ctx + "/images/testimonialspic1.jpg\"/>";
		    		str = str + "</a><span>" + video.title + "</span>";
		    		//str += "<a rel=\"#video_overlay" + i + "\" href=\"" + g_ALFRESCO_BASE_URL + video.downloadUrl + "\" title=\""+ video.title + "\" class=\"video_title\">" + video.title + "</a></div>";
		    		$("#testimonials_tab h2").after(str);
		    		overlay += "<div class=\"overlay\" id=\"video_overlay" + i + "\">" +
		    				     "<h3>" + video.title + "</h3>" +
		    				     "<div class=\"overlay-content\">" +
		    				       video.description +
		    				       "<a href=\"" + g_ALFRESCO_BASE_URL + video.downloadUrl + "\" class=\"player\" id=\"video_player" + i + "\" style=\"display:block;width:440px;height:330px\">&nbsp;</a>" +
		    				     "</div>" +
		    				   "</div>";
		    		$("body").append(overlay);
		    		flowplayer("video_player" + i, ctx + g_FLOWPLAYER);
		    	}
		    	mediaTable.update("testimonials_tab");
		    });
		},
		buildHomePageVideo: function() {
			if ($("#homepage-right").size() > 1)
				return;
			var url = g_ALFRESCO_QUERY_URL + "&type=video&ctg=testimonial&alf_callback=?";
			var ctx = this.appContext;
			$.getJSON(url, function(json) {
//                        $.get(url, function(json1) {
//                            json = eval('(' + json1 + ')');
			    var videos = json.list;
			    videos.sort(function() {return 0.5 - Math.random();});
		    	for (var i = 0; i < 6; i++) {
		    		var str = '';
			        var overlay = '';
		    		var video = videos[i];
		    		str += "<a href=\"#\" rel=\"#video_overlay" + i + "\" title=\""+ video.title + "\">";
		    		if (video.overlayImage != "") 
					    str += "<img src=\"" + g_ALFRESCO_BASE_URL + getGuestDownloadUrl(video.overlayImage, false) + "\" width=\"117\" height=\"71\"/>";
		            else 
		                str += "<img src=\"" + ctx + "/images/testimonialspic1.jpg\" width=\"117\" height=\"71\"/>";
		    		str += "</a>";
		    		$("#homepage-right h2").after(str);
		    		overlay += "<div class=\"overlay\" id=\"video_overlay" + i + "\">" +
		    				     "<h3>" + video.title + "</h3>" +
		    				     "<div class=\"overlay-content\">" +
		    				       video.description +
		    				       "<a href=\"" + g_ALFRESCO_BASE_URL + video.downloadUrl + "\" class=\"player\" id=\"video_player" + i + "\" style=\"display:block;width:440px;height:330px\"></a>" +
		    				     "</div>" +
		    				   "</div>";
		    		$("body").append(overlay);
		    		flowplayer("video_player" + i, ctx + g_FLOWPLAYER);
		    	}
		    	mediaTable.update("homepage-right");
		    });
		},
        update: function(containerId) {
        	mediaPlayer.add(containerId, this.appContext + g_AUDIO_PLAYER);
            $("#" + containerId + " a[rel]").each( function(i) {
	            	$(this).overlay({
	            		effect: 'apple',
	            		closeOnClick: false,
	            		expose: '#123448',
	            		onLoad: function() {
	            		    var p = this.getContent().find("a.player");
	            		    if (p.attr("id") && p.attr("id").indexOf("video") >= 0)
	            		    	p.flowplayer(0).load();
		                }
	            	});
            });
        }
};
// Inject audio player into selected flash elements
var mediaPlayer = {
		id : 1,
		addAll: function(){
		    $(".flash a").each( function(el) {
				$(this).css('display', 'none');
				$(this).flash(
				{ src: mediaTable.appContext + g_AUDIO_PLAYER, height: 18, width: 212, id: 'audio' + mediaPlayer.id, wmode: 'transparent' },
				{ version: 7 },
				function(htmlOptions) {
					$this = $(this);
					htmlOptions.flashvars.soundFile = $this.attr('href');
					htmlOptions.flashvars.track = '0xFBFAFA';
					htmlOptions.flashvars.playerID = mediaPlayer.id;
					$this.before($.fn.flash.transform(htmlOptions));						
				});
				mediaPlayer.id = mediaPlayer.id + 1;
		    });
		},
		add: function(tableId, player){
			$("#" + tableId + " .flash a.audio-link").each( function(el) {
				$(this).css('display', 'none');
				$(this).flash(
        		{ src: player, height: 22, width:210, id: 'audio' + mediaPlayer.id, wmode: 'transparent'},
				{ version: 7 },
				function(htmlOptions) {
					$this = $(this);
					htmlOptions.flashvars.soundFile = $this.attr('href');
					htmlOptions.flashvars.track = '0xFBFAFA';
					htmlOptions.flashvars.playerID = mediaPlayer.id;
					$this.before($.fn.flash.transform(htmlOptions));						
				});
        		mediaPlayer.id = mediaPlayer.id + 1;
          });
		},
		addFullSize: function(tableId, player){
			$("#" + tableId + " .flash a").each( function(el) {
	        	  $(this).css('display', 'none');
	        		  $(this).flash(
	        		{ src: player, height: 30, width: 300, id: 'audio' + mediaPlayer.id },
					{ version: 7 },
					function(htmlOptions) {
						$this = $(this);
						htmlOptions.flashvars.soundFile = $this.attr('href');
						htmlOptions.flashvars.track = '0xFBFAFA';
						htmlOptions.flashvars.playerID = mediaPlayer.id;
						$this.before($.fn.flash.transform(htmlOptions));						
					});
	        		mediaPlayer.id = mediaPlayer.id + 1;
	          });
		}
};

function getGuestDownloadUrl(url, attach){
	var posn = url.indexOf("/workspace/");
	var guestDownloadUrl="";
	if(posn > 0){
		if(attach == true)
			guestDownloadUrl = "/guestDownload/attach"+ url.substr(posn);
		else
			guestDownloadUrl = "/guestDownload/direct"+ url.substr(posn);
	}
	else{
		guestDownloadUrl= url;
	}
	return guestDownloadUrl;
}

/* Cycle lite, jquery plugin necessary for rotating images */
(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery)

