$(document).ready(function() {

	if (typeof($.facebox) != 'undefined') {
		$('a[rel*=lyteframe]').click(function(e, a) {
			var a = e.currentTarget;
			$.facebox('<iframe frameborder="0" style="'+a.rev+'" src="'+a.href+'"><a href="' + a.href+'">click here</a></iframe>');
			return false;
		});
		$('a[rel*=lytebox]').facebox();
	};

	if ($('textarea.remaining').length) {

		var $t = $('textarea.remaining');
		var $p = $t.parents('fieldset');
		var $r = $p.find('span.remaining');
		var max = $r.html();

		var lastValue = $t.val();
		$r.html("" + (max - lastValue.length));

		$t.keyup(function() {
			var len = $(this).val().length;
			if (len > max) $(this).val(lastValue);
			else {
				$r.html("" + (max - len));
				lastValue = $(this).val();
			}
		});
	}
	/**
	 * no annoying dotted lines 
	*/
	$('a').focus(function(el) {
		this.blur();
	});
	/**
	 * Fix image padding/margin
	*/
	if (!$.browser.msie) {
		/*
		$('div.image').css('paddingBottom', '0px');
		*/
	};

	$('a.hover').each(function(i, el) {
		el 	= $(el);
		img = el.find('img');
		if (img) {
			var offSrc 	= img.attr('src');
			var onSrc	= offSrc.replace('off.', 'on.');

			el.hover(function() {
				el.find('img').attr('src', onSrc);
			}, function() {
				el.find('img').attr('src', offSrc);
			});
		};
	});

	/**
	 * auto popups
	*/
	$('a.popup').click(function(event) {

		// we have a default size
		var width 		= 400;
		var height 		= 400;
		var scrolling 	= '1';

		if (this.rev) {
			var rev = this.rev.split(" ");

			// which can easily be overridden
			if (rev[0].split('x').length == 2) {
				var parts = this.rev.split('x');
				width 	= parts[0];
				height	= parts[1];
			}

			if ($.grep(rev, function(val) { val == 'noscroll' })) scrolling = '0';
		};

		var target = (typeof(this.target) == 'undefined' || this.target == "") ? 'Popup' + Math.round(Math.random() * 100) : this.target;
		var win = window.open(this.href, target, 'status=1,toolbar=0,location=0,menubar=0,directories=0,resizeable=1,scrollbars='+scrolling+',height=' + height + ',width=' + width);
		if (win) win.focus();

		return false;
	});

	/**
	 * a bit of fancier display of the pager
	*/
	$('div.pager').each(function(i, el) {

		var list = $(el).find('div.l');
		list.each(function(index, div) {
			if (index != list.length - 1) $(div).after(' | ');
		});

	});

	/**
	 * loginbox should display name when logged in
	*/
	$('#top').each(function(i, el) {

		var myId = $.cookie('firstName') ? 'loggedin' : 'not_loggedin';
		var my = $('#' + myId);
		if ($.cookie('firstName')) {
			
			var html = my.html();
			html = html.replace('#[Name]', $.cookie('firstName'));
			my.html(html);

			if ($.cookie('userId')) {
				$('.showTo' + $.cookie('userId')).show();
			}

			$('.hideToLogin').hide();

		}

		my.show();
	});

	/**
	 * after every block of links, clear out
	*/
	$('ul.links').after('<div style="clear: both"></div>');

	/**
	 * those nice pinkblocks have up and down states
	 */
	$('ul.pinkblocks li').each(function(i, el) {
		if ($(el).find('.inside').length == 0) $(el).find('a').wrap('<div class="inside" />');

		// init image paths
		var orig 	= $(el).css('backgroundImage');
		var over	= orig.replace(/_off.jpg/, '_over.jpg');
		var down	= orig.replace(/_off.jpg/, '_on.jpg');

		// preload images
		(new Image()).src = over.replace(/(url\("?|"?\))/g, '');
		(new Image()).src = down.replace(/(url\("?|"?\))/g, '');

		$(el).find('a').hover(function() {

			$(el).css('backgroundImage', over);

		}, function() {

			$(el).css('backgroundImage', orig);

		});
		
		$(el).find('a').mousedown(function() {

			$(el).css('backgroundImage', down);
			
		});
	});

	/**
	 * login happens in an iframe, after a successful login we want to get back to the main page 
	*/
	$('.login_ok').each(function() {
		if (window.parent) {
			var p = window.parent;

			window.parent.setTimeout(function() {

				var loc = p.location.href;
				loc 	+= (loc.match(/\?/) ? '&rnd=' : '?rnd=') + Math.random();
				p.location.href = loc;

			}, 1000);
		};
	});

	$('div.bb').each(function() {
		if ($(this).height() < 325) $(this).height(325);
	});

	/**
	 * display a text in the search field
	*/
	$('div.search input.text_field').each(function(i, el) {

		var def = 'Search the Eurovision Family';

		if (el.value == '' || el.value == def) {
			$(el).addClass('inactive').attr('value', def);
			el.onfocus = function() {
				$(el).removeClass('inactive');
				el.value 	= '';
				el.onfocus 	= null;
			}
		}

	});
	/**
	 * Fit an element into the complete height
	*/
	$('div.container div.fit-y').each(function(i, el) {
		$(el).height($(el).parent('div.container').height());
	});

	$('.report form').submit(function() {

		var form = $(this);

		var msg = 'Are you sure you wish to report this post to the moderators? Only click yes if you believe that this post does not meet the guildelines!';

		if (typeof($.prompt) == 'undefined') {
			return confirm(msg);
		}

		$.prompt(msg, {
			buttons: { Yes: 1, No: 2},
			prefix: 'colsJqi',
			show: 'fadeIn',
			callback: function(b, el) {
				if (b == 1) form.ajaxSubmit({
						success: function(val) {
							form.parent().remove();
							alert(val.content);
						},
						dataType: 'json'
					});
			}
		});

		return false;

	});

	/**
	 * ImageScroller
	*/
	/*
	$('div.ImageScroll').each(function(i, el) {
		
		// set id for viewer frame
		$(el).find('div.qw').get(0).id = 'ImageScrollFrame' + i;

		// add next and prev buttons
		$(el).prepend('<span id="btnNext' + i + '"></span>');
		$(el).prepend('<span id="btnPrev' + i + '"></span>');

		// do the muck
		$(el).imageScroller({
			next: 'btnNext' + i,
			prev: 'btnPrev' + i,
			frame: 'ImageScrollFrame' + i,
			width: 95,
			child: 'a',
			auto: true
		});


	});
	*/
});

var debug = function() {
	// do nothing
}
if (typeof(console) != "undefined") {
	debug = function(str) {
		console.log(str);
	};
}

function tsSortValue(a, b) {
	return fdTableSort.sortText(a, b);
}
function tsSortValueNumeric(a, b) {
	return fdTableSort.sortNumeric(a, b);
}
function tsSortValueNumericPrepareData(td, inner) {
	return tsSortValuePrepareData(td, inner);
}
function tsSortValuePrepareData(tdNode, innerText) {
	try {
		var txt = $(tdNode).find('.sortValue').html();
		return txt;
	} catch(e) {
		return innerText;
	}
}
function fbs_click() {
	/** 
	 * Just to make sure stage is never referenced
	*/
	var u=location.href.replace('stage', 'www');
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function refreshStylesheets(loop) {
	var rnd = Math.round(Math.random()*500);
	$('link').each(function(i, l) {
		try {
			l.href = l.href.replace(/\?.*$/, '') + '?rnd = ' + rnd;
			debug(l.href);
		} catch(e) { debug(e); };
	});

	if (loop > 1000) {
		setInterval(refreshStylesheets, loop);
	}
}


function rgbToHex(color) {
	var rgb =  color = color.replace(/[^\d,]/g, '').split(',');
	var r = Math.round(rgb[0]);
	var g = Math.round(rgb[1]);
	var b = Math.round(rgb[2]);
	return '#' + (r < 16 ? '0' : '') + r.toString(16) +
		(g < 16 ? '0' : '') + g.toString(16) +
		(b < 16 ? '0' : '') + b.toString(16);

}
/**
 * Hook into lytebox in order to track images
*/
(function() {
if (typeof(LyteBox) != "undefined") {
	var orig = LyteBox.prototype.changeContent;
	LyteBox.prototype.changeContent = function(imageNum) {

		orig.apply(this, arguments);
		if (!this.isLyteframe) {

			var src = (this.isSlideshow ? this.slideArray[this.activeSlide][0] : this.imageArray[this.activeImage][0]);
			pageTracker._trackPageview(src);

		}
	}
}
})();
