/**
 * This file contains different jQuery functions
 * 
 * First functions are for madtv
 * 
 * shadow plugin is from ui.jquery.com
 * shadow is modified for madtv
 * 
 * dimensions plugin is from jquery.com/plugins/project/dimensions
 * 
 * jTip (modified) plugin is from http://www.learningjquery.com/2006/10/updated-plugin-jtip
 * jTip is also modified (livequery, dimensions) for madtv
 */


/**
 * Bugfix for live -> remove when new jQuery version handles this correctly
 */
// Fix for .live() bug with right click on Firefox,
// because right click it's not a click!
jQuery.fn.__live__ = jQuery.fn.live;
jQuery.fn.live = function(type,fn) {
	if(type != 'click') {
		return this.__live__(type, fn);
	} else {
		var anti_right_click_callback = fn;
		var anti_right_click_proxy = function(e) {
			if(e && e.button && e.button === 2) {
				e.stopPropagation();
				return true;
			} else {
				anti_right_click_callback.call(this, e);
			}
		};
		return this.__live__(type, anti_right_click_proxy);
	}
};



/**
 * Init
 * Use this function that way:
 * $("#some_id").showElementsInit({options});
 * $("#some_id").showNextElements();
 * The id is important because there can be more than one container to handle!
 */
(function($) {
	$.fn.showElementsInit = function(options) {
		id = $(this).attr("id");
		var opts = $.extend({}, $.fn.showElementsInit.defaults, options);
		if (typeof(optArray) == "undefined") {
			optArray = new Array();
		}
		optArray[id] = opts;
		optArray[id].elementsToHandle = $("#" + optArray[id].idOfContainer).children("." + optArray[id].classOfElements);
		if (typeof(optArray[id].countElements) == "undefined") {
			optArray[id].countElements = optArray[id].elementsToHandle.length;
		}
		$(".all_needs_item").hide();
		for (var i = optArray[id].index; i < optArray[id].index + optArray[id].count; i++) {
			if (i < optArray[id].countElements) {
				$(optArray[id].elementsToHandle[i]).show();
			}
		}
		optArray[id].index += optArray[id].count;
		
		$("#" + optArray[id].idOfMoveUp).hide();
		$("#" + optArray[id].idOfMoveDown).hide();
		if (optArray[id].countElements > optArray[id].count) {
			$("#" + optArray[id].idOfMoveDown).show();
		}
	};
	$.fn.showElementsInit.defaults = {
		count: 3,
		index: 0,
		idOfContainer: false,
		classOfElements: false,
		idOfMoveUp: false,
		idOfMoveDown: false
	};
})(jQuery);

/**
 * Show the next x items in a container
 */
(function($) {
	$.fn.showNextElements = function(options) {
		id = $(this).attr("id");
		for (var i = optArray[id].index; i < optArray[id].index + optArray[id].count; i++) {
			if (i < optArray[id].countElements) {
				$(optArray[id].elementsToHandle[i]).show();
			}
		}
		for (var i = optArray[id].index - 1; i >= optArray[id].index - optArray[id].count; i--) {
			if (i >= 0) {
				$(optArray[id].elementsToHandle[i]).hide();
			}
		}
		optArray[id].index += optArray[id].count;
		if (optArray[id].index >= optArray[id].countElements) {
			$("#" + optArray[id].idOfMoveDown).hide();
		}
		$("#" + optArray[id].idOfMoveUp).show();
	};
})(jQuery);

/**
 * Show the prev x items in a container
 */
(function($) {
	$.fn.showPrevElements = function(options) {
		id = $(this).attr("id");
		for (var i = optArray[id].index - 2 * optArray[id].count; i < optArray[id].index - optArray[id].count; i++) {
				$(optArray[id].elementsToHandle[i]).show();
		}
		for (var i = optArray[id].index - optArray[id].count; i < optArray[id].index; i++) {
			if (i < optArray[id].countElements) {
				$(optArray[id].elementsToHandle[i]).hide();
			}
		}
		optArray[id].index -= optArray[id].count;
		if (optArray[id].index <= optArray[id].count) {
			$("#" + optArray[id].idOfMoveUp).hide();
		}
		$("#" + optArray[id].idOfMoveDown).show();
	};
})(jQuery);


(function($) {
	$.fn.showInTooltip = function(options){
		var opts = $.extend({}, $.fn.showInTooltip.defaults, options);
		return this.each(function() {
			var o = $.meta ? $.extend({}, opts, $(this).data()) : opts;
			if ($(this).next(".details").length) {
				$(this).hover(function(){
					offsetContent = $("#game_screen").offset({ scroll: false });
				    offsetCurrent = $(this).offset({ scroll: false });
				    innerPosX = offsetCurrent.left - offsetContent.left + $(this).width() + 10;
				    innerPosY = offsetCurrent.top - offsetContent.top + 5;
				    if (offsetCurrent.left + $('#madtvTooltip').outerWidth({margin: "true"}) > offsetContent.left + $("#game_screen").width()) {
				    	innerPosX -= $("#madtvTooltip").width() + $(this).width() + 20;
				    }
				    $("#madtvTooltip").css("left", innerPosX);
				    $("#madtvTooltip").css("top", innerPosY);
				    $("#madtvTooltip").addClass("tooltipp");
				    $("#madtvTooltip").html('<div id="madtvTooltipInner" class="shadow">' + $(this).next(".details").html() + '</div>');
				    $("#madtvTooltip").show();
			    },function() {
			    	$("#madtvTooltip").hide();
			    	$("#madtvTooltip").removeAttr("style");
			    	$("#madtvTooltip").removeAttr("class");
			    });
			}
		});
	};
	$.fn.showInTooltip.defaults = {
	};
})(jQuery);

/**
 * Show fixed tooltip (used for movie and ad details and other)
 */
(function($) {
	$.fn.fixedTooltip = function(options) {
		var opts = $.extend({}, $.fn.fixedTooltip.defaults, options);
		return this.each(function() {
			var o = $.meta ? $.extend({}, opts, $(this).data()) : opts;
			$(this).mouseover(function(e){
		        // width of tooltip
		        if (!o.width) {
		        	o.width = 280;
		        }
		        
		        $("#madtvTooltip").css("width", o.width);
		        // offset to left
		        offsetContent = $("#game_screen").offset({ scroll: false });
				$(this).mousemove(function(e){
					cursorPosX = e.pageX ? e.pageX : e.clientX + window.document.documentElement.scrollLeft;
					innerPosX = cursorPosX - offsetContent.left;
			        // elements are displayed in an area map
			        if (innerPosX == 0) {
			            coords = $(this).attr("coords");
			            coords = coords.split(",");
			            innerPosX = coords[0];
			        }
			        // if there's no space on the left side, show tooltip on right side
			        if (innerPosX < 320) {
						$("#madtvTooltip").css("left", (340 + 280 - o.width));
			        } else {
						$("#madtvTooltip").css("left", 18);
			        }
				});
		        if (o.tooltipClass) {
		        	$("#madtvTooltip").toggleClass(o.tooltipClass);
		        }
				$(this).fixedTooltipDisplay();
		    });
			$(this).mouseout(function(e){
			    $("#madtvTooltip").hide();
			    $("#madtvTooltip").empty();
			    if (o.tooltipClass) {
		        	$("#madtvTooltip").toggleClass(o.tooltipClass);
		        }
		        // hide all movie and ad category pictures in console
	        	$("#console").children(".console_movie").hide();
			});
		});
	};
	$.fn.fixedTooltip.defaults = {
		tooltipClass: false,
		tooltipDetails: true,
		width: 0
	};
})(jQuery);

/**
 * Show fixed tooltip at once
 */
(function($) {
	$.fn.fixedTooltipDisplay = function(options) {
		var opts = $.extend({}, $.fn.fixedTooltip.defaults, options);
		return this.each(function() {
			var o = $.meta ? $.extend({}, opts, $(this).data()) : opts;
	        if ($(this).next(".details").children(".meta_category")) {
	        	$("#console_movie_" + $(this).next(".details").children(".meta_category").text()).show();
	        }
	        if ($(this).next().is(".details")) {
	        	$("#madtvTooltip").html('<div id="madtvTooltipInner" class="shadow">' + $(this).next(".details").html() + '</div>');
	        }
        	$("#madtvTooltip").show();
		});
	};
})(jQuery);

/**
 * Display an element with a shadow and a fade effect
 */
(function($) {
	// plugin definition
	$.fn.madtvShow = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.madtvShow.defaults, options);
		// iterate and reformat each matched element
		return this.each(function() {
			// build element specific options
			var o = $.meta ? $.extend({}, opts, $(this).data()) : opts;
			if ($(this).css("display") != "block" && $(this).css("display") != "inline") {
				if (o.fade) {
					$(this).fadeIn();
				} else {
					$(this).show();
				}
				if (o.shadow) {
					$(this).dropShadow({'blur': 0, 'color': '#000', 'opacity': 1});
				}
			}
		});
	};
	// plugin defaults
	$.fn.madtvShow.defaults = {
		shadow: true,
		fade: false
	};
})(jQuery);

(function($) {
	// plugin definition
	$.fn.madtvHide = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.madtvHide.defaults, options);
		// iterate and reformat each matched element
		return this.each(function(i) {
			// build element specific options
			var o = $.meta ? $.extend({}, opts, this.data()) : opts;
			if (o.fade) {
				$(this).fadeOut();
			} else {
				$(this).hide();
			}
			$(this).removeShadow();
		});
	};
	// plugin defaults
	$.fn.madtvHide.defaults = {
		fade: false
	};
})(jQuery);

(function($) {
	// plugin definition
	$.fn.madtvRemove = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.madtvRemove.defaults, options);
		// iterate and reformat each matched element
		return this.each(function(i) {
			// build element specific options
			var o = $.meta ? $.extend({}, opts, this.data()) : opts;
			$(this).removeShadow();
			if (o.fade) {
				$(this).fadeOut().remove();
			} else {
				$(this).remove();
			}
		});
	};
	// plugin defaults
	$.fn.madtvRemove.defaults = {
		fade: false
	};
})(jQuery);


/* dimensions plugin (Version 1.2) */

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		var val = this.is(':visible') ? 
				this[0]['offset' + name] : 
				num( this, name.toLowerCase() )
					+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
					+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
		
		return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);





/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 
 * Modifications by Rey Bango and Karl Swedberg
 * livequery and dimensions modifications by Sven Burkert
 */

function JT_init(cObj){
	// show jTip only, if there doesn't already exist one
	if (!$("#JT").length) {
		jTipObj = cObj;
		jTipTitle = jTipObj.title;
		jTipUrl = $(jTipObj).attr('href');
		jTipLinkId = jTipObj.id;
		if(jTipUrl != "#"){
			$(jTipObj).removeAttr("title");
		}
		if (typeof(jTipTimeout) != "undefined") {
			clearTimeout(jTipTimeout);
		}
		jTipTimeout = setTimeout("JT_show()", 400);
	}
}

function JT_show(){
	if(jTipTitle == false) jTipTitle = "&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(jTipLinkId);
	var clickElementy = getAbsoluteTop(jTipLinkId) - 3; //set y position
	
	var queryString = jTipUrl.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
  		$('#' + jTipLinkId).bind('click',function(){window.location = params['link']});
  		$('#' + jTipLinkId).css('cursor','pointer');
  	}
  	if(jTipUrl != "#"){
		body = "<div id='JT_copy'><div class='JT_loader'><div></div>";
	} else {
		body = "";
	}
	
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_close_left' class='JT_title'>" + jTipTitle + "</div>" + body + "</div>");//right side
		$('body').append('<div id="JT_arrow_left" class="JT_arrow"></div>'); 
		var arrowOffset = getElementWidth(jTipLinkId) + 11;
		var clickElementx = getAbsoluteLeft(jTipLinkId) + arrowOffset; //set x position
		$('#JT_arrow_left').css({left: (clickElementx - 10) + "px", top: clickElementy +"px"});		
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_close_right' class='JT_title'>" + jTipTitle + "</div>" + body + "</div>");//left side
		$('body').append('<div id="JT_arrow_right" class="JT_arrow"></div>');
		var clickElementx = getAbsoluteLeft(jTipLinkId) - ((params['width']*1) + 20); //set x position
		$('#JT_arrow_right').css({left: (getAbsoluteLeft(jTipLinkId) - 20) + "px", top: clickElementy + "px"});		
	}
	if ($.browser.msie) { 
		$('#JT').prepend('<iframe id="jTipiFrame"></iframe>'); // iframe for IE select box z-index issue
		$('#jTipiFrame').width((params['width']*1) + "px");	
	}	
	$('#JT').css({left: clickElementx+"px", top: clickElementy +"px"});
	if(jTipUrl != "#"){
		$.ajax({ /* make compatible with madtv javascript */
			url: jTipUrl,
			dataType: "html",
			success: function(data){
				$('#JT_copy').html(data);
				//if jtip goes to left side and is partially cut off at left of doc...	  
				if ($('#JT_arrow_right') && clickElementx < 0) {
					var JT_width = (getAbsoluteLeft(jTipLinkId) - 22);
					$('#JT').css({left: 2, width: JT_width}); //adjust width to fit
				}
				//get the height of the jtip after loading it
				var jtip_height = $('#JT').height();
				//adjust the top of jTip
				move_jtip();
				if ( (scroll_position + window_height) - clickElementy < jtip_height ) {
					var adjusted_top = (window_height - jtip_height) - 6 + scroll_position;
					if ( adjusted_top - scroll_position < 0 ) {
						$('#JT').css({top: scroll_position + 1});
					} else {
						$('#JT').css({top: adjusted_top});
					}
				}
			}
		});
	}
	$('#JT, .JT_arrow').fadeIn();
} // end JT_show()

function JT_hide(){
	clearTimeout(jTipTimeout);
	$(jTipObj).attr("title", jTipTitle);
	$('#JT, .JT_arrow').remove()
}

function getElementWidth(objectId) {
	//x = document.getElementById(objectId);
	//return x.offsetWidth;
	x = $("#" + objectId);
	return $("#" + objectId).width();
}

function getAbsoluteLeft(objectId) {
	offset = $("#" + objectId).offset({scroll: true});
	return offset.left;
}

function getAbsoluteTop(objectId) {
	offset = $("#" + objectId).offset({scroll: true});
	return offset.top;
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function move_jtip() {
  if (window.innerHeight) {
	  scroll_position = window.pageYOffset;
	  window_height = window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		scroll_position = document.documentElement.scrollTop;
    window_height = document.documentElement.clientHeight;
	}
	else if (document.body) {
	  scroll_position = document.body.scrollTop;
	  window_height = document.body.clientHeight;
	}
}

function blockEvents(evt) {
  if(evt.target){
    evt.preventDefault();
  }else{
    evt.returnValue = false;
  }
}