var __cp = Array();
CoverPlayer = function (params){
	
	this.debug = false;
	
	this.dimensions = params.dimensions;
	this.list = params.list;
	this.title = params.title;
	this.elementID = params.element;
	this.element = params.element?$(params.element):$(document.body);
	
	if(params.cdn && params.cdn.length>0){
		this.CDN = params.cdn.replace(/\/+$/,"") + "/";
	}else{
		this.CDN = "";
	}
	
	this.preloadImage = params.preloadImage?params.preloadImage:"";
	
	this.thumbsNumVisible = params.list;
	this.thumbBorder = 1;
	this.defaultDirection = typeof(params.direction)!="undefined" && params.direction.match(/^left$/i) ? "left" : "right";
	
	this.speed = typeof(params.speed)!="undefined" ? params.speed : 2000;
	this.timeout = params.timeout>0 ? params.timeout*1000 : 5000;
	
	this.showControls = typeof(params.control)!="undefined" && params.control?true:false;
	this.showThumbs = typeof(params.thumbs)!="undefined" && params.thumbs?true:false;
	this.position = Array();
	
	this.zIndex = parseInt(params.zIndex);
	
	this.tabs = Array();
	this.items = Array(Array());
	this.itemThumbs = Array(Array());
	this.targets = Array(Array());
	this.links = Array(Array());
	this.titles = Array(Array());
	this.titles_short = Array(Array());
	this.text = Array(Array());
}

CoverPlayer.prototype.addTab = function(name){
	this.tabs.push(name);
	var newindex = this.tabs.length-1;
	this.items[newindex] = Array();
	this.itemThumbs[newindex] = Array();
	this.text[newindex] = Array();
	this.links[newindex] = Array();
	this.titles[newindex] = Array();
	this.titles_short[newindex] = Array();
	this.position.push(0);
}

CoverPlayer.prototype.add = function(params,src,blurb,link,tab){
	if(this.tabs.length>0){
		tabIndex = this.tabs.length-1;
	}else{
		this.addTab("_default");
		tabIndex = 0;
	}
	
	if(typeof(params.tab)!="undefined"){
		for(var i=0; i<this.tabs.length; i++){
			if(this.tabs[i]==params.tab){
				tabIndex = i;
				break;
			}
		}
	}
	
	params.blurb = params.blurb?params.blurb:"";
	params.target = (params.target && params.link)?params.target:"_self";
	params.link = params.link?params.link:"javascript:void(0)";
	params.images.small = params.images.small.length>0?params.images.small:params.images.large;
	params.box_title = params.box_title?params.box_title:"";
	
	this.items[tabIndex].push(params.images.large);
	this.itemThumbs[tabIndex].push(params.images.small);
	this.titles[tabIndex].push(params.title);
	this.titles_short[tabIndex].push(params.box_title);
	this.text[tabIndex].push(params.blurb);
	this.links[tabIndex].push(params.link);
	this.targets[tabIndex].push(params.target);
}

CoverPlayer.prototype.make = function(){
	__cp.push(this);
	this.__cpIndex = __cp.length-1;
	
	// without tabs
	if(this.tabs.length==1 && this.tabs[0]=="_default"){
		this.makeTab(0);

	// with tabs
	}else{
		
		// tab navigation
		this.element.append($('<ul class="tab-navigation"></ul>'));
		for(var i=0; i<this.tabs.length; i++){
			this.makeTab(i,true);
		}
	}
	
	this.element.css("width",this.dimensions.large.w+"px");
	this.element.css("height",this.dimensions.large.h+"px");
	this.element.css("background","#000 url('" + this.preloadImage + "') no-repeat center center");


	// TODO: Modify isEmpty to support multiple tabs
	images2load = Array();
	var empty = true;
	for(tabindex in this.items){
		if(this.items[tabindex].length>0){
			empty = false;
		}
		for(imgindex in this.items[tabindex]){
			img = new Image();
			img.src = this.items[tabindex][imgindex];
			images2load.push(img)
		}
	}
	if(empty){
		this.element.css("background","#000");
		this.element.html("No Covers.");
	}else{
		preloadImages(this.__cpIndex,images2load);
	}
}

function preloadImages(cpindex, images2load){
	var loaded = true;
	for(var i=0; i<images2load.length; i++){
		if($.browser.msie){
			if(typeof(images2load[i].naturalWidth)!="undefined" && images2load[i].naturalWidth==0){
				loaded = false;
				break;
			}
		}else{
			if(!images2load[i].complete){
				loaded = false;
				break;
			}
		}
	}
	if(loaded){
		_showTab(cpindex,0);
	}else{
		setTimeout(function(){preloadImages(cpindex,images2load)},1000);
	}
}

CoverPlayer.prototype.makeTab = function(tabindex,showtab){
	var tmp;
	var rnd = Math.round(Math.random()*1000000);
	
	/*************************
	 * tab navigation item
	 *************************/
	if(showtab && this.tabs[tabindex]!="_default"){
		var _tabnav = $('<li><a href="javascript:void(0)" onclick="_showTab('+this.__cpIndex+','+tabindex+');">'+this.tabs[tabindex]+'</a></li>');
		this.element.find("ul.tab-navigation").eq(0).append(_tabnav);
	}

	/*************************
	 * tab content item
	 *************************/
	var IEclassName = "";
	if($.browser.msie){
		IEclassName = "ie ie"+parseInt($.browser.version);
	}
	var NoThumbClass = this.showThumbs?"":" noThumbs";
	
	var step = this.defaultDirection=="right"?-1:1;
	
	var controlItemWidth = 39;
	var controlHeight = 90;
	var paddingTop = 86;
	var controlTop = (this.dimensions.large.h-controlHeight-paddingTop);
	var blurbTop = controlTop+30; blurbTop = this.showThumbs?blurbTop:blurbTop+controlHeight;
	
	var _tabcontent = $('<div style="width:'+this.dimensions.large.w+'px; height:'+this.dimensions.large.h+'px;" id="tab-content-'+this.tabs[tabindex]+'" class="cover-tab-content ' + IEclassName + NoThumbClass + '"></div>');
	this.element.append(_tabcontent);
	_tabcontent.hover(
			function(){
				var isover = parseInt($(this).attr("over"))>0?true:false;
				if($(this).attr("to")){
					clearTimeout($(this).attr("to"));
				}
				
				if(!isover){
					$(this).find(".cover-play-control").eq(0).fadeIn(500);
					$(this).attr("over",1);
				}
			},
			function(){
				var O = $(this)
				$(this).attr("to",setTimeout(function(){
					O.find(".cover-play-control").eq(0).fadeOut(500);
					O.attr("over",0);
				},1000));
			}
	);

	// controls
	if(this.showControls){
		tmp = '<div class="cover-play-control" style="z-index: '+(this.zIndex+5)+'">';
		tmp += '<span class="start"></span>';
		tmp += '<a href="javascript:void(0)" onclick="CoverPlayer_Go2Position(-1,'+this.__cpIndex+','+tabindex+'); CoverPlayer_ControlSetPlayStop($(this).parent(),\'play\');" class="previous"></a>';
		tmp += '<a href="javascript:void(0)" onclick="CoverPlayer_TogglePlay('+this.__cpIndex+','+tabindex+'); CoverPlayer_ControlSetPlayStop($(this).parent());" class="stop"></a>';
		tmp += '<a href="javascript:void(0)" onclick="CoverPlayer_Go2Position(1,'+this.__cpIndex+','+tabindex+'); CoverPlayer_ControlSetPlayStop($(this).parent(),\'play\');" class="next"></a>';
		tmp += '<span class="end"></span>';
		tmp += '</div>';
		var _controls = $(tmp);
		_tabcontent.append(_controls);
	}
	
	
	// screen
	var href="javascript:void(0)", cursor="default", target="_self";
	if(this.links[tabindex][0].length){
		href = this.links[tabindex][0];
		cursor = "pointer";
		target = this.targets[tabindex][0];
	}
	tmp = '<div class="cover-screen" style="width:'+this.dimensions.large.w+'px; height:'+this.dimensions.large.h+'px; z-index: '+(this.zIndex+1)+'">';
	tmp += '<a href="'+href+'" target="'+target+'" style="cursor:'+cursor+'; height: '+Math.round(this.dimensions.large.h/2)+'px;">';
	tmp += '<img src="' + this.CDN + this.items[tabindex][this.position[tabindex]] + '" alt="" width="'+this.dimensions.large.w+'" height="'+this.dimensions.large.h+'" border="0" />';
	tmp += '</a>';
	tmp += '</div>';
	var _screen = $(tmp);
	_tabcontent.append(_screen);
	
	// screen blurb
	tmp = '<div class="cover-blurb" style="top:'+blurbTop+'px; z-index: '+(this.zIndex+3)+'">';
	tmp += '<h1 class="title">'+this.titles[tabindex][this.position[tabindex]]+'</h1>';
	tmp += '<p class="blurb">'+this.text[tabindex][this.position[tabindex]]+'</p>';
	tmp += '</div>';
	var _screen_blurb = $(tmp);
	_tabcontent.append(_screen_blurb);
	
	/*********************************
	*		THUMBNAILS
	**********************************/
	
	// controls
	var _thumbcontrols = $('<div class="cover-controls" style="width:'+this.dimensions.large.w+'px; height:'+controlHeight+'px; top:'+controlTop+'px; z-index: '+(this.zIndex+2)+'"></div>');
	_tabcontent.append(_thumbcontrols);
	
	if(this.showThumbs){
		// thumb pointer
		tmp = '<div class="cover-thumb-pointer" style="top:'+(controlTop+paddingTop-12)+'px; z-index: '+(this.zIndex+4)+'">';
		tmp += '<div class="arrow"></div>';
		tmp += '<div class="border"><div class="border-inner"></div></div>';
		tmp += '</div>';
		_thumbpointer = $(tmp);
		_thumbpointer.click(function(){
			_GoLink($(this).attr("href"),$(this).attr("target"));
		});
		_tabcontent.append(_thumbpointer);
		
		// thumb control left
		var _thumbcontrolleft = $('<div class="control go-left"><a href="javascript:void(0);" onclick="CoverPlayer_Go2Position(-1,'+this.__cpIndex+','+tabindex+'); CoverPlayer_ControlSetPlayStop($(\'.cover-play-control\'),\'play\');">&#9668;</a></div>');
		_thumbcontrols.append(_thumbcontrolleft);
		
		// thumb control right
		var _thumbcontrolright = $('<div class="control go-right"><a href="javascript:void(0);" onclick="CoverPlayer_Go2Position(1,'+this.__cpIndex+','+tabindex+'); CoverPlayer_ControlSetPlayStop($(\'.cover-play-control\'),\'play\');">&#9658;</a></div>');
		_thumbcontrols.append(_thumbcontrolright);
		
		// thumb images
		var _thumbscreen = $('<div class="cover-thumb-screen" style="width:'+(this.dimensions.large.w-2*controlItemWidth)+'px;"></div>');
		_thumbcontrolleft.after(_thumbscreen);
		
		var _ul = $('<ul></ul>');
		var _li, l, target, cursor;
		var limit = this.itemThumbs[tabindex].length;
		limit = limit>this.thumbsNumVisible?this.thumbsNumVisible:limit;
		for(var i=0; i<limit; i++){
			l = this.links[tabindex][i];
			target = this.targets[tabindex][i];
			cursor = "pointer";
			if(!l.length || l.match(/^javascript:\s*void\(/)){
				l = "javascript:void(0);";
				target = "_self";
				cursor = "default";
			}
			tmp = '<li style="width:'+(this.dimensions.small.w+(2*this.thumbBorder))+'px;">';
			tmp += '<a href="' + l + '" target="' + target + '" style="cursor:'+cursor+'">';
			tmp += '<img width="' + this.dimensions.small.w + '" height="' + this.dimensions.small.h + '" src="' + this.CDN + this.itemThumbs[tabindex][i] + '" alt="" />';
			tmp += '</a>';
			tmp += '<br />'+this.titles_short[tabindex][i];
			tmp += '</li>';
			_li = $(tmp);
			_ul.append(_li);
		}
		_thumbscreen.append(_ul);
	}
	
	CoverPlayer_RepositionBlurb(this.__cpIndex, tabindex);
}


function _showTab(cpindex,tabindex){
	
	var C = __cp[cpindex];
	
	C.element.find(".tab-navigation li").removeClass("active");
	C.element.find(".tab-navigation li").eq(tabindex).addClass("active");
	
	C.element.find(".cover-tab-content").hide();
	C.element.find("#tab-content-"+C.tabs[tabindex]).show();
	
	var indx = C.__cpIndex;
	if(C.to){
		C._clearTimeout();
	}
	C._reset(cpindex);
	if(C.items[tabindex].length>1){
		C.to = setTimeout(function(){_go(indx,tabindex,C.defaultDirection)},C.timeout);
	}

}

CoverPlayer.prototype._clearTimeout = function(){
	if(this.to){
		clearTimeout(this.to);
		this.to = null;
	}
}

CoverPlayer.prototype._reset = function(cpindx){
	var second;
	for(var i=0; i<this.position.length; i++){
		this.position[i] = this.defaultDirection=="left"?1:(this.items[i].length-1);
		second = this.defaultDirection=="left"?1:(this.items[i].length-1);
		
		var currentLink = this.links[i][0]
		var currentTarget = this.targets[i][0];
		$(".cover-thumb-pointer").attr("href",currentLink);
		$(".cover-thumb-pointer").attr("target",currentTarget);
		
		$("#tab-content-"+this.tabs[i]+" .cover-screen a img").attr("src",this.CDN + this.items[i][0]);
		$("#tab-content-"+this.tabs[i]+" .cover-screen a").attr("href",this.links[i][0]);
		$("#tab-content-"+this.tabs[i]+" .cover-screen a").attr("target",this.targets[i][0]);
		if(this.links[i][0].match(/^javascript:\s*void\(/)){
			$("#tab-content-"+this.tabs[i]+" .cover-screen a").css("cursor","default");
		}else{
			$("#tab-content-"+this.tabs[i]+" .cover-screen a").css("cursor","pointer");
		}
		$("#tab-content-"+this.tabs[i]+" .cover-blurb .title").html(this.titles[i][0]);
		$("#tab-content-"+this.tabs[i]+" .cover-blurb .blurb").html(this.text[i][0]);
	}
}

_GoLink = function(href,target){
	var newwin = window.open(href,target);
	newwin.focus();
}

function _go(cpindex, tabindex, direction, donotforward){
	var C = __cp[cpindex], tmp;
	donotforward = donotforward?true:false;

	direction = direction=="right"?direction:C.defaultDirection;
	step = direction=="right"?-1:1;
	
	
	var scr = $("#tab-content-" + C.tabs[tabindex] + " .cover-screen").eq(0);
	var scrBlurb = $("#tab-content-" + C.tabs[tabindex] + " .cover-blurb").eq(0);
	var ul = $("#tab-content-" + C.tabs[tabindex] + " .cover-thumb-screen ul").eq(0);

	var position = C.position[tabindex];
	var newposition = position+step;
	
	var limit = (C.thumbsNumVisible>C.itemThumbs[tabindex].length)?C.itemThumbs[tabindex].length:C.thumbsNumVisible;
	
	if(newposition >= C.itemThumbs[tabindex].length){
		newposition = 0;
	}else if(newposition < 0){
		newposition = C.itemThumbs[tabindex].length-1;
	}
	
	var lastposition;
	
	if(step > 0){
		lastposition = position+limit-1;
	}else{
		lastposition = position;
	}
	
	if(lastposition >= C.itemThumbs[tabindex].length){
		lastposition -= C.itemThumbs[tabindex].length
	}else if(lastposition < 0){
		lastposition = C.itemThumbs[tabindex].length-1;
	}

	var LastLink = C.links[tabindex][lastposition];
	var LastTarget = LastLink.match(/^javascript:\s*void\(/)?"_self":C.targets[tabindex][lastposition];
	var LastCursor = LastLink.match(/^javascript:\s*void\(/)?"default":"pointer";
	var LastSRC = C.CDN + C.itemThumbs[tabindex][lastposition]
	var LastText = C.titles_short[tabindex][lastposition];
		
	tmp = '<li style="width:'+(C.dimensions.small.w + (2*C.thumbBorder))+'px;">';
	tmp += '<a href="' + LastLink + '" target="' + LastTarget + '" style="cursor: '+LastCursor+'">';
	tmp += '<img src="' + LastSRC + '" width="' + C.dimensions.small.w + '" height="' + C.dimensions.small.h + '" alt="" />';
	tmp += '</a>';
	tmp += '<br />'+LastText;
	tmp += '</li>';
	var LastLI = $(tmp);
	
	// calculate thumb-li margin-left
	var ThumbLI_marginLeft = parseInt(ul.find("li").eq(0).css("margin-right"));
	
	var animateto;
	if(direction=="left"){
		ul.append(LastLI);
		animateto = Math.round(-1*(C.dimensions.small.w+ThumbLI_marginLeft+(2*C.thumbBorder)));
	}else{
		ul.css("margin-left",(-1*(C.dimensions.small.w+ThumbLI_marginLeft+(2*C.thumbBorder))) + "px")
		ul.prepend(LastLI);
		animateto = 0;
	}
	
	ul.animate(
		{marginLeft: animateto+"px"},
		{
			duration: Math.round(C.speed),
			queue:false, 
			easing:'easeOutQuart',
			complete: function(){
				if(direction=="left"){
					ul.find("li").eq(0).remove();
				}else{
					var lis = ul.find("li");
					lis.eq(lis.length-1).remove();
				}
				
				var nextpos = C.position[tabindex];
				
				// set scroller ul position
				ul.css("margin-left","0");
				
				// show next large image
					// image
					scr.find("img").eq(0).attr("src",C.CDN + C.items[tabindex][nextpos]);
					// link
					tmp = scr.find("a").eq(0);
					tmp.attr("href",C.links[tabindex][nextpos]);
					tmp.attr("target",C.targets[tabindex][nextpos]);
					// title
					scrBlurb.find("h1.title").eq(0).html(C.titles[tabindex][nextpos]);
					// blurb
					scrBlurb.find("p.blurb").eq(0).html(C.text[tabindex][nextpos]);
					
				// reposition new blurb
				CoverPlayer_RepositionBlurb(cpindex, tabindex);
				
				scr.attr("moving",0);
				
				// calculate nextpos
				var newpos = C.position[tabindex];
				if(direction=="left"){
					newpos += 1;
					newpos  = newpos >= C.itemThumbs[tabindex].length?0:newpos;
				}else{
					newpos -= 1;
					newpos  = newpos >= 0 ? newpos : C.itemThumbs[tabindex].length-1;
				}
				
				var currentLink = $(".cover-screen a").eq(0).attr("href");
				var currentTarget = $(".cover-screen a").eq(0).attr("target");
				
				$(".cover-thumb-pointer").attr("href",currentLink);
				$(".cover-thumb-pointer").attr("target",currentTarget);
				if(!currentLink.match(/^javascript:\s*void\(/)){
					$(".cover-thumb-pointer").css("cursor","pointer");
				}else{
					$(".cover-thumb-pointer").css("cursor","default");
				}
				
				C.position[tabindex] = newpos;
				
				if(C.to){
					C._clearTimeout();
				}
				if(!donotforward){
					C.to = setTimeout("_go("+cpindex+","+tabindex+",'"+direction+"',"+donotforward+")",C.timeout);
				}
			}
		}
	);

	scr.attr("moving",1);
}

function CoverPlayer_Go2Position(step,cpindex,tabindex){
	var C = __cp[cpindex];
	var scr = $("#tab-content-" + C.tabs[tabindex] + " .cover-screen").eq(0);
	var moving = parseInt(scr.attr("moving")); moving = moving>0?true:false;
	var direction = step>0?"left":"right";
	var tmp;
	
	if(!moving){
		C._clearTimeout();
		var limit = (C.thumbsNumVisible>C.items[tabindex].length)?C.items[tabindex].length:C.thumbsNumVisible;
		var dirchange = C.defaultDirection==direction?false:true;
		var newpos = C.position[tabindex];
		if(dirchange){
			newpos += 2*step;
			if(newpos >= C.items[tabindex].length){
				newpos -= C.items[tabindex].length
			}else if(newpos < 0){
				newpos += C.items[tabindex].length
			}
		}
		
		C.defaultDirection = direction;
		C.position[tabindex] = newpos;

		_go(cpindex, tabindex, direction, 1);
	}
}

function CoverPlayer_RepositionBlurb(cpindex, tabindex, again){
	var C = __cp[cpindex];
	var thumbsHeight = 107;
	
	again = parseInt(again)>0?parseInt(again):0;
	
	if(C){
		var scrBlurb = $("#tab-content-" + C.tabs[tabindex] + " .cover-blurb").eq(0);
		var coverControl = $("#tab-content-" + C.tabs[tabindex] + " .cover-controls").eq(0);
		
		var blurbHeight = scrBlurb.height();
		var blurbPosition = [parseInt(scrBlurb.css("left")),parseInt(scrBlurb.css("top"))];
		
		var maxTop = C.dimensions.large.h - thumbsHeight;
		if(!blurbHeight){
			var html = '<div class="cover-blurb" style="display:none; width: '+C.dimensions.large.w+'px" id="tempBlurbHeight">'+scrBlurb.html()+'</div>';
			var div = $(html);
			$(document.body).append(div);
			blurbHeight = div.height();
		}
		$("#tempBlurbHeight").remove();
		var setTop = maxTop - blurbHeight;
		scrBlurb.css("top",setTop+"px");
	}
}

function CoverPlayer_TogglePlay(cpindex,tabindex){
	var C = __cp[cpindex];
	if(C.to){
		C._clearTimeout();
	}else{
		_go(cpindex,tabindex);
	}
}
function CoverPlayer_ControlSetPlayStop(control,className){
	var obj = control.find("a").eq(1);
	if(typeof(className)=="undefined"){
		if(obj.hasClass('stop')){
			obj.attr('class','play');
		}else{
			obj.attr('class','stop');
		}
	}else{
		obj.attr('class',className);
	}
}