/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.08.19 +r2
 */
/* Drag */
dragging = false;
(function($){
	var timeOutDrag = null;
	$.fn.jqDrag=function(h) {
		return i(this,h,'d');
	};
	$.jqDnR={dnr:{},e:0,
		drag:function(v) {
			dragging = true;
			var container = E.parent().parent();
			if (container.hasClass("horizontal") || container.hasClass("vertical")) {
				if (container.hasClass("horizontal")) { // Horizontal
					var posX = Math.min(Math.max(M.X+v.pageX-M.pX,0),E.parent().width()-E.width());
					E.css({left:posX});
					marginContent = (((container.find(".ctn-scrollingcontent").width() - container.find(".ctn-scrollingcontentcontainer").width())*(100*posX) / (E.parent().width() - E.width()))/100)*(-1);
					container.find(".ctn-scrollingcontent").css("margin-left",marginContent+"px");
				} else { // Vertical
					var posY = Math.min(Math.max(M.Y+v.pageY-M.pY,0),E.parent().height()-E.height());
					E.css({top:posY});
					marginContent = (((container.find(".ctn-scrollingcontent").height() - container.find(".ctn-scrollingcontentcontainer").height())*(100*posY) / (E.parent().height() - E.height()))/100)*(-1);
					E.html("&nbsp;");
					container.find(".ctn-scrollingcontent").css("margin-top",marginContent+"px");
				}
			} else if (E.hasClass("ctn-dragmodule")) {
				E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});
			}
			return false;
		},
		stop:function(v) {
			E.css('opacity',M.o);
			if (E.hasClass("ctn-dragmodule")) {
				elementOver("over",".ctn-boxmodule",0);
				bindUnbindBoxmodule(0);
				/* Change position */
				E.css({position:'static',left:0,top:0});
				E.removeClass("active");
				obj = testPositinModuleDrag(E,v.pageX,v.pageY);
				if (obj) {
					if (!($(obj).prev().get(0)==E.get(0) || $(obj).next().get(0)==E.get(0))) {
						objBoxmodule = E.next();
						$(obj).after(E);
						E.after(objBoxmodule);
					}
				}
				/* // Change position */
			}
			$().unbind('mousemove',J.drag).unbind('mouseup',J.stop);
			$("iframe").css("visibility","visible");
			setTimeout("dragging = false",200);
		}
	};
	var J=$.jqDnR,M=J.dnr,E=J.e,i=function(e,h,k) {
		return e.each(function() {
			h=(h)?$(h,e):e;
			h.bind('mousedown',{e:e,k:k},function(v) {
				var d=v.data,p={};
				E=d.e;			
				// attempt utilization of dimensions plugin to fix IE issues
				if (E.css('position') != 'relative') {
					try{
						E.css("position","relative");
					}catch(e){
					}
				}
				if (E.hasClass("ctn-dragmodule")) {
					$("iframe").css("visibility","hidden");
					bindUnbindBoxmodule(1);
					E.css({left:0,top:0});
					E.parent().parent().find(".ctn-dragmodule").css("z-index",2);
					E.css("z-index",3);
					E.addClass("active");
				}
				M={X:p.left||f('left')||0,Y:p.top||f('top')||0,W:f('width')||E[0].scrollWidth||0,H:f('height')||E[0].scrollHeight||0,pX:v.pageX,pY:v.pageY,k:d.k,o:E.css('opacity')};
				//E.css({opacity:0.8});
				$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
				return false;
			});
		});
	},
	f=function(k) {
		return parseInt(E.css(k))||false;
	};
	testPositinModuleDrag=function(E,posX,posY) {
		returnValue = false;
		$(".ctn-boxmodule").each(function() {
			var leftMin = $(this).offset().left;
			var leftMax = leftMin + $(this).width();
			var topMin = $(this).offset().top;
			var topMax = topMin + $(this).height() + 200;
			if ((posX >= leftMin && posX <= leftMax) && (posY >= topMin && posY <= topMax)) {
				returnValue = this;
			}
		});
		return returnValue;
	}

	// Bind Unbind Module Over
	/*
	PAREMETERS
	- action (unbind = 0 / bind = 1)
	*/
	function bindUnbindBoxmodule(action) {
		if (action == 1) { // bind
			$(".ctn-boxmodule").hover(
				function() {
					elementOver("over",this,1);
				},
				function() {
					elementOver("over",this,0);
				}
			);
		} else { // unbind
			$(".ctn-boxmodule").unbind();
		}
	}
})(jQuery);
/* // Drag */

/* Scrolling */
	// Init scrolling
function initScrolling(obj) {
	if ($(obj).find(".ctn-scrolling").size() > 0) {
		$(obj).find(".ctn-scrolling .ctn-scrollbar").click(function(e) {
			scrollClick(this,e);
		});
		$(obj).find(".ctn-scrolling .ctn-bar").each(function(){$(this).jqDrag()});
		
		$(obj).find(".ctn-scrolling .ctn-scrollbar").show();
		$(obj).find(".ctn-scrolling .ctn-scrollingcontentcontainer").removeClass("ctn-alternate");
		
		/* Adjust width */
		$(obj).find(".ctn-photosgallery .ctn-scrollingcontent").each(function(i) {
			var w = $(this).find("li").size()*115;
			
			$(this).width(w);
			if (w < parseInt($(this).parent().css("width").replace("px",""))) {
				$(this).parent().parent().find(".ctn-scrollbar").hide();
			}
		});
		
		$(obj).find(".ctn-scrollingcontentcontainer").each(function(i) {
			if ($(this).parents(".ctn-scrolling:first").hasClass("vertical")) {
				E = $(this);
				$(document).ready(function() {
					if (E.height() > E.find(".ctn-scrollingcontent").height()) {
						E.parents(".ctn-scrolling").find(".ctn-scrollbar").hide();
						E.parents(".ctn-scrolling").find(".ctn-scrollingcontentcontainer").css("width","100%");
						E.parents(".ctn-scrolling").find(".ctn-scrollingcontentcontainer").css("margin","0");
					}
				});
			}
		});
	}
}

	// Click scrollbar position
function scrollClick(obj,e) {
	if (!dragging) {
		var objBar = $(obj).find(".ctn-bar");
		if ($(obj).parent().hasClass("horizontal")) { // Horizontal
			var posX = Math.min(Math.max(e.pageX - $(obj).parent().offset().left - objBar.width()/2,0),$(obj).width()-objBar.width());
			objBar.animate({left:posX+"px"},{ duration: 200, queue: false });
			var marginContent = ((($(obj).parent().find(".ctn-scrollingcontent").width() - $(obj).parent().find(".ctn-scrollingcontentcontainer").width())*(posX * 100 / ($(obj).width() - objBar.width())))/100)*(-1);
			$(obj).parent().find(".ctn-scrollingcontent").animate({marginLeft:marginContent+"px"},{ duration: 200, queue: false });
		} else { // Vertical
			var posY = Math.min(Math.max(e.pageY - $(obj).parent().offset().top - objBar.height()/2,0),$(obj).height()-objBar.height());
			objBar.animate({top:posY+"px"},{ duration: 200, queue: false });
			var marginContent = ((($(obj).parent().find(".ctn-scrollingcontent").height() - $(obj).parent().find(".ctn-scrollingcontentcontainer").height())*(posY * 100 / ($(obj).height() - objBar.height())))/100)*(-1);
			$(obj).parent().find(".ctn-scrollingcontent").animate({marginTop:marginContent+"px"},{ duration: 200, queue: false });
		}
	}
}

	// Move scrollbar position
	/*
	PARAMETERS
	- obj (Object Scrolling)
	- position (Margin)
	*/
function scrollMoveContentPosition(obj,position) {
	if ($(obj).hasClass("horizontal")) { // Horizontal
		var objScrollbar = $(obj).find(".ctn-scrollbar");
		var marginContent = Math.min(Math.max(position,$(obj).find(".ctn-scrollingcontentcontainer").width()-$(obj).find(".ctn-scrollingcontent").width()),0);
		$(obj).find(".ctn-scrollingcontent").animate({marginLeft:marginContent+"px"},{ duration: 200, queue: false });
		var percent = marginContent*100/($(obj).find(".ctn-scrollingcontentcontainer").width() - $(obj).find(".ctn-scrollingcontent").width());
		var posBar = ((objScrollbar.width()-objScrollbar.find(".ctn-bar").width())*percent)/100;
		objScrollbar.find(".ctn-bar").animate({left:posBar+"px"},{ duration: 200, queue: false });
	} else { // Vertical
		var objScrollbar = $(obj).find(".ctn-scrollbar");
		var marginContent = Math.min(Math.max(position,$(obj).find(".ctn-scrollingcontentcontainer").height()-$(obj).find(".ctn-scrollingcontent").height()),0);
		$(obj).find(".ctn-scrollingcontent").animate({marginTop:marginContent+"px"},{ duration: 200, queue: false });
		var percent = marginContent*100/($(obj).find(".ctn-scrollingcontentcontainer").height() - $(obj).find(".ctn-scrollingcontent").height());
		var posBar = ((objScrollbar.height()-objScrollbar.find(".ctn-bar").height())*percent)/100;
		objScrollbar.find(".ctn-bar").animate({top:posBar+"px"},{ duration: 200, queue: false });
	}
}


	/* Wheel */
function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta) {
		var obj = event.currentTarget || event.srcElement;
		obj = $(obj);
		if (obj.parents(".ctn-scrollingphoto").size() > 0 || obj.hasClass("ctn-scrollingphoto")) { // Scrolling photo
			if (!obj.hasClass("ctn-scrollingphoto"))
				obj = obj.parents(".ctn-scrollingphoto");
			if (delta < 0) {
				obj.find(".lnk-next:first").click();
			} else {
				obj.find(".lnk-back:first").click();
			}
		} else { // Scrolling content
			if (!obj.hasClass("ctn-scrolling"))
				obj = obj.parents(".ctn-scrolling");
			if (obj.hasClass("horizontal")) { // Horizontal
				if (delta < 0)
					scrollMoveContentPosition(obj,parseInt(obj.find(".ctn-scrollingcontent").css("margin-left").replace("px",""))-200);
				else
					scrollMoveContentPosition(obj,parseInt(obj.find(".ctn-scrollingcontent").css("margin-left").replace("px",""))+200);
			} else { // Vertical
				if (delta < 0)
					scrollMoveContentPosition(obj,parseInt(obj.find(".ctn-scrollingcontent").css("margin-top").replace("px",""))-200);
				else
					scrollMoveContentPosition(obj,parseInt(obj.find(".ctn-scrollingcontent").css("margin-top").replace("px",""))+200);
			}
		}
	}
	if (event.preventDefault)
		event.preventDefault();
	
	event.returnValue = false;
}


	// Initialization code
	function initWheel(obj) {
		if (window.addEventListener) {
			$(obj).find(".ctn-scrolling:not(.noscrolling)").each(function(i) {
				$(this).get(0).addEventListener('DOMMouseScroll', wheel, false);
			});
			$(obj).find(".ctn-scrollingphoto").each(function(i) {
				if ($(this).find(".lnk-next").size() > 0 || $(this).find(".lnk-back").size() > 0) {
					$(this).get(0).addEventListener('DOMMouseScroll', wheel, false);
				}
			});
		}
		$(obj).find(".ctn-scrolling:not(.noscrolling)").each(function(i) {
			$(this).get(0).onmousewheel = $(this).get(0).onmousewheel = wheel;
		});
		$(obj).find(".ctn-scrollingphoto").each(function(i) {
			if ($(this).find(".lnk-next").size() > 0 || $(this).find(".lnk-back").size() > 0) {
				$(this).get(0).onmousewheel = $(this).get(0).onmousewheel = wheel;
			}
		});
	}
	/* // Wheel */
/* // Scrolling */



/* Live */
arrModules = new Array();
arrModules[0] = new Array("#futebol .status", "livemodules/placar-futebol.htm",500000);
arrModules[1] = new Array("#basquete .status", "livemodules/placar-basquete.htm",500000);
arrModules[2] = new Array("#handebol .status", "livemodules/placar-handebol.htm",500000);
arrModules[3] = new Array("#hoquei .status", "livemodules/placar-hoquei.htm",500000);
arrModules[4] = new Array("#tenis .status", "livemodules/placar-tenis.htm",500000);
arrModules[5] = new Array("#volei .status", "livemodules/placar-volei.htm",500000);
arrModules[6] = new Array("#voleidepraia .status", "livemodules/placar-voleidepraia.htm",500000);
arrModules[7] = new Array(".minmin.game", "livemodules/narracao.htm",50000);
arrModules[8] = new Array(".minmin.no-game", "livemodules/narracao-evento-nao-esportivo.htm",500000);
arrModules[9] = new Array(".gameinfo .scoring-soccer-hockey", "livemodules/_aovivo-estatisticas-scoring_futebol_hoquei-spa.html",50000);
arrModules[10] = new Array(".gameinfo .roster-basketball", "livemodules/_aovivo-estatisticas-cambios_futebol-spa.html",50000);
arrModules[11] = new Array(".gameinfo .roster-soccer", "livemodules/_aovivo-estatisticas-roster_futebol-spa.html",500000);
arrModules[12] = new Array(".gameinfo .roster-handball-hockey", "livemodules/_aovivo-estatisticas-roster_handball_hoquei-spa.html",500000);
arrModules[13] = new Array(".gameinfo .roster-tennis", "livemodules/_aovivo-estatisticas-roster_tenis-spa.html",500000);
arrModules[14] = new Array(".gameinfo .roster-volleyball", "livemodules/_aovivo-estatisticas-roster_volei-spa.html",500000);
arrModules[15] = new Array(".gameinfo .cambios-soccer", "livemodules/_aovivo-estatisticas-cambios_futebol-spa.html",500000);
arrModules[16] = new Array(".gameinfo .matchinformation", "livemodules/_aovivo-estatisticas-matchinformation-spa.html",500000);
arrModules[17] = new Array(".gameinfo .matchstats-basketball", "livemodules/_aovivo-estatisticas-roster_basquete-spa.html",500000);
arrModules[18] = new Array(".gameinfo .matchstats-soccer", "livemodules/_aovivo-estatisticas-matchstats_futebol-spa.html",500000);
arrModules[19] = new Array(".gameinfo .matchstats-handball", "livemodules/_aovivo-estatisticas-matchstats_handball-spa.html",500000);
arrModules[20] = new Array(".gameinfo .matchstats-hockey", "livemodules/_aovivo-estatisticas-matchstats_hoquei-spa.html",500000);
arrModules[21] = new Array(".gameinfo .matchstats-tennis", "livemodules/_aovivo-estatisticas-matchstats_tenis_tenisduplas-spa.html",500000);
arrModules[22] = new Array(".gameinfo .matchstats-volleyball", "livemodules/_aovivo-estatisticas-matchstats_volei-spa.html",500000);

// Update modules
function updateModule(obj, URL) {
	if (!dragging) {
		objAux = obj;
		if ($(obj).parents(".ctn-dragmodule").size() > 0) {
			obj = $(obj).parents(".ctn-dragmodule");
		}
		if ($(obj).is(":visible")) {
			if ($(obj).find(".ctn-modulecontent").size() > 0) {
				obj = $(obj).find(".ctn-modulecontent");
				if (obj.find(objAux.substring(objAux.lastIndexOf("."))).size() > 0) {
					obj = objAux;
				}
			}
			
			$(obj).prepend("<div class='ctn-loading'>loading...</div>");
			$.ajax({
				url: URL,
				cache: false,
				async: false,
				success: function(html){
					$(obj).html(html);
					initScrolling(obj);
					initWheel(obj);
				}
			});
		}
	}
}

for (index = 0; index < arrModules.length; index++) {
	updateModule(arrModules[index][0], arrModules[index][1]);
	setInterval("updateModule('"+arrModules[index][0]+"', '"+arrModules[index][1]+"')", arrModules[index][2]);
}

/* Drag modules */
// Toggle module
/*
PARAMETERS
- obj (Object)
- action (hide = 0 / collapse = 1 / expand = 2)
*/
function toggleModule(obj,action) {
	if (action == 0) { // Hide
		$(obj).fadeOut(200,function() {
			// Move to main
			objAux = $(obj).next();
			$(".ctn-module").append($(obj));
			$(".ctn-module").append(objAux);
			$(obj).each(function() {
				value = $(this).attr("class").substr($(this).attr("class").lastIndexOf(" ")+1);
				$("input:checkbox[value='"+value+"']").removeAttr("checked");
				updateCheck(value);
			});
		});
	} else if (action == 1) { // Show
		// Expand
		if (!$(obj).find(".ctn-modulecontent").is(":visible")) {
			$(obj).find(".lnk-expandmodule").hide();
			$(obj).find(".lnk-collapsemodule").show();
			$(obj).find(".ctn-modulecontent").show();
		}
		if ($(obj).hasClass("gameinfo")) { // Game info
			objAux = $(obj).next();
			$(".ctn-dragmodules .col-left").prepend($(obj));
			$(".ctn-dragmodules .col-left").prepend(objAux);
			$(".gameinfo").css("opacity",0);
			$(".gameinfo").show();
			$(".gameinfo").animate({opacity:1},400);
			setTimeout("window.scrollTo(0,$('.ctn-dragmodules .col-left').offset().top)",1000);
		} else {
			actualModule = $(".ctn-module .ctn-dragmodule:visible[class!='"+$(obj).attr("class")+"']");
			
			if (actualModule.size() > 0) {
				if (actualModule.queue("fx").length == 0) { // Not animating
					actualModule.fadeOut(200,function() {
						value = $(this).attr("class").substr($(this).attr("class").lastIndexOf(" ")+1);
						$("input:checkbox[value='"+value+"']").removeAttr("checked");
						updateCheck(value);
						$(obj).fadeIn(200);
					});
				} else {
					value = $(obj).attr("class").substr($(obj).attr("class").lastIndexOf(" ")+1);
					$("input:checkbox[value='"+value+"']").removeAttr("checked");
					updateCheck(value);
				}
			} else {
				$(obj).fadeIn(200);
			}
		}
		for (index = 0; index < arrModules.length; index++) {
			className = arrModules[index][0].substring(arrModules[index][0].lastIndexOf(".")+1);
			if ($(obj).hasClass(className)) {
				updateModule(arrModules[index][0], arrModules[index][1]);
			}
			if ($(obj).find("."+className).size() > 0) {
				updateModule(arrModules[index][0], arrModules[index][1]);
			}
		}
	} else if (action == 2) { // Collapse
		$(obj).find(".lnk-collapsemodule").hide();
		$(obj).find(".lnk-expandmodule").show();
		$(obj).find(".ctn-modulecontent").slideUp(200);
	} else if (action == 3) { // Expand
		if (!$(obj).find(".ctn-modulecontent").is(":visible")) {
			$(obj).find(".lnk-expandmodule").hide();
			$(obj).find(".lnk-collapsemodule").show();
			$(obj).find(".ctn-modulecontent").slideDown(200);
		}
	}
}

// Expose all
function exposeAllModules() {
	var dragModulesCollection = new Array();
	dragModulesCollection[0] = new Array();
	dragModulesCollection[0][0] = "gameinfo";
	dragModulesCollection[0][1] = "photos";
	
	dragModulesCollection[1] = new Array();
	dragModulesCollection[1][0] = "chat";
	dragModulesCollection[1][1] = "minmin";
	dragModulesCollection[1][2] = "highlights";
	dragModulesCollection[1][3] = "nearlive";
	dragModulesCollection[1][4] = "articles";
	
	for (collection = 0; dragModulesCollection.length > collection; collection++) {
		var columnName = "";
		if (collection == 0) {
			columnName = "col-left";
		} else {
			columnName = "col-right";
		}
		for (cont = 0; dragModulesCollection[collection].length > cont; cont++) {
			auxObj = $("."+dragModulesCollection[collection][cont]).next();
			if ($("."+dragModulesCollection[collection][cont]+":visible").parents(".ctn-module").size() == 0 && $("."+dragModulesCollection[collection][cont]+":visible").parents(".ctn-novideo").size() == 0) {
				$(".ctn-dragmodules ."+columnName).append($("."+dragModulesCollection[collection][cont]).show());
				$(".ctn-dragmodules ."+columnName).append(auxObj);
			}
		}
	}
	
	$(".lst-dragmodules").find("input:checkbox").each(function() { // Check all
		$(this).attr("checked","checked");
		updateCheck($(this).val());

	});
	
	for (index = 0; index < arrModules.length; index++) {
		updateModule(arrModules[index][0], arrModules[index][1]);
	}

	setTimeout("window.scrollTo(0,$('.ctn-dragmodules .col-left').offset().top)",1000); // Scroll down

}

function initDragModule() {
	$(".ctn-dragmodule").each(function(){$(this).jqDrag(".lnk-dragmodule")});
}

// Update checks
function updateCheck(value) {
	chkObj = $(".lst-dragmodules").find("input:checkbox[value='"+value+"']");
	if ($(chkObj).attr("checked")) {
		$(chkObj).prev().addClass("checked");
	} else {
		$(chkObj).prev().removeClass("checked");
	}
}

/* // Drag modules */
/* // Live */