(function($) {
	$.fn.imageCycler = function(arg, parameters) {
		if(this.length>0) {
			var self = this;

			if(typeof(arg)=="object" || (typeof(arg)=="undefined" && typeof(parameters)=="undefined")) {
				options = arg;
				var defaultConfig = {
					cycleNavigationClass: ".cycleNavigation",
					cycleContentClass: ".cycleContent",
					cycleListClass: ".cycleList",
					cycleThumbsClass: ".cycleThumbs",
					activeClassName: "active",
					fadeOutOpacity: 0.5,
					normalOpacity: 1,
					intervalSeconds: 5,
					animSpeed: 350,
					crossFade: true,
					autoCycle: true
				}, settings = $.extend(defaultConfig, options);

				self.data( "_currentIndex", 0);
				self.data( "_interval", false);

			} else {
				var settings = self.data( "settings");
			}
			
			self._currentIndex = self.data( "_currentIndex");
			self._contentContainer = $(settings['cycleContentClass'], self);
			self._items = $(settings['cycleListClass']+" li", self);
			self._itemList = $(settings['cycleListClass'], self);
			self._navigation = $(settings['cycleNavigationClass'], self);
			self._thumbs = $(settings['cycleThumbsClass'], self);
			self._hasPips = self._navigation.length>0;
			self._hasThumbs = self._thumbs.length>0;
			self._pipList = false;
			self._thumbList = false;
			
			$.extend(self, {
				jumpTo : function(target, newPosition) {
					var currentIndex = target.data( "_currentIndex");
					clearInterval(target.data( "_interval"));
					target.transition(target, currentIndex, newPosition);
					target.data( "_currentIndex", newPosition);
				},
				
				cycle : function(target) {
					var currentIndex = target.data( "_currentIndex");

					var nextIndex = currentIndex+1;
					if (nextIndex>target._items.length-1) {
						nextIndex = 0;
					}
					target.transition(target, currentIndex, nextIndex);
					target.data( "_currentIndex", nextIndex);
				},

				transition : function(target, from, to) {
					var fadeInFunc = function(target) {
						$(target._items.get(to)).css({zIndex:20,opacity:0}).animate({opacity:settings['normalOpacity']}, settings['animSpeed']).addClass(settings['activeClassName']);
						if(target._hasPips) {
							$("."+settings['activeClassName'], target._navigation).removeClass(settings['activeClassName']);
							$(target._pipList.get(to)).addClass(settings['activeClassName']);
						}
						if(target._hasThumbs) {
							$(target._thumbList.get(to)).addClass(settings['activeClassName']);
							$("."+settings['activeClassName']+" a", target._thumbs).animate({opacity: 1}, settings['animSpeed']);
						}
					} 
					
					if(target._hasThumbs) {
						$("."+settings['activeClassName']+" a", target._thumbs).animate({opacity: settings['fadeOutOpacity']}, settings['animSpeed'])
						$("."+settings['activeClassName'], target._thumbs).removeClass(settings['activeClassName']);
					}
					$(target._items.get(from)).css({zIndex:10}).animate({opacity:0}, settings['animSpeed'], (function(target) {
						$(this).removeClass(settings['activeClassName']);
						if (settings['crossFade']===false) {
							fadeInFunc(target);
						}
					})(target));
					if (settings['crossFade']===true) {
						fadeInFunc(target);
					}
				}
			});
			
			if(typeof(arg)=="object" || (typeof(arg)=="undefined" && typeof(parameters)=="undefined")) {
				$(self).css({position: "relative", opacity:0, visibility: "visible"});
				$(self._navigation).css({ position: "absolute"});
				$(self._items.get(0)).addClass(settings['activeClassName']).css({opacity:settings['normalOpacity']});
				var maxheight = 0;
				
				if(self._hasPips) {
					$(self._navigation).html('');
				}
				if(self._hasThumbs) {
					$(self._thumbs).html('');
				}
				self._items.css({position: "absolute", top:0 }).each(function() {
					maxheight = Math.max($(this).height(), maxheight);
					if(self._hasPips) {
						$(self._navigation).append('<li><a href="">pip</a></li>');
					}
					if(self._hasThumbs) {
						$(self._thumbs ).append('<li><a href="#">'+($(".thumb", this).length>0 ? $(".thumb", this).html() : $("a", this).html())+'</a></li>')
					}
				});
				$(self._contentContainer).css({ position: "relative"}).height(maxheight);
				
				if(self._hasPips) {
					self._pipList = $("li", self._navigation);
					$(self._pipList.get(0)).addClass(settings['activeClassName']);
					$(self._pipList).bind("click", {target:self}, function(e) {
						if(!$(this).hasClass(settings['activeClassName'])) {
							self.jumpTo(e.data.target, $(this).index());
						}
						return false;
					});						
					$(self._navigation).css({zIndex: 30});
				}
				
				if(self._hasThumbs) {
					self._thumbList = $("li", self._thumbs);
					self._thumbs.css({"z-index": 100});
					$("li a", self._thumbs).css({opacity: settings['fadeOutOpacity']});
					$(self._thumbList.get(0)).addClass(settings['activeClassName']);
					$("."+settings['activeClassName']+" a", self._thumbs).css({opacity: 1});
					$(self._thumbList).live("click", {target:self}, function(e) {

						if(!$(this).hasClass(settings['activeClassName'])) {
							self.jumpTo(e.data.target, $(this).index());
						}
						return false;
					});						
				}

				$(self).animate({opacity:1}, settings['animSpeed'], function(target) { 
					$(target).css({opacity:""});
				});
				if(settings['autoCycle']) {
					self.data("_interval", setInterval(function() { self.cycle(self); }, settings['intervalSeconds']*1000));
				}
			} else {
				switch(arg) {
					default:
				}
			}

			self.data( "settings", settings);
		}
		return this;
	}
})(jQuery);

(function($){
$.fn.clearReFill = function() {
    this.each(function(){
        var $this = $(this);
        if ($this.is('input'))
            setEvents($this, 'val', $this.val());
        else if ($this.is('textarea'))
            setEvents($this, 'html', $this.html());
        else 
            return;
    });
    return this;
};

function setEvents($element, valueFunc, initValue) {
    $element.focus(function() {
            if ($element[valueFunc]() === initValue){
                $element[valueFunc]('');
             }
        })
        .blur(function() {
            if ($element[valueFunc]() === ''){
                $element[valueFunc](initValue);
                }
        });
}
})(jQuery);

$(window).ready(function() {
	var fadeSpeed = 300,fadeCascadeDelay = 150,fadeIndex = 1;
	var borderSize = 5;
	$('#searchQueryText').clearReFill();
	$('input[type=submit]:not(.button),input[type=button]:not(.button)').addClass('button');
	$('input[type=text]:not(.text),textarea:not(.text)').addClass('text');
	
	$('.border').each(function() {
		$(this).append($('<div class="border_inner">').append($(this).contents()));
		$('.border_inner', this).css("margin", borderSize);
	});
	
	$('.video').each(function() {
		$(this).prepend('<div class="video_overlay"></div>');
		$(this).css({position: "relative", zIndex: 10 });
		$('.video_overlay').css({position: "absolute", top: 0, left: 0, zIndex: 20 });
		$('.video_overlay', this).width($(this).width());
		$('.video_overlay', this).height($(this).height());
	});
	var thumbCount = 1;
	$('.altLayout .thumb').each(function() {
		$(this).prepend('<div class="thumb_overlay">'+(thumbCount++)+'</div>');
		$(this).css({position: "relative", zIndex: 10 });
		$('.thumb_overlay').css({position: "absolute", top: 0, left: 0, zIndex: 20 });
	});
	
//	var floatListLi = $(".floatList").find("li");
//	
//	if(floatListLi.length>0) {
//		
//		floatListLi.each(function(index) {
//		var h = $(".highlight").height();
//		var $self = $(this), index = $self.index();
//			if(index%2==1) { // if the LI is even add the alt class. This is used for the shift fixes
//				$self.addClass("alt");
//				if($self.parent().hasClass('fixSize')){
//				    var height = $self.height();
//				    if(index === 1){ // we dont want to move the top LI
//				     h = 0;
//				    }
//				    if ($.browser.msie && $.browser.version.substr(0,1)<7) { // WTF?!
//				       h = h - height - 20;    //20px accounts for the margins. The li is shifted to match the Star letter. This must always be the bigger than the next article down.
//				        $self.css({marginTop: "-"+h+"px"});
//				    }else{
//				      h = h - height - 20;
//				        $self.css({marginTop: "-"+h+"px"});
//				    }    
//				    
//				   //  console.log(h, $self, index);
//				}
//			}
//		});
//	}
		
	var x = function() {
		if($('#competition').length>0) {
			$('#competition').delay(fadeIndex*fadeCascadeDelay).imageCycler({animSpeed: fadeSpeed});
			fadeIndex++;
		}
		
		if($('#latestNews').length>0) {
			$('#latestNews').delay(fadeIndex*fadeCascadeDelay).imageCycler({intervalSeconds: 7, animSpeed: fadeSpeed});	
			fadeIndex++;
		}
		
		if($('#games').length>0) {
			$('#games').delay(fadeIndex*fadeCascadeDelay).imageCycler();
			fadeIndex++;
		}
		
		if($('#gameContent').length>0) {
			$('#gameContent').delay(fadeIndex*fadeCascadeDelay).fadeIn(fadeSpeed, function() {

				var visibleSize = 4;
				var unitSize = 146;
				var maxSize = $('#gamesList li').length;
				var speed = 250;
				$('#gamesList').data("pos", 1);
				
				var updatePos = function() {
					var pos = $('#gamesList').data("pos");
					if(pos*visibleSize>=maxSize) {
						$('#gameThumbs .next').addClass("last");
					} else {
						$('#gameThumbs .last').removeClass("last");					
					}

					if(pos==1) {
						$('#gameThumbs .prev').addClass("first");
					} else {
						$('#gameThumbs .first').removeClass("first");					
					}
				
				};
				updatePos();
				
				$('#gameThumbs .next').bind("click", function() {
					var pos = $('#gamesList').data("pos");
					pos++;
					$('#gamesList ul').stop(true, true).animate({left: "-"+((pos-1)*visibleSize*unitSize)+"px"}, speed, function() {
						$('#gamesList').data("pos", pos);
						updatePos();
					});
					return false;
				});

				$('#gameThumbs .prev').bind("click", function() {
					var pos = $('#gamesList').data("pos");
					pos--;
					$('#gamesList ul').stop(true, true).animate({left: "-"+((pos-1)*visibleSize*unitSize)+"px"}, speed, function() {
						$('#gamesList').data("pos", pos);
						updatePos();
					});
					return false;
				});
			});
			fadeIndex++;
		}

		
		$(".widget,.pageContent,.PhoenixPollWidget").each(function() {
			if ($(this).css("visibility")=="hidden") { 
				$(this).css({opacity:0, visibility:"visible"}).delay(fadeIndex*fadeCascadeDelay).animate({opacity:1}, fadeSpeed, function() { 
					$(this).css({opacity:""});
				});
				fadeIndex++;
			}
		});
	};
	
	setTimeout(x, 100);
	
	flowplayer(".flowplayer", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", {
	    clip: {
		    autoPlay: false, 
		    autoBuffering: true // <- do not place a comma here  
	    }
	});
});
