var loading = false;
var requests = { };
var totalLoads = 4;
var reqLoads = 0;
var currSortUrl = "";
var disp;
var fade;
var panelHover;
var listHover;
var channelHover;
var channelBase;
var lastUrls = { };
var thumbTimer;
var tel;
//Prepare the player

//soundManager.debugMode = false;


//Prepare Play Link links
window.addEvent('domready', function( ) { 
	prepPlayLinks( );
	prepListThumbs( );
	prepPanelThumbs( );
	//applyPngFix( );

	if(window.ie) {
		var el = $('bodyFix');
		if(el) el.setStyle("overflow", "auto");
	}
});

function applyPngFix( ) {
	if(Browser.Engine.trident && Browser.Engine.version == 4) { 
		var arVersion = navigator.appVersion.split("MSIE");
		   var version = parseFloat(arVersion[1]);
		   if ((version >= 5.5) && (document.body.filters)) 
		   {
		      for(var i=0; i<document.images.length; i++)
		      {

			 var img = document.images[i];
			 var imgName = img.src.toUpperCase();
			 if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			 {
			    var imgID = (img.id) ? "id='" + img.id + "' " : "";
			    var imgClass = (img.className) ? "class='" + img.className + "' " : "";
			    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
			    var imgStyle = "display:inline-block;" + img.style.cssText; 
			    if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			    if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
			    var strNewHTML = "<span " + imgID + imgClass + imgTitle;
			    + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			    + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
			    img.outerHTML = strNewHTML;
			    i = i-1;
			 }
		      }
   		}    		
	}
}

function prepChannelThumbs(el) {
	if(!el) el = $$('body')[0];

	var ele = el.getElement('.channelImage');
	if(!channelHover) channelHover = el.getElement("#channelThumbHolder");
		


	if(ele && channelHover) {
		ele.addEvent("mouseenter", function(e) {
			var ev = new Event(e);
			displayThumbImage(
				this.id, ev, channelHover, ele, ".png", channelBase, 150
			);
		});
	}
}

function prepListThumbs(el) {
	if(!el) el = $$('body')[0];

	var els = el.getElements(".listThumb");
	if(!listHover) listHover = el.getElement("#listThumbHolder");

	if(els && listHover) {
		els.each(function(el) {
			el.addEvent("mouseenter", function(e) {
				var ev = new Event(e); 
				displayThumbImage(
					this.id, ev, listHover, el
				);
				ev.stopPropagation( );
			});		
		});
	}
}

function prepPanelThumbs(el) {
	if(!el) el = $$('body')[0];

	var els = el.getElements(".panelThumb");
	if(!panelHover) panelHover = el.getElement("#panelThumbHolder");

	if(els && panelHover) {
		els.each(function(el) {
			el.addEvent("mouseenter", function(e) {
				var ev = new Event(e); 
				displayThumbImage(
					this.id, ev, panelHover, el
				);
				ev.stopPropagation( );
			});		
		});
	}
}

function hideThumbImage(thumbEl) {
	if(disp) {
		if(fade) fade.cancel( );
		fade = new Fx.Tween(thumbEl);
		fade.start('opacity', 0).chain(function(el) {
			thumbEl.setStyle("display", "none");
		});
		disp = false;
	}
}

function displayThumbImage(id, ev, thumbEl, el, prefix, base, offX) {
	if(!disp) {
		var matches = id.match(/.*\-(\d+)/);
        if(!matches) return;

		clearTimeout(thumbTimer);
		if(fade) fade.cancel( );
		disp = true;

		var id = matches[matches.length - 1];

		var top =  el.getPosition( ).y;
		var left = el.getCoordinates( ).right;
		var winWidth = window.getWidth( );
		var winHeight = window.getHeight( );

		if(left + 180 > winWidth) left = winWidth - 180;

		var im = el.getElement("img");

		var ratio = im.height / im.width;
		thumbEl.getChildren( ).each(function(el) {
			el.dispose( );
		});
		var img = new Element("img");

		img.src = (base ? base : imgBase)+id+(prefix ? prefix : "-large.png");
		img.width = 180;
		img.height = ratio * 180;
		img.injectInside(thumbEl);
		thumbEl.setOpacity(0);
		thumbEl.setStyle("postition", "absolute");
		thumbEl.setStyle("display", "block");
		thumbEl.setStyle("z-index", "100000");

		thumbEl.setStyle("left", left);
		thumbEl.setStyle("top", top + 50);
		thumbEl.setStyle("width", 180);
		thumbEl.setStyle("height", 180 * ratio);

		thumbEl.removeEvents("mouseleave");
		thumbEl.addEvent("mouseleave", function(e) {
			clearTimeout(thumbTimer);
			var ev = new Event(e);
			hideThumbImage(thumbEl);
			ev.stopPropagation( );
		});
		el.addEvent("mouseleave", function(e) {
			clearTimeout(thumbTimer);
			var ev = new Event(e);
			hideThumbImage(thumbEl);
			ev.stopPropagation( );
		});

		tel = thumbEl;
		thumbTimer = setTimeout("dispThumb( )", 300);

	}
}

function dispThumb( ) {
	tel.tween('opacity', 1);
}


function prepPlayLinks(el) {
	var els = { };

	if(el) els = el.getElements('a.audio');
		else els = $$('a.audio'); 

	for(id in els) {
		if(els[id].addEvent) {
			els[id].addEvent('click', function(event) {
				if(pl) {
					pl.playUrl(
						this.href, false, false, true
					);
				}
				var e = new Event(event);
				e.stop( );
				return false;						
			});	
		}
	}

	if(el) els = el.getElements('a.video');
		else els = $$('a.video'); 	

	for(id in els) {
		if(els[id].addEvent) {
			els[id].addEvent('click', function(event) {
				if(pl) {
					pl.playUrl(
						this.href, false, false, true
					);
				}
				var e = new Event(event);
				e.stop( );
				return false;						
			});	
		}
	}		
}

//Prepare Channel Switching links
window.addEvent('domready', function( ) {
	if($('mainChannelLink')) {
		$('mainChannelLink').addEvent('click', function(event) {
			var e = new Event(event);
			e.stop( );
			return false;
		});
	}

	var els = $$('a.channelLink'); 
	for(id in els) {
		if(els[id].addEvent) {
			els[id].addEvent('click', function(event) {
				if(!content.href || content.href != this.href && !this.loading) {
                    $$('.hideOnChange').destroy();
					prepare(this.href);
					if(content.channel) {
						sendRequest(
							"channelDetails", 
							"http://"+controllerBase+"channel-details/"+
							content.channel
						);	
						sendRequest(
							"cPodcastList", 
							"http://"+controllerBase+"current-podcasts/"+
							content.channel
						);	
						sendRequest(
							"top-podcast-panel", 
							"http://"+controllerBase+"top-podcasts/"
							
						);	
						sendRequest(
							"feedLink", 
							"http://"+controllerBase+"feed-link/"+
							content.channel
							
						);	
				
					}
				}

				var e = new Event(event);
				e.stop( );
				return false;					
			});		
		}	
	}


	prepSortLinks($('cPodcastList'));	
	prepPaginationLinks($('cPodcastList'));


});

function setPrepUrl(t) { alert(t); }

function updateContent(id, text) {
	if(id=="channelDetails") {
		var el = new Element("div");
		el.set('html', (text));
		loadContent("channelDetails", el);
		reqLoads++;			
	}
	if(id=="cPodcastList") {
		var el = new Element("div");
		el.set('html', (text));
		reqLoads++;	
		loadContent("cPodcastList", el, text);
		prepListThumbs( );
	}
	if(id=="top-podcast-panel") {
		var el = new Element("div");
		el.set('html', (text));
		loadContent("top-podcast-panel", el);
		reqLoads++;
	}
	if(id=="feedLink") {
		var el = new Element("div");
		el.set('html', (text));
		loadContent("feedLink", el);
		reqLoads++;
	}

	checkReqLoads( );
}

function checkReqLoads( ) {
	if(reqLoads >= totalLoads) { 
		loadComplete( );
	}
}

function loadComplete( ) {
	var height = window.getHeight( );

    var t = new Fx.Tween($('loadPanel'));

	 t.start("top", height).chain(function() {


		$('loadPanel').setStyle("display", "none");
	});
	reset( );
}

function loadContent(id, el, raw) {
	var dets;
	dets = el.getElement("#"+id);
	
	if(!dets) {
		var kids = el.getChildren( );
		kids.each(function(el) {
			if(el.id == id) {
				dets = el;
			}
		});
	}

	if(dets) {
		if($(id)) {		
            var t= new Fx.Tween($(id), {duration: 300});
            t.start("opacity", 0).chain(function() {
				$(id).set('html', (dets.innerHTML));
				prepPlayLinks($(id));

				if(id == "cPodcastList") {
					prepSortLinks($(id));
					prepTracklist($(id), raw);
					prepPaginationLinks($(id));
					prepListThumbs($(id));
					prepChannelThumbs($(id));


                    if(Browser.Engine.trident && Browser.Engine.version == 4) {
                        $(id).getElements('.rating img').each(function(el) {
                            el.src = el.src.replace(".png", ".gif");
                        });
                    }

				} else if(id == "top-podcast-panel") {

                    if(Browser.Engine.trident && Browser.Engine.version == 4) {
                        $(id).getElements('.rating img').each(function(el) {
                            el.src = el.src.replace(".png", ".gif");
                        });
                    }

					prepPanelThumbs($(id));
				} else if(id == "channelDetails") {
					prepChannelThumbs($(id));
				}

				var fi = new Fx.Tween($(id), {duration: 300});
                fi.start("opacity", 1);

			});
		}
		
	}
}

function prepTracklist(el, raw) {
	var ch = el.getFirst( );

	if(ch.id == "tracklistVar") {
        var input = ch.getElement("input[name=playlistUrl]");
        if(input && pl) {
            pl.loadPlaylist(input.get('value'));
        }
	}
}

function prepPaginationLinks(el) {
	var prevLink = el.getElement("#prevPageLink");
	if(prevLink) {
		prevLink.removeEvents("click");
		prevLink.addEvent("click", function(ev) {	
			sendRequest("cPodcastList", el.getElement("#prevAjaxLink").href);
			var e = new Event(ev);
			e.stop( );
		});
	}

	var nextLink = el.getElement("#nextPageLink");
	if(nextLink) {
		nextLink.removeEvents("click");
		nextLink.addEvent("click", function(ev) {
			sendRequest("cPodcastList", el.getElement("#nextAjaxLink").href);
			var e = new Event(ev);
			e.stop( );
		});
	}
}

var currId = null;
var defaultTypes = {
    'stitle': '/dir=descending',
    'spublished': '/dir=ascending',
    'srating': '/dir=ascending',    
    'sdownloads': '/dir=ascending'
};

function prepSortLinks(el) {
	el.getElements('.sortLink').each(function(el) {
		var id = el.id.substring(1);

		el.removeEvent("click");
		el.addEvent("click", function(ev) {
			var url;
			var parts = this.href.split("/");

			if(parts[3]!="school") url = podcastAjaxUrl+"/channel="+parts[3]+
				"/sort="+id+typeExts[id];
				else  url = podcastAjaxUrl+"/sort="+id+typeExts[id];

            if(el.id != currId) {
                typeExts[el.id] = defaultTypes[el.id];
                console.log(typeExts[el.id]);
            }

            if(!currSortUrl.match(typeExts[el.id])) {
                if(el.id == 'stitle') {
                    currId = 'stitle';
				    typeExts[el.id] = "/dir=ascending";
    				url = url.replace("descending", "ascending");
                } else {
                    currId = el.id;
				    typeExts[el.id] = "/dir=descending";
    				url = url.replace("ascending", "descending");                
                }
            } else if(currSortUrl.match(typeExts[el.id]) && currSortUrl.match(/ascending/)) {
				typeExts[el.id] = "/dir=descending";
				url = url.replace("ascending", "descending");
			} else {
				typeExts[el.id] = "/dir=ascending";
				url = url.replace("descending", "ascending");
			}

            console.log(url);
			currSortUrl = url;
			sendRequest(
				"cPodcastList", url
			);
			new Event(ev).stop( );
		});
		/*new Ajax(url, {
			method: 'get',
			onComplete: function(text) { updateContent(id, text); },
			onFailure: function(request) { rollback(request); }
		}).request();*/
	}.bind(el));	
}


function rollback(request) {
	for(id in content) {
		var obj = $(id);
		if(obj) obj.innerHTML = content.id;
	}

	reset( );
	alert(	"Sorry, we could not load the page correctly.\nPlease try again, and if the problem "+
		"persists,\ncontact a system administrator.");
}

function reset( ) {
	for(id in requests) {
		if(requests.id) requests.id.cancel( );
	}

	//content={ };
	requests=[ ];
	loading = false;
	reqLoads = 0;


}

function sendRequest(id, url, def) {
	if(url) lastUrls[id] = url;
	else {
		if(lastUrls[id]) url = lastUrls[id];
		else if(def) url = def;
		else return false;
	}

	requests[requests.length-1] = 
		new Request({
            url: url,
			onComplete: function(text) { updateContent(id, text); },
			onFailure: function(request) { rollback(request); }
		}).get();
}

function prepare(href) {
	href = href.trim("/");
	var parts = href.split("/");
	content.channel = parts[parts.length-1];

	loading = true;
	
	var id = "loadPanel";

	if($(id)) {
		$(id).setStyle("width", window.getWidth( ));
		$(id).setStyle("height", window.getHeight( ));
		$(id).setStyle("left", window.getScrollLeft( ));
		$(id).setStyle("top", 0);
        $(id).setOpacity(0);

		$('loadPanel').tween("top", window.getHeight( ), window.getScrollTop( ));
		(function( ) {$('loadPanel').setOpacity(0.8);}).delay(100);
		$('loadPanel').setStyle("display", "block");
	}
	content.href = href;
	
	var cd = $('channelDetails');
	if(cd) {
		$('channelDetails').dispose( );
	}//content.channelDetails = cd.innerHTML;
	var cd = $('cPodcastLink');
	if(cd) content.cPodcastList = cd.innerHTML;
	var cd = $('top-podcasts');
	if(cd) content.toppodcastpanel = cd.innerHTML;
	var cd = $('feedLink');
	if(cd) content.feedLink = cd.innerHTML;
}

