(function($) {
// ignore firebug console.log calls when firebug is not available
if (typeof(window.console) == "undefined") {
	window.console = {
		log: function() {}
	};
}
/** 
 * start enclosure part 
**/

jQuery.fn.extend({
	lbconfirm: function(okFunction, cancelFunction) {
		var $t = $(this);
		$t.submit(function() {
			$.facebox(function() {
				
				var ok = $.create('button', {className: 'okButton'}, 'OK').click(function() {

					var data = $t.serializeArray();
					$.facebox(function() {

						$.post($t.attr('action'), data, function(info) {
							
							$.facebox(info.content);

							if (info.status) {
								if (typeof(okFunction) == 'function') {
									okFunction($t);
								}
								setTimeout(function() { $.facebox.close(); }, 2500);
							}
						
						}, 'json');

					});


				});
				var cancel = $.create('button', {className: 'cancelButton'}, 'Cancel').click(function() {
					if (typeof(cancelFunction) == 'function') {
						cancelFunction($t);
					}
					$.facebox.close();
				});

				var buttons = $.create('div', {className: 'confirm'}, [ok, cancel]);

				var resultFunction = function(info) {

					if (info.status) {
						$.facebox($.create('div', {}, [ info.content, buttons ]));
					} else {
						$.facebox(info.content);
					}
				};

				$.get($t.attr('action'), $t.serializeArray(), resultFunction,'json');
			}); 
			return false;
		});

		return $t;
	}, /* lbconfirm */

	/**
	 * Removes the <var>disabled</var> class from the matched form elements, and
	 * re-enables them.
	 * @return jQuery The matched elements.
	 */
	enable: function() {
		$(this).removeClass("disabled").attr("disabled", false);
		// in case 'this' is a single form tag, disable all elements below it
		if ($(this).length == 1 && $(this).get(0).tagName.toUpperCase() == 'FORM') {
			$(this).find('input,select,textarea').enable();
		}
		return $(this);
	}, /** // enable **/

	/**
	 * Disables the matched form elements, and adds the <var>disabled</var> class
	 * to them.
	 * @return jQuery The matched elements.
	 */
	disable: function()  {
		$(this).addClass("disabled").attr("disabled", true);
		// in case 'this' is a single form tag, disable all elements below it
		if ($(this).length == 1 && $(this).get(0).tagName.toUpperCase() == 'FORM') {
			$(this).find('input,select,textarea').disable();
		}
		
		return this;
	}, // $.fn.disable()

	grayout: function() {
		var $t = $(this);
		if ($t.length === 0) {
			return $t;
		}

		var onFocus = function() {
			$t.val('');
			$t.removeClass('gray');
		};

		$t.val('');

		var grayOut = function() {
			if ($t.val() === '' || $t.val() == $t.attr('title')) {
				$t.val($t.attr('title')).addClass('gray').one('focus', onFocus).blur(grayOut);
			}
		};
		grayOut();

		return $t;
	}, /** // grayout **/
	YouTube: function(width, height) {

		$(this).flash(
			{ height: height, width: width, wmode: 'transparent' },
			{ version: 8 },
			function(htmlOptions) {
				$this = $(this);
				var href = $this.attr('href');
				var id = href.replace(/.*?(youtube\.com\/v\/([^"\&]+)|youtube\.com\/watch\?v=([^"\&]+))/, '$3');
				htmlOptions.src = 'http://youtube.com/v/' + id;
				$this.before($.fn.flash.transform(htmlOptions));						
			}
		).hide();
	},

	serializeHash: function() {

		var l	= this.serializeArray();
		var obj	= {};
		for(var i = 0; i < l.length; i++) {
			obj[l[i].name] = l[i].value;
		}
		return obj;
	}
}); /* end fn.extend */
jQuery.fn.extend({

	max: function() {

		var max = 0;
		this.map(function(i, elem) { 
			if (elem > max) {
				max = elem;
			}
		});
		return max;
	
	},
	sum: function() {

		var total = 0;
		this.map(function(i, elem) { 
			total += (elem * 1);
		});
		return total;
	
	}
});

jQuery.extend({

	scrollTo: function(d, speed) {
		if (typeof(speed) == "undefined") {
			speed = 1100;
		}
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: d}, speed);
	}

});
$.lbajax = function(url, cb) {
	return $.facebox(function() {
		$.get(url, {}, function(info) { 
			$.facebox(info.content); 
			if ($.isFunction(cb)) {
				cb();
			}
		}, 'json');
	});
};

$.lbframe = function(style, name, url, onClose, closeArg) {

	if (typeof(name) == "undefined" || !name) {
		name = 'iframe_' + Math.round(Math.random()*800);
	}
	if (typeof(url) == "undefined" || !url) {
		name = 'about:blank';
	}

	$.facebox('<iframe frameborder="0" style="' + style + '" src="' + url + ' " name="' + name + '"></iframe>');
	if ($.isFunction(onClose)) {

		var onFbClose = function() {
			onClose.call(closeArg);
			$(document).unbind('close.facebox', onFbClose);
		};
		$(document).bind('close.facebox', onFbClose);

	}

	return name;
};

$.lbsubmit = function() {

	var style = $(this).attr('data:style');
	if (!style) {
		style = $(this).attr('rev');
	}

	if (!style) {
		style = 'width: 370px; height: 230px';
	}

	this.target = $.lbframe(style); 

	return true;
};

$.submitForm = function(el) {
	var $t = $(this);
	var $f = $t.parents('form:first');
	var data = $f.serializeArray();
	$f.disable();
	$.post($f.attr('action'), data, function() { $f.enable(); } );

	return $t;
};

$.absolutePosition = function (el) {
	var sLeft = 0, sTop = 0;
	var isDiv = /^div$/i.test(el.tagName);
	if (isDiv && el.scrollLeft) {
		sLeft = el.scrollLeft;
	}
	if (isDiv && el.scrollTop) {
		sTop = el.scrollTop;
	}
	var r = {x: el.offsetLeft - sLeft, y: el.offsetTop - sTop};
	if (el.offsetParent) {
		var tmp = $.absolutePosition(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

$.collapseScrollIntoView = function (node) {
	var h = self.innerHeight || document.documentElement.clientHeight || $("body")[0].clientHeight || 0;
	var offset = self.pageYOffset || document.documentElement.scrollTop || $("body")[0].scrollTop || 0;
	var pos = $.absolutePosition(node);
	var fudge = 55;
	if (pos.y + node.offsetHeight + fudge > h + offset) {
		if (node.offsetHeight > h) {
				window.scrollTo(0, pos.y);
		} else {
				window.scrollTo(0, pos.y + node.offsetHeight - h + fudge);
		}
	}
};

$.getPageHeight = function() {
	var windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}	
	return windowHeight;
};

$.toggleFieldset = function(fieldset) {

	var content;
	if ($(fieldset).is('.collapsed')) {
		content = $('> div', fieldset).hide();
		$(fieldset).removeClass('collapsed');
		content.slideDown( {
		duration: 300, // THE FIX
			complete: function() {
				// Make sure we open to height auto
				$(this).css('height', 'auto');
				$.collapseScrollIntoView(this.parentNode);
				this.parentNode.animating = false;
			},
			step: function() {
				 // Scroll the fieldset into view
				$.collapseScrollIntoView(this.parentNode);
			}
		});
		/*
		if (typeof Drupal.textareaAttach != 'undefined') {
			// Initialize resizable textareas that are now revealed
			Drupal.textareaAttach(null, fieldset);
		}
		*/
	} else {
		content = $('> div', fieldset).slideUp('medium', function() {
			$(this.parentNode).addClass('collapsed');
			this.parentNode.animating = false;
		});
	}
};

$.esc_slider = function() {

	var $t = $(this);

	$t.append('<img src="/img/eurovisionfamily/arrow_left.gif" alt="prev" class="prev" />');
	$t.append('<img src="/img/eurovisionfamily/arrow_right.gif" alt="next" class="next" />');
	$t.prepend('<div class="index-pos"><div class="index"></div></div>');

	var $slides 	= $t.find('ul.slides li');
	var $index = $t.find('div.index');
	for(var i = 0; i < $slides.length; i++) {
		$index.append('<div>&nbsp;</div>');
	}

	var currentIndex 	= 0;
	var $indice			= $index.find('div');
	var $currentObject 	= null;
	var timer 			= null;
	
	$index.width($indice.length * $indice.width());

	function swapObjects(i, o, dir) {

		var duration = 750;
		var ease = null;

		if (o) {

			$index.css('z-index', '3');
			$(o).css('z-index', '1');
			$(i).css('z-index', '2');
			var iw = $(i).width();
			var $buttons = $t.find('img.prev,img.next');
			$buttons.fadeOut('fast');

			if (dir == 1) {

				$(i).width(1).show().css({'right': 0, 'left': 'auto'}).animate({
					width: iw
				}, duration, ease, function() { $(o).hide(); $buttons.fadeIn('fast'); });

				$(o).animate({
					right: iw
				}, duration, ease);

			} else {

				$(i).show().css({'right': iw, 'left': 'auto'}).animate({
					right: 0
				}, duration, ease, function() { $(o).hide(); $buttons.fadeIn('fast'); });

				$(o).css({'left': 0, 'right': 'auto'}).animate({
					left: iw
				}, duration, ease);

			}
		} else {
			$(i).show();
		}

		return $(i);
	}

	function setCurrentIndex(i, dir) {
		if (i < $slides.length) {

			currentIndex = i;
			$indice.removeClass('active');
			$($indice.get($indice.length - i - 1)).addClass('active');
			$currentObject = swapObjects($slides.get(currentIndex), $currentObject, dir);

		}
	}
	
	function next() {
		currentIndex++;
		if ($slides.length == currentIndex) {
			currentIndex = 0;
		}
		setCurrentIndex(currentIndex, 1);
	}

	function prev() {
		currentIndex--;
		if (currentIndex < 0) {
			currentIndex = $slides.length - 1;
		}
		setCurrentIndex(currentIndex, -1);
	}

	function nextRotation(wait) {
		timer = setTimeout(function() {
			next();
			nextRotation(wait);
		}, wait);
	}

	function startRotation() {
		nextRotation(5000);
	}

	function stopRotation() {
		clearTimeout(timer);
	}

	/**
	 * attach clickers to the index
	 */
	var clickIndex = function() {
		var newCi = $indice.length - $(this).data('index') - 1;
		if (newCi != currentIndex) {
			setCurrentIndex(newCi, newCi > currentIndex ? 1 : -1);
		}
	};
	for(var j = 0; j < $indice.length; j++) {
		$ix = $($indice.get(j));
		$ix.data('index', j).click(clickIndex);
	}
	/**
	 * Hide all but the first
	 */
	$slides.hide();
	setCurrentIndex(0);

	$t.find("img.prev").click(prev);
	$t.find("img.next").click(next);
	$t.hover(stopRotation, startRotation);

	/**
	 * Start rotation
	 */
	startRotation();
};

/**
 * End enclose
**/
})(jQuery);

function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}

