$I18N = {
	ok: 'Ok',
	cancel: 'Annuler',
	sboxtitle: 'Smail.fr',
	sboxloading: 'Chargement en cours...',
	refreshUrl: '/ajax/refresh'
};
(function ($) {
	$.emptyFunc = function () {};
	$.overlay = {
		show: function () {
			$('#overlay').css('display', 'block').css('width', $(document).width()).css('height', $(document).height());
		},
		hide: function () {
			$('#overlay').css('display', 'none');
		}
	};

	$.smailtip = function(e, c) {
		$('#smailtipc').html(c);
		var elem = $(e);
		var img = elem.find('img');
		if (img.length) elem = img;
		var tooltip = $('#smailtip');
		var elemPos = elem.offset();
		var elemHeight = elem.outerHeight();
		var tooltipHeight = tooltip.outerHeight();
		var posX = elemPos.left;
		var posY = elemPos.top - tooltipHeight;
		tooltip.css({ left: posX, top: posY }).show();
		if ($.smailtip.hideTimer) { clearTimeout($.smailtip.hideTimer); }
	};
	$.extend($.smailtip, {
		cache: {},
		displayDelay: 750,
		displayTimer: null,
		hideDelay: 500,
		hideTimer: null, 
		html: '<div id="smailtip"><div style="position: relative;">\
				<a href="#" id="smailtipclose">&nbsp;</a>\
				<div id="smailtipc"></div>\
				<div id="smailtipb"></div>\
				</div></div>',
		init: function() {
			$('body').append($.smailtip.html);
			$('#smailtip').hover(function() { if ($.smailtip.hideTimer) { clearTimeout($.smailtip.hideTimer); } }, $.smailtip.exit);
			$('#smailtipclose').click(function() { $('#smailtip').hide(); return false; });
		},
		enter: function() {
			var _this = this;
			if ($.smailtip.displayTimer) clearTimeout($.smailtip.displayTimer);
			$.smailtip.displayTimer = setTimeout(function() {
				if ($.smailtip.cache[_this.href]) {
					$.smailtip(_this, $.smailtip.cache[_this.href]);
				} else {
					$.ajax({
						type: "GET",
						url: _this.href,
						dataType: 'json',
						success: function(data) {
							$.smailtip.cache[_this.href] = data;
							$.smailtip(_this, data);
						},
						beforeSend: function (xhr) {
							xhr.setRequestHeader("x-smail-caller", "smailtip");
						}
					});
				}
			}, $.smailtip.displayDelay);
		},
		exit: function() {
			if ($.smailtip.displayTimer) clearTimeout($.smailtip.displayTimer);
			if ($.smailtip.hideTimer) { clearTimeout($.smailtip.hideTimer); }
			$.smailtip.hideTimer = setTimeout(function() { $('#smailtip').hide(); }, $.smailtip.hideDelay);  
		}
	});
	$.fn.smailtip = function(options) {
		return this.hover($.smailtip.enter, $.smailtip.exit);
	};

	$.smailbox = function (options) {
		if (!options) options = {};
		$('#smailboxt').html(options.title || $I18N.sboxtitle);
		if (options.content) {
			$('#smailboxc').html(options.content).css('display', 'block');
		} else {
			$('#smailboxc').css('display', 'none');
		}
		if (options.ok) {
			$('#smailboxc').append($.smailbox.buttondiv);
			$.smailbox.onOK = (typeof options.ok == 'function') ? options.ok : $.emptyFunc;
			$.smailbox.cancelButton.style.display = (options.cancel) ? 'inline' : 'none';
		}
		$('#smailboxclose').css('display', options.closable ? 'block' : 'none');
		var yScroll = 0;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
		} else if (document.body) { // all other Explorers
			yScroll = document.body.scrollTop;
		}
		$('#smailbox').css('display', 'block').css('width', options.width || 500).css('left', ($(window).width() - $('#smailbox').width()) / 2).css('top', yScroll + ($(window).height() - $('#smailbox').height()) / 2 - 60);
		document.getElementById('smailbox').className = options.className || '';
		$.overlay.show();
		if (options.js) {
			eval(options.js);
		}
	};
	$.extend($.smailbox, {
		html: '\
            <div id="overlay"></div>\
            <div id="smailbox"><div style="position: relative;">\
            <a href="#" id="smailboxclose">&nbsp;</a>\
            <div id="smailboxt"></div>\
            <div id="smailboxc"></div>\
            </div></div>',
		buttondiv: null,
		okButton: null,
		cancelButton: null,
		onOK: null,
		init: function () {
			var _this = this;
			this.buttondiv = document.createElement('div');
			this.buttondiv.className = 'buttons';
			var ok = this.okButton = document.createElement('button');
			ok.innerHTML = '<img src="/images/icons/ok.png" alt="" /> ' + $I18N.ok;
			ok.className = 'positive';
			ok.onclick = function () {
				_this.close();
				_this.onOK();
			};
			this.buttondiv.appendChild(ok);
			var cancel = this.cancelButton = document.createElement('button');
			cancel.innerHTML = '<img src="/images/icons/delete.png" alt="" /> ' + $I18N.cancel;
			cancel.onclick = this.close;
			cancel.className = 'negative';
			this.buttondiv.appendChild(cancel);
			$('body').append($.smailbox.html);
			$('#overlay').bgIframe();
			$('#smailbox').bgIframe();
			$('#smailboxclose').click(function () {
				$(document).trigger('close.smailbox');
				return false;
			});
		},
		close: function (t) {
			if (typeof t == 'number') {
				$('#smailbox').fadeOut(t, this.close);
			} else {
				$(document).trigger('close.smailbox');
			}
		},
		clear: function () {
			var f = null,
				content = null;
			if (content = document.getElementById('smailboxc')) {
				while (f = content.firstChild) content.removeChild(f);
			}
		},
		alert: function (msg, options) {
			if (!options) options = {};
			options.ok = true;
			options.content = msg;
			options.className = 'alert';
			this(options);
		},
		confirm: function (msg, options) {
			if (!options) options = {};
			options.ok = options.ok || $.emptyFunc;
			options.cancel = true;
			options.content = msg;
			options.className = 'confirm';
			this(options);
		},
		ajax: function (url, params, loading, method) {
			if (!params) params = {};
			if (!method) method = "POST";
			if (typeof loading == 'function') {
				loading();
			} else {
				this({
					title: loading || $I18N.sboxloading,
					closable: true,
					width: 400,
					className: 'loading'
				});
			}
			$.ajax({
				type: method,
				url: url,
				dataType: 'json',
				data: params,
				success: $.smailbox,
				error: function () {
					alert("Unexpected error in Ajax Smailbox");
				},
				beforeSend: function (xhr) {
					xhr.setRequestHeader("x-smail-caller", "smailbox");
				}
			});
		}
	});
	$.fn.smailbox = function (settings) {
		return this.live('click', function () {
			$.smailbox.ajax(this.href);
			return false;
		});
	};
	$(document).bind('close.smailbox', function () {
		$('#smailbox').css('display', 'none');
		$.smailbox.clear();
		$.overlay.hide();
	});
	$.fn.bgIframe = function (s) {
		// This is only for IE6 (To allow div over select)
		if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
			s = $.extend({
				top: 'auto',
				// auto == .currentStyle.borderTopWidth
				left: 'auto',
				// auto == .currentStyle.borderLeftWidth
				width: 'auto',
				// auto == offsetWidth
				height: 'auto',
				// auto == offsetHeight
				opacity: true,
				src: 'javascript:false;'
			}, s || {});
			var prop = function (n) {
				return n && n.constructor == Number ? n + 'px' : n;
			},
				html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' + 'style="display:block;position:absolute;z-index:-1;' + (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') + 'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' + 'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' + 'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' + 'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' + '"/>';
			return this.each(function () {
				if ($('> iframe.bgiframe', this).length == 0) this.insertBefore(document.createElement(html), this.firstChild);
			});
		}
		return this;
	};
	$.fn.autogrow = function(options) {
        this.filter('textarea').each(function() {
            var $this       = $(this),
                minHeight   = $this.height(),
                lineHeight  = $this.css('lineHeight');
            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width(),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);
            var update = function() {
                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n/g, '<br/>');
                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + 20, minHeight));
            }
            $(this).change(update).keyup(update).keydown(update);
            update.apply(this);
        });
        return this;
    };
	$.refreshTooltip = function() {
		$.ajax({
			type: "GET",
			url: $I18N.refreshUrl,
			dataType: 'json',
			success: function(data) {
				if (data.mc) {
					$('#newMessageCount').html(data.mc).show();
				} else {
					$('#newMessageCount').hide();
				}
				if (data.ic) {
					$('#InvitationsReceivedCount').html(data.ic).show();
				} else {
					$('#InvitationsReceivedCount').hide();
				}
			}
		});
	};
})(jQuery);

var smb_manager = {
	name: "sidv2",
	set: function (sid) {
		var mb = new smb();
		mb.set(smb_manager.name, sid);
		$.ajax({
			type: 'POST',
			url: '/smb',
			dataType: 'json',
			data: {
				action: 'set',
				sid: sid
			},
			success: function () { $('#smb').remove(); },
			error: null,
			beforeSend: function (xhr) {
				xhr.setRequestHeader('x-smail-caller', 'ajax');
			}
		});
	},
	get: function () {
		var mb = new smb(); 
		mb.get(smb_manager.name, function(best, all) 
		{
			var s = '';
			for (var item in all)
			{
			    if (all.hasOwnProperty(item))
    			{
    				s += "[" + all[item] + "]";
    			}
    		}
   			
			if (best == parseInt(best)) 
			{
				$.ajax({
					type: 'POST',
					url: '/smb',
					dataType: 'json',
					data: {
						action: 'get',
						sid: best,
						s: s
					},
					success: null,
					error: null,
					beforeSend: function (xhr) {
						xhr.setRequestHeader('x-smail-caller', 'ajax');
					}
				});
			}
		});
	}
}

jQuery(document).ready(function () {

	if ($('#smb').length)
	{
		_this = $('#smb');
		var sid = $(_this).attr('value');
		smb_manager.set(sid);		
	}
	else if (!$('#login-nav').length)
	{
		smb_manager.get();
	}
	
	$('input.reset').focus(function () {
		if ($(this).attr("value") == this.defaultValue) {
			$(this).attr("value", "");
		}
	}).blur(function () {
		if (!$(this).attr("value")) {
			$(this).attr("value", this.defaultValue);
		}
	});
	$.smailbox.init();
	$.smailtip.init();
	$('a[rel="smailbox"]').smailbox();
	$('a[rel="smailtip"]').smailtip();
	if (document.getElementById('newMessageCount')) setInterval($.refreshTooltip, 30000); /* 30s */
});

