//messages

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function fbs_click(u, t) {
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
} 

var $imTimeout;
var imInited = false;
function showInlineMessage($message, $type, $right, $time, $callback)
{
	if (!imInited){
		initMessages();
		imInited = true;
	}
	
	if ($type == 'err'){
		c = $("#inlineMessages .err");
	} else {
		c = $("#inlineMessages .not");
		if ($.cookie('ignallguidlines')){
			return;
		}
	}
	clearTimeout($imTimeout);
	c.find("div.right").html($right);
	c.find("div.left").html($message);
	
	if (typeof $message == 'object'){
		c.find("div.left").html($message);
		$message.show();
	} else {
		c.find("div.left").html($message);
	}
	
	if (c.css("display") == 'none'){
		c.slideDown(200);
	}
	c.find("a.close").click(_closeInlineMessage);
	if (c.find("a.ignore_all").length == 1){
		c.find("a.ignore_all").click(_ignoreAllGuidlines);
	}
	if (parseInt($time) > 0){
		$imTimeout = setTimeout("hideInlineMessage()",$time);
	}
	if ($(window).scrollTop() > $("#inlineMessages").position().top){
		$('html').animate({scrollTop: $("#inlineMessages").position().top}, 300);
	}
	
	if (typeof $callback == 'function'){
		$callback(im);
	}
}
function _ignoreAllGuidlines(){
	$.cookie('ignallguidlines', true, { expires: 10*365, path: '/' });
	hideInlineMessage($(this).parent().parent().parent().attr("class"), true);
}
function _closeInlineMessage(){
	hideInlineMessage($(this).parent().parent().parent().attr("class"), true);
}

function initMessages(){
	if ($("#inlineMessages").length >= 1){
		im = $("#inlineMessages"); 
	} else {
		im = $("<div />").attr({id: 'inlineMessages'});
		$("#master").before(im);
	}
	
	cont = $("<div />").addClass("cont");
	cont.append($("<div />").addClass("left"));
	cont.append($("<div />").addClass("right"));
	cont.append($("<br />").addClass("clear"));
	contErr = cont.clone();
	not = $("<div />").addClass("not").append(cont);
	err = $("<div />").addClass("err").append(contErr);
	im.html("");
	im.append(not).append(err);
}

function hideInlineMessage(t,userClicked)
{
	if (t && t == 'not') {
		if (typeof onGuidlineClose == 'function'){
			r = onGuidlineClose($("#inlineMessages .not"), userClicked);
			if (r == true){
				$("#inlineMessages .not").slideUp(200);
			}
		} else {
			$("#inlineMessages .not").slideUp(200);
		}
	} else {
		if (typeof onNoticeClose == 'function'){
			r = onNoticeClose($("#inlineMessages .not"), userClicked);
			if (r == true){
				$("#inlineMessages .not").slideUp(200);
			}
		} else {
			$("#inlineMessages .err").slideUp(200);
		}
	}
}
function hideGuidline()
{
	hideInlineMessage('not');
}
function showNotice(message, timeout, callback)
{
	showErrorMessage(message, timeout, callback);
}
function showGuidline(message, timeout, callback)
{
	showMessage(message, timeout, callback);
}
function hideNotice()
{
	hideInlineMessage('err');
}
function hideAllMessages()
{
	hideInlineMessage('not');
	hideInlineMessage('err');
}
function showErrorMessage(message, timeout, callback)
{
	right = $("<a>").addClass("close").text("Dismiss").attr({href: '#'});
	showInlineMessage(message, 'err', right, timeout, callback);
}

function showMessage(message, timeout, callback)
{
	//right = '<a href="#" class="close">Dismiss</a> <span style="color: #D2D2D2">|</span> <a href="#" class="ignore_all">Ignore all</a>';
	right = $("<a>").addClass("close").text("Dismiss").attr({href: '#'});
	showInlineMessage(message, 'not', right, timeout, callback);
}


// end messages



$(document).ready(function(){
	$.ajaxSetup({
		url: "/ajax/index.php",
		global: false,
		type: "get",
		dataType: "json"
	});
});

function error(msg, timeout)
{
	alert(msg);
}

function notice(notice, timeout)
{
	alert(notice);
}

function UA_onLogout(){
	$.ajax({
		data: {page: 'logout'},
		success: function(d) {
			LOGGED = false;
			if (typeof REQUIRE_LOGGED_IN != 'undefined' && REQUIRE_LOGGED_IN){
				location.href = '/';
			}
		}
	});
	if (typeof(UA_onLogout2) == 'function') {
		UA_onLogout2();
	}
}

UAjustRegistered = false;
function UA_onRegister(user)
{
	UAjustRegistered = true;
}

function UA_onRegisterContinue()
{
	if (LOGGED == true){
		if (goToPageAfterLogin != ''){
			location.href = goToPageAfterLogin; 
		}
	} else {
		location.href = '/';
	}
}

function UA_onLogin(sId){
	$.ajax({
		data: {page: 'login', sessionId: sId},
		success: function(){
			LOGGED = true;
			if (goToPageAfterLogin != '' && !UAjustRegistered)
			{
				location.href = goToPageAfterLogin;
			}
			if (typeof(UA_onLogin2) == 'function') {
				UA_onLogin2();
			}
		}
	});
}


function doActionOnBuyPoints()
{
	$.userApi.buyPoints();
}

preloadbuttons = {};
function buttonToPreloader(elem, type, name)
{
	if (elem.hasClass("ui-button")){
		elem.addClass("ui-button-preloader");
	} else {
		elem.addClass("buttonpreloader");
	}
	if (!name){
		name = 'default';
	}
	if (typeof type == "undefined" || type == ""){
		type = "blue";
	}
	
	loader = getMiniLoader(type);
	loader.css({'position': 'absolute', 'margin': '-8px auto auto -8px', 'left': '50%', 'top':'50%'});
	elPos = elem.position();
	
	var outerWidth = elem.outerWidth();
	
	elem.addClass('ua-b-' + type + '-active');
	if (elem.is('input')) {
		elem.data('value', elem.attr('value'));
		elem[0].setAttribute('type', 'button');
		elem[0].setAttribute('value', '');
	} else {
		elem.data('html', elem.html());
		elem.html('');
	}
	
	if (elem.hasClass("ui-button")){
		elem.css('cssText', 'width:'+outerWidth+'px !important');
	}
	
	loadercont = $("<div />").css({
		'position': 'absolute',
		'left': elPos.left + 'px',
		'top': elPos.top + 'px',
		'width': outerWidth,
		'height': elem.innerHeight(),
		'margin-left': elem.css('margin-left'),
		'margin-top': elem.css('margin-top')
	}).html(loader);
	
	preloadbuttons[name] = loadercont;
	elem.after(preloadbuttons[name]);
}
tmpPreload = new Array();
function buttonPreload(type)
{
	if (typeof type == "undefined" || type == ""){
		type = "blue";
	}
	if (tmpPreload[type]){
		return;
	}
	tmpPreload[type] =  new Image(16, 16);
	tmpPreload[type].src = "/images/loader_mini_" + type + ".gif";
}
function clearPreloader(elem, name)
{
	if (!name){
		name = 'default';
	}
	
	if (elem.hasClass("ui-button")){
		elem.removeClass("ui-button-preloader");
	} else {
		elem.removeClass("buttonpreloader");
	}
	
	if (!preloadbuttons[name]){
		return;
	}
	preloadbuttons[name].remove();
}

function getMiniLoader(type)
{
	if (typeof type == "undefined"){
		type = "";
	} else {
		type = "_" + type;
	}
	elem = $("<img />").attr({src: "/images/loader_mini" + type + ".gif", width: "16", height: "16"});
	return elem;
}

function doActionOnStartSubscription()
{
	doActionOnBuyPoints();
}
