var user_url;
var mousePosition = {
	x: 0,
	y: 0
}

function hideInteractions()
{
	$('.interactions').css('display', 'none');
}

$(document).ready(function(){
	var showtimeout;
	$('#ajaxProgress').bind('ajaxSend', function(){
		showtimeout = setTimeout(function(){
			$(this).show();
		}, 200);
	}).bind('ajaxComplete', function(){
		clearTimeout(showtimeout);
		$(this).hide();
	});
	
	$('#prereg').css('display', 'none');
	$('#login').css('display', 'none');
	
	var browserClass;
	switch (true)
	{
		case $.browser2.firefox():
			browserClass = 'firefox';
			break;
		case $.browser2.msie():
			browserClass = 'msie';
			break;
		case $.browser2.safari():
			browserClass = 'safari';
			break;
	}
	if (browserClass)
	{
		$('body').addClass(browserClass);
	}
	
	var osClass;
	switch (true)
	{
		case $.browser2.mac():
			osClass = 'mac';
			break;
		case $.browser2.win():
			osClass = 'win';
			break;
	}
	if (osClass)
	{
		$('body').addClass(osClass);
	}
	
	$(document).mousemove(function(e){ mousePosition.x = e.pageX; mousePosition.y = e.pageY; });
});

var regexp = {
	email: /^[^ ]+@[^ ]+\.[a-z]{2,6}$/i
}

var ie6 = function(){
	return ($.browser.msie && /^6/.test($.browser.version));
};

var message = {
	prepared: false,
	show: function(headline, text)
	{
		if (!this.prepared)
		{
			$('#message').find('.close').click(function(){
				$('#message').css('display', 'none');
			});
			this.prepared = true;
		}
		$('#message').find('.h2').html(headline);
		
		$('#message').css('display', 'block');
		var minHeight = $('#message').find('.h2').height()+14;
		
		if (!text)
		{
			var cssProperties = ie6() ? { height: minHeight + 'px' } : { minHeight: minHeight + 'px' };
			$('#message')
				.find('.content').removeClass('content2').css(cssProperties)
				.find('.element').css('display', 'none');
		}
		else
		{
			$('#message')
				.find('.content').addClass('content2').css({ paddingTop: minHeight + 'px', minHeight: minHeight + 'px' })
				.find('.element').css('display', 'block');
			$('#message').find('.bodytext').html(text);
		}
			
		
		if ($('#content').attr('class').indexOf('userhome') != -1)
		{
			$('#message').css('left', 316);
		}
		else if (!$('#content').hasClass('profile'))
		{
			$('#message').css('left', ($('#page').width()-$('#message').width())/2);
		}
		
		$('#message').css('top', 
			( $(window).height() - $('#message').height() ) / 2 + $(window).scrollTop() - $('#page').offset().top
		);
		/*
		$('#message').css('top', (mousePosition.y + 25 - $('#page').offset().top));
		*/
	}
}

var lightbox = {
	ref: null,
	prepared: null,
	prepare: function(){
		var self = this;
		
		$(window).keyup(function(e){ self.keyboard(e); });
		
		this.ref = $('.lightbox').get(0);
		
		$(this.ref).find('.arrow_left, .previous')
			.css('visibility', 'hidden').click(function(){ self.prev(); });
		$(this.ref).find('.arrow_right, .next')
			.css('visibility', 'hidden').click(function(){ self.next(); });
		
		$(this.ref).find('.close').click(function(){ self.close(); });
		
		$(this.ref).find('.background').height($('#page').height());
		$(this.ref).find('.numbers').css('visibility', 'hidden');
		
		this.loading();
		this.prepared = true;
	},
	keyboard: function(e){
		if (e.keyCode == 27) // Esc
		{
			this.close();
		}
		else if (e.keyCode == 37) // Arrow left
		{
			this.prev();
		}
		else if (e.keyCode == 39) // Arrow right
		{
			this.next();
		}
	},
	
	index: null,
	image: null,
	roll: [],
	descriptions: [],
	animate: function(w, h, onComplete){
		var bgWidth = $(this.ref).find('.background').width();
		var padding = parseInt($(this.ref).find('.imageview').css('paddingLeft'))+parseInt($(this.ref).find('.imageview').css('paddingRight'));
		var left = (bgWidth-(w+padding))/2;
		
		var self = this;
		
		$(this.ref).find('.imageview').animate({ left: left, width: (w) });
		$(this.ref).find('.image').animate({ width: w, height: h }, { complete: function(){ onComplete.call(self); } });
	},
	close: function(){
		this.roll = this.descriptions = [];
		$(this.ref).find('.image').html('');
		$(this.ref).css('display', 'none');
	},
	expose: function(){
		if (this.descriptions[this.index])
		{
			this.showDescription(this.descriptions[this.index]);
		}
		$(this.ref).find('.image').html('<img src="' + this.image.src + '" />');
	},
	load: function(src){
		var self = this;
		if (/\.flv$/.test(src))
		{
			this.showVideo(src);
		}
		else
		{
			this.loading();
			this.image = new Image();
			this.image.onload = function(){
				self.animate(self.image.width, self.image.height, self.expose);
			}
			var maxHeight = Math.min($('#page').height(), $(window).height())-150;
			maxHeight = Math.round(maxHeight/100)*100;
			this.image.src = get_image(src, 900, maxHeight);
		}
	},
	loading: function(){
		this.showDescription('');
		$(this.ref).find('.image').html('<div style="margin-top: 50px;"><img src="' + global_url + 'image/loading.black.gif" alt="Loading..." /></div>');
	},
	prev: function(){
		if (this.index > 0)
			this.showFromRoll(this.index-1);
		else
			this.showFromRoll(this.roll.length-1);
	},
	next: function(){
		if (this.index < this.roll.length-1)
			this.showFromRoll(this.index+1);
		else
			this.showFromRoll(0);
	},
	show: function(index, roll, descriptions, skipLogin){
		if (!user_id && !skipLogin)
		{
			login.show(true, lang('login_to_view_image'), { referer: 'gallery', referer_info: 'user_url:' + user_url });
			return;
		}
		
		if (!this.prepared) this.prepare();
		$(this.ref).css('display', 'block')
		
		if (roll) 			this.roll = roll;
		if (descriptions) 	this.descriptions = descriptions;
		
		this.showFromRoll(index);
	},
	controls: function(action){
		if (action == 'show')
		{
			$(this.ref).find('.arrow_left, .previous, .arrow_right, .next').css('visibility', 'visible');
		}
		else
		{
			$(this.ref).find('.arrow_left, .previous, .arrow_right, .next').css('visibility', 'hidden');
		}
	},
	numbers: function(action){
		var num = $(this.ref).find('.numbers');
		if (action == 'show')
		{
			num.css('visibility', 'visible');
			num.find('.current').text(this.index+1);
			num.find('.total').text(this.roll.length);
		}
		else
		{
			num.css('visibility', 'hidden');
		}
	},
	showDescription: function(desc){
		$(this.ref).find('.description').html(desc);
	},
	showFromRoll: function(index){
		if (!this.roll) return;
		this.index = index;
		if (this.roll.length > 1)
		{
			this.controls('show');
			this.numbers('show');
		}
		else
		{
			this.controls('hide');
			this.numbers('hide');
		}
		this.load(this.roll[index]);
	},
	showVideo: function(src)
	{
		var self = this;
		this.showDescription('');
		$(this.ref).find('.image').html('<div></div>');
		var container = $(this.ref).find('.image div').get(0);
		this.animate(600, 375, function(){
			if (self.descriptions[self.index])
			{
				self.showDescription(self.descriptions[self.index]);
			}
		});
		setup_videoplayer(container, src);
	}
}

var prereg = {
	prepared: false,
	prepare: function(){
		$('#prereg').find('input, select').each(function(){
			$(this)
				.addClass('default:'+$(this).val())
				.focus(function(){
					var defaultValue = /default:(.+)$/i.exec(this.className);
					if (!defaultValue) return;
					
					defaultValue = defaultValue[1];
					if ($(this).val() == defaultValue)
						$(this).val('');
				})
				.blur(function(){
					var defaultValue = /default:(.+)$/i.exec(this.className);
					if (!defaultValue) return;
					
					defaultValue = defaultValue[1];
					if (!$(this).val())
						$(this).val(defaultValue);
				});
		});
		
		var self = this;
		$('#prereg input').keyup(function(event){
			if (event.keyCode == 13)
			{
				self.submit();
			}
		});
		
		$('#prereg .submit').click(function(){ self.submit(); });
		$('#prereg .close').click(function(){ self.close(); });
		
		$('#prereg').css('display', 'block');
		
		this.prepared = true;
	},
	close: function(){
		$('#prereg').css('display', 'none');
	},
	show: function(){
		if (this.prepared == false)
		{
			this.prepare();
		}
		var pos_left = ($(document).width()-$('#prereg').width())/2;
		$('#prereg').css({ display: 'block', left: pos_left+'px' });
		positionMiddle('#prereg');
	},
	showMessage: function(message){
		$('#login>.h2').html($('#prereg>h2').html());
		$('#login .content').html('<div class="message_container">' + message + '</div>');
	},
	submit: function(){
		var error = false;
		var alertField;
		
		$('#prereg .required').each(function(){
			var defaultValue = new RegExp('default:(.+)$', 'i').exec(this.className);
			if (defaultValue) defaultValue = defaultValue[1];
			
			if (!this.value || this.value == defaultValue)
			{
				if (this.title && !alertField)
				{
					alertField = this;
				}
				error = true;
			}
		});
		
		if (error == true)
		{
			if (alertField)
			{
				alertField.focus();
				alert(alertField.title);
			}
			return false;
		}
		
		var self 			= this;
		var firstname 		= $('#prereg input[name="firstname"]').val();
		var lastname 		= $('#prereg input[name="lastname"]').val();
		var email 			= $('#prereg input[name="email"]').val();
		
		var referer 		= $('#doLogin input[name="referer"]').val();
		var referer_info 	= $('#doLogin input[name="referer_info"]').val();

		$.post(global_url + 'ajax/prereg/create', {
			firstname: firstname,
			lastname: lastname,
			email: email,
			referer: referer,
			referer_info: referer_info
		}, function(response){
			if (!response.error)
			{
				self.showMessage(response.message);
			}
			else
			{
				alert(response.message);
			}
		}, 'json');
	}
}

var login = {
	prepared: false,
	prepare: function(){
		prereg.prepare();

		$('#login input.replacement')
			.each(function(){
				var rfor = this.name.replace('_replacement', '');
				this._for = $('#login input[name="' + rfor + '"]').get(0);
				this._for._replacement = this;
				$(this._for).blur(function(){
					if (!this.value)
					{
						$(this._replacement).css('display', 'block');
						$(this).css('display', 'none');
						$(this._replacement).blur();
					}
				});
			})
			.focus(function(){
				$(this._for).css('display', 'block');
				$(this).css('display', 'none');
				this._for.focus();
			});

		$('#login').find('input, select').each(function(){
			$(this)
				.addClass('default:'+$(this).val())
				.focus(function(){
					var defaultValue = /default:(.+)$/i.exec(this.className);
					if (!defaultValue) return;
					
					defaultValue = defaultValue[1];
					if ($(this).val() == defaultValue)
						$(this).val('');
				})
				.blur(function(){
					var defaultValue = /default:(.+)$/i.exec(this.className);
					if (!defaultValue) return;
					
					defaultValue = defaultValue[1];
					if (!$(this).val())
						$(this).val(defaultValue);
				});
		});
		
		var self = this;
		
		$('#login .close').click(function(){
			login.close();
		});
		
		$('#doLogin .submit').click(function(){
			$('#doLogin form').submit();
		});
		
		$('#doLogin input').keyup(function(event){
			if (event.keyCode == 13)
			{
				$('#doLogin form').submit();
			}
		});
		
		$('#forgotLogin .submit').click(function(){
			$('#forgotLogin form').submit();
		});
		
		$('#forgotLogin input').keyup(function(event){
			if (event.keyCode == 13)
			{
				$('#forgotLogin form').submit();
			}
		});
		
		$('#forgotLogin').css('display', 'none');
		this.prepared = true;
	},
	refererObj: null,
	close: function(){
		$('#login').css('display', 'none');
		if (this.refererObj)
		{
			$.post(global_url + 'ajax/log/close/', {
				referer: this.refererObj.referer,
				referer_info: this.refererObj.referer_info
			});
		}
	},
	show: function(centerAlign, message, refererObj, hideprereg){
		if (!this.prepared)
		{
			this.prepare();
		}
		
		this.refererObj = refererObj;
		
		if (message)
		{
			$('#login .message')
				.css('display', 'block')
				.find('.message_container')
				.html(message);
		}
		else
		{
			$('#login .message').css('display', 'none');
		}
		
		if (refererObj && refererObj.referer)
		{
			var $doLogin = $('#doLogin');
			$doLogin.find('input[name="referer"]').val(refererObj.referer);
			if (refererObj.referer_info)
			{
				$doLogin.find('input[name="referer_info"]').val(refererObj.referer_info);
			}
			
			$.post(global_url + 'ajax/log/open/', {
				referer: 		refererObj.referer,
				referer_info: 	refererObj.referer_info
			});
		}
		
		$('#doLogin').css('display', 'block');
		$('#forgotLogin').css('display', 'none');
		
		var pos_left = Math.round(($(document).width()-$('#login').width())/2);
		if (!centerAlign)
		{
			$('#login').css({ top: '170px' });
			pos_left += 100;
		}
		else
		{
			positionMiddle('#login');
		}
		$('#login').css({ display: 'block', left: pos_left+'px' });
		
		if (hideprereg)
		{
			$('#prereg').hide();
		}
		else
		{
			$('#prereg').show();
		}
		
		
	},
	forgotLogin: function(){
		$('#doLogin').css('display', 'none');
		$('#forgotLogin').css('display', 'block');
	}
}

function returnFalse()
{
	return false;
}

function wallNavigate(page)
{
	if (page !== false)
	{
		var path = location.pathname.replace(new RegExp('^/', ''), '').split('/');
		path.splice(2);
		location.href = global_url + path.join('/') + '/' + page + '#wall';
	}
}

function uniqueId()
{
	var chars = 'abcdefghijklmnopqrstuvwxyz';
	var str = '';
	for (var i = 0; i < 10; i++)
	{
		str = str + chars.substr(Math.floor(Math.random()*chars.length), 1);
	}
	return str;
}

function get_image(url, w, h)
{
	return server_image + 'image.resize.php?lightbox=1&image=' + escape(url) + '&w=' + w + '&h=' + h;
}

function get_image_crop(server, url, w, h)
{
	return server + 'image.crop.php?image=' + escape(url) + '&w=' + w + '&h=' + h;
}

function get_image_zoom(url, z)
{
	return server_image + 'image.zoom.php?image=' + escape(url) + '&z=' + z;
}

function setup_videoplayer(container, video)
{
	if (!container.id)
	{
		var container_id;
		do
		{
			container_id = uniqueId();
		}
		while(document.getElementById(container_id));
		container.id = container_id;
	}
	
	var flashvars 	= { video: server_video + video };
	var params		= { wmode: 'transparent' };
	swfobject.embedSWF(global_url + 'image/videoplayer.swf', container_id, '600', '375', "9.0.124", global_url + 'image/expressInstall.swf', flashvars, params);
}

function maxsize(elm, size)
{
	if (elm.value.length > size)
	{
		elm.value = elm.value.substr(0, size);
	}
}

function positionMiddle(elm, factor)
{
	factor = factor || 0;
	$(elm).css('top', ($(window).height()-$(elm).height())/2+$(window).scrollTop()+factor);
}

/*
 * Cookie functions
 */
 
function setcookie(name, value, expires, path, domain, secure) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *     example 1: setcookie('author_name', 'Kevin van Zonneveld');
    // *     returns 1: true
 
    expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
    var r = [name + "=" + escape(value)], s, i;
    for(i in s = {expires: expires, path: path, domain: domain}){
        s[i] && r.push(i + "=" + s[i]);
    }
    return secure && r.push("secure"), document.cookie = r.join(";"), true;
}

function getcookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1)
		{ 
			c_start = c_start + c_name.length+1; 
			c_end	= document.cookie.indexOf(";", c_start);

			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		} 
	}
	return "";
}

function birth_to_age(birth)
{
	var birth = {
		y: birth.getFullYear(),
		m: (birth.getMonth()+1),
		d: birth.getDate()
	}
	
	var todayDate = new Date();
	var today = {
		d:	todayDate.getDate(),
		m:	(todayDate.getMonth()+1),
		y:	todayDate.getFullYear()
	}
	
	var age = today.y - birth.y;	
	if (birth.m > today.m || birth.m == today.m && birth.d > today.d)
		age--;

	return age;
}

function actionOnLogin(action, info)
{
	var expire = new Date();
	expire.setDate(expire.getDate()+1);
	setcookie('actionOnLogin', action+';'+info, expire, '/');
}

function toggleMsn()
{
	$submsn = $('#msn .submsn');
	
	if ($submsn.height() > 0) height = { from: 74, to: 0 };
	else height = { from: 0, to: 74 };
	
	$submsn
		.css('height', height.from + 'px')
		.animate({
			height: height.to + 'px'
		}, {
			duration: 200
		});
}


var party = {
	prepared: false,
	popup: function()
	{
		hideInteractions();
		
		if (!this.prepared)
		{
			$('#deleteParty .submit').click(function(){ party.submit(); });
			$('#deleteParty .close').click(function(){ party.close(); });
			this.prepared = true;
		}
		positionMiddle('#deleteParty', -($('#page').offset().top));
		$('#deleteParty').css('display', 'block');
	},
	close: function()
	{
		$('#deleteParty').css('display', 'none');
	},
	submit: function()
	{
		$('#deleteParty form').submit();
	}
};