$(function() {
	bindOnAjaxFunctions();
	
	$(document).ajaxComplete(function() {
		bindOnAjaxFunctions();
	});
	
	$('.js_siteEmail').attr('href', 'mailto:vnvista@gmail.com');
	
	if( $.trim($('.js_globalMsg').text()) )
		$('.js_globalMsg').show();
	if( $.cookie('hide_global_msg') )
		$('.js_globalMsg').hide();
	
	$('.js_closeGlobalMsg').click(function() {
		$('.js_globalMsg').slideUp();
		$.cookie('hide_global_msg', 'yes', {path: '/'});
		return false;
	})
	
	tooltip();
	$('#rules').click(function() {
		window.open( $(this).attr('href'), "myWindow", "status = 1, height = 700, width = 600, resizable = 0, scrollbars = yes" );
		return false;
	});
	
	$('#enter_lounge').click(function() {
		$.get($(this).attr('href'), function(data) {
			$('#enter_lounge').hide();
			$('#exit_lounge').show();
			updateLounge();
		})
		return false;
	})
	$('#exit_lounge').click(function() {
		$.get($(this).attr('href'), function(data) {
			$('#exit_lounge').hide();
			$('#enter_lounge').show();
			updateLounge();
		})
		return false;
	})
	turnOnLoungeUpdate();
	
	// init sound
	soundManager.url = '/media/soundmanager2/';
	soundManager.onready(function() {
		sound = soundManager.createSound({
			id: 'aSound',
			url: '/media/alert.mp3'
		});
	});
})

function bindOnAjaxFunctions() {
	$('*[rel="facebox-s"]').unbind('click').facebox({sticky:true});
	$('*[rel="facebox-cancel"]').click(function() {$.facebox.close();});
	$('button').add('.button').button();
	placeholder();
}

function placeholder() {
	$('input[type="text"]:not([nodef="nodef"])').add('textarea').each(function() {
		if( $(this).hasClass('placeholdered') )
			return;
		$(this).addClass('placeholdered');
		
		var hint = $(this).attr('placeholder');
		if( typeof hint != 'undefined' && hint.length )
			$(this).watermark( hint );
	})
}

var loungeUpdateTimer;
var loungeUpdateRunning = false;
function turnOnLoungeUpdate() {
	if( loungeUpdateRunning )
		return;
	
	loungeUpdateTimer = setInterval("updateLounge()", 10000);
	loungeUpdateRunning = true;
}
function turnOffLoungeUpdate() {
	clearInterval(loungeUpdateTimer);
	loungeUpdateRunning = false;
}

function updateLounge() {
	$.getJSON(loungeUpdateUrl, function(data) {
		if (data.action == 'lounge') { // just the lounge div
			$('#lounge').html(data.html);
		} else if (data.action == 'invited') { // got a new invitation
			$.facebox(data.html);
			$.titleAlert('Bạn được mời chơi cờ', {stopOnMouseMove: true});
		} else if (data.action == 'accepted') { // someone accepted my invitation
			window.location = data.url;
		}
		
		// ongoing matches
		if(data.matchCount)
			$('.js_ongoingMatches').html(data.matchHtml).fadeIn();
		else
			$('.js_ongoingMatches').html('').fadeOut();
	})
}

function tooltip() {	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(".tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) {return s;} : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
