String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

var img_loading = new Image();
img_loading.src = 'images/loading.gif';
var LOADING = '<img src='+img_loading.src+' align=absmiddle>';
var SMALL_LOADING = '<img src="images/loading1.gif" align=absmiddle>';
var periodic_for_comment;
var periodic_for_duel_news;
var periodic_for_player_status;
var player_status_tab = 0;
var IE = document.all?true:false;
var tempX = 0;
var tempY = 0;
var context_info;

function changeDivSpanStatus(id,status){
	$(id).style.display = status;
}

function checkUserName(el){
	el.disabled=true;
    $('span_check_result').update("Checking...");
    
	var username = document.register_form.username.value;
	
	if(username==''||username.length<4){
		alert('Please Key in User Name. Minimum 4 characters.');
		$('span_check_result').update('');
		el.disabled=false;
		return;
	}
	new Ajax.Request('register.php?a=checkusername&username='+username,
	{
		onComplete: function(e) {
			$('span_check_result').update(e.responseText);
			el.disabled=false;
			//new Insertion.After(obj.parentNode.parentNode.parentNode, e.responseText);
			//$('r_'+m+'_'+qn), e.responseText);
			//obj.remove();
			//obj.src = 'ui/collapse.gif';
		}
	});
}

function checkEmail(el){
	el.disabled=true;
    $('span_check_email_result').update("Checking...");

	var email = document.register_form.email.value;

	if(email==''){
		alert('Please Key in Email.');
		$('span_check_email_result').update('');
		el.disabled=false;
		return;
	}

	if(email.indexOf('@')<=0||email.indexOf('@')==email.length-1){
        $('span_check_email_result').update('<font color=red>Failed</font>');
		el.disabled=false;
		return;
	}
	
	new Ajax.Request('register.php?a=checkemail&email='+email,
	{
		onComplete: function(e) {
			$('span_check_email_result').update(e.responseText);
			el.disabled=false;
		}
	});
}

function checkRegisterForm(){
    var username = document.register_form.username.value;
    var p1 = document.register_form.userpass.value;
    var p2 = document.register_form.userpass2.value;
    var email = document.register_form.email.value;
    
    if(username==''||username.length<4){
		alert('Please Key in User Name. Minimum 4 characters.');
		return false;
	}
	
	if(p1.length<6||(p1!=p2)){
		alert('Incorrect Password');
		return false;
	}
	
	if(email==''||email.indexOf('@')<=0||email.indexOf('@')==email.length-1){
		alert('Incorrect Email');
		return false;
	}
	
    return true;
}

function viewOrCloseMessage(id){
	if($('tbody_'+id).style.display=='none'){
        $('tbody_'+id).style.display='';
        $('span_label_'+id).update('Close');

		var obj = $('tbody_msg_list_'+id).getElementsByTagName('tr');
		if(obj[0].className=='message_0'){
			var url="profile.php?a=markasread&msg_id="+id;

            new Ajax.Request(url,
			{
				onComplete: function(e) {
					obj[0].className='message_1';
			        var num = $('span_unread_msg').innerHTML;
			        var num2 = int(num-1);
			        if(num2<=0){
						num2=0;
					}
			        $('span_unread_msg').update(num2);
				}
			});
			
      		/*new Ajax(url,{method:'post',onComplete:function(){
		        obj[0].className='message_1';
		        var num = $('span_unread_msg').innerHTML;
		        $('span_unread_msg').update(num-1);
		    }}).request();*/

		    /*
		    new Json.Remote(url, {
			onComplete: function(ret){
                obj[0].className='message_1';
		        var num = $('span_unread_msg').innerHTML;
		        $('span_unread_msg').update(num-1);
			},
			onFailed: function(err) {
				alert('Failed to send info to server');
			}}).send();*/
		}
	}else{
        $('tbody_'+id).style.display='none';
        $('span_label_'+id).update('view');
	}
}

function viewOrCloseMessage2(id){
	if($('tbody_'+id).style.display=='none'){
        $('tbody_'+id).style.display='';
        $('span_label_'+id).update('Close');
	}else{
        $('tbody_'+id).style.display='none';
        $('span_label_'+id).update('view');
	}
}

function forgotPassword(){
	var email=prompt('Please enter your email address, your password will send to your email address');
	if(email!=''){
	    if(email.indexOf('@')<=0||email.indexOf('@')==email.length-1){
			alert('Incorrect Email');
			return;
		}

	    var url = 'profile.php?a=reSendPassword&email='+email;
        new Ajax.Request(url,
		{
			onComplete: function(e) {
			    result = e.responseText;
			    if(result==1){
					alert('Your password was successfully sent to your email address.');
				}else{
					alert('Error: email address ( '+email+' ) not found in database.');
				}
			}
		});
	}
}

function changePassword(){
	if(confirm('This action will close this page, any unsave data will lost, do you want to continue?')){
        openpage('profile','changePassword');
	}
}

function checkChangePasswordForm(){
    var old_pass = document.change_password_form.old_pass.value;
	var pass1 = document.change_password_form.pass1.value;
	var pass2 = document.change_password_form.pass2.value;
	
	if(old_pass==''){
        alert('Current password cannot empty.');
		return false;
	}
	
	if(pass1==''){
		alert('Password cannot empty.');
		return false;
	}
	
	if(pass1.length<6){
		alert('New password minimum 6 characters');
		return false;
	}
	
	if(pass1!=pass2){
		alert('New password not match');
		return false;
	}
	
	return true;
}

function checkProfileForm(){
	var email = document.profile_form.email.value;
	
	if(email==''){
		alert('Please Key in Email.');
		return false;
	}

	if(email.indexOf('@')<=0||email.indexOf('@')==email.length-1){
        alert('Incorrect Email Address');
		return false;
	}
	
	return true;
}

function periodicUpdateMessage(){
	var url = 'index.php?a=load_unread_message_number&ajax=1';
	
    new Ajax.PeriodicalUpdater('span_unread_msg', url,
	  {
	    method: 'get',
	    frequency: 120
	  });
}

function openSubPage(filename,loc,container){
    new Ajax.Updater(container, filename+'.php?a='+loc,
	{
		method: 'get',
		onLoading: function(){
			$(container).update(SMALL_LOADING+' Loading...');
		},
		evalScripts: true,
		onComplete: function(){
			if(loc=='load_inbox'){
                $('span_msg_header').update('Inbox');
			}else if(loc=='load_sent_message'){
                $('span_msg_header').update('Sent Message');
			}else if(loc=='load_write_message_page'){
                $('span_msg_header').update('Write Message');
			}
		}
	});
}

function write_message(){
    new Ajax.Updater('div_content', 'profile.php?a=write_message',
	{
		method: 'get',
		parameters: context_info,
		onLoading: function(){
			$('div_content').update('<br>'+LOADING);
		},
		onComplete: function(){
            $('span_msg_header').update('Write Message');
		}
	});
}

function changeProfileMenuColor(el_name){
	var mtable = $('profile_side_link');
	var obj = mtable.getElementsByTagName('a');

	for(var i=0; i<obj.length; i++){
		if(obj[i].name!=el_name){
            obj[i].className = "li_m";
		}else{
            obj[i].className = "li_m_sel";
		}
	}
}

function checkWriteMessageForm(){
	var receiver_id = document.write_message_form['receiver'].value;
	var msg_title = document.write_message_form.message_title.value;
	var msg_content = document.write_message_form.content.value;
	
	if(!receiver_id){
		alert('Please search for user to send.');
		return false;
	}
	
	if(msg_title==''){
		alert('Title cannot be empty');
		return false;
	}
	
	if(msg_content==''){
		alert('Message Content cannot be empty');
		return false;
	}
	
	if(confirm('Click OK to send.')){
        return true;
	}else{
		return false;
	}
}

function postComment(el){
	el.disabled = true;
	
	var content = document.comment_form.content.value;
	
	if(content==''){
		alert('Cannot post empty message.');
		el.disabled = false;
		return;
	}
	
	var url = 'comment.php?a=post_new_comment';
	new Ajax.Updater('div_comment_content', url,
	{
		method: 'post',
		parameters: {comment: content},
		onLoading: function(){
			$('span_comment_post_loading').update('Posting your comment...Please wait...');
		},
		onComplete: function(){
		    document.comment_form.content.value = '';
		    $('span_comment_post_loading').update('');
            el.disabled = false;
		}
	});
}

function periodicRefreshCommentContent(){
    var url = 'comment.php?a=periodic_load_comment_content';

    periodic_for_comment = new Ajax.PeriodicalUpdater('div_comment_content', url,
	{
	    method: 'get',
	    frequency: 20
	});
}

function tab_activeMe(menu_id, tab_name){
	var obj = $(menu_id).getElementsByTagName('a');

	for(var i=0; i<obj.length; i++){
		if(obj[i].name!=tab_name){
			obj[i].className = 'tab_m';
		}else{
            obj[i].className = 'tab_m_sel';
		}
	}
}

function joinMatchRoom(room_id,seat_num){
	loc = 'join_match_room&room_id='+room_id+'&seat_num='+seat_num;
    openSubPage('match',loc,'div_match_content');
}

function unSeatMatchRoom(room_id,seat_num){
    loc = 'exit_match_room&room_id='+room_id+'&seat_num='+seat_num;
    openSubPage('match',loc,'div_match_content');
}

function duel_challenge(){
	$('tmsg').update(SMALL_LOADING+' Processing ...');
	new Ajax.Request('point_system.php?a=duel_challenge',
	{
	    method: 'get',
	    parameters: context_info,
		onComplete:function(e){
			alert(e.responseText);
			$('tmsg').update('');
		}
	});
}

function periodicLoadPointSystemNews(){
	periodic_for_duel_news = new Ajax.PeriodicalUpdater('div_point_system_news', 'point_system.php',
	{
	    method: 'get',
	    parameters:{
			a: 'getNews'
		},
	    frequency: 30
	});
}

function periodicLoadPointSystemPlayerStatus(tab){
	if(tab==''){
		player_status_tab = 0;
	}else{
        player_status_tab = tab;
	}
	
	try{
        periodic_for_player_status.stop();
	}catch(ex){

	}

	
    periodic_for_player_status = new Ajax.PeriodicalUpdater('div_point_system_player_status', 'point_system.php',
	{
	    method: 'get',
	    parameters:{
			a: 'load_challenge',
			tab: player_status_tab
		},
		onLoading:function(){
            $('tmsg').update(SMALL_LOADING+' Processing ...');
		},
		onSuccess:function(e){
            $('tmsg').update('');
		},
	    frequency: 30,
	    evalScripts: true
	});
}

function acceptDuelChallenge(id,accept,ele){
	if(!confirm('Click OK to confirm')){
		return;
	}
	$(ele).disabled = true;
	var sb = $(ele).siblings();
	for(var i=0; i<sb.length; i++){
		sb[i].disabled = true;
	}
	
	$('tmsg').update(SMALL_LOADING+' Processing ...');
	new Ajax.Request('point_system.php',
	{
	    method: 'post',
	    parameters:{
			a: 'accept_challenge',
			id: id,
			accept: accept
		},
		onComplete:function(e){
			if(e.responseText.indexOf('Error: ')>=0){
				alert(e.responseText);
				$('tmsg').update('');
				$(ele).disabled = false;
				for(var i=0; i<sb.length; i++){
					sb[i].disabled = false;
				}
				return;
			}
			
			$('div_point_system_player_status').update(e.responseText);
			$('tmsg').update('');
		}
	});
}

function confirmDuelResult(id,result,ele){
    if(!confirm('You choose you have '+result+' this match, the point will given to winner once your opponent confirm the result')){
		return;
	}

    $('tmsg').update(SMALL_LOADING+' Processing ...');
    $(ele).disabled = true;
	var sb = $(ele).siblings();
	for(var i=0; i<sb.length; i++){
		sb[i].disabled = true;
	}
	
    
	new Ajax.Request('point_system.php',
	{
	    method: 'post',
	    parameters:{
			a: 'confirmDuelResult',
			id: id,
			result: result
		},
		onComplete:function(e){
			if(e.responseText.indexOf('Error: ')>=0){
				alert(e.responseText);
				$('tmsg').update('');
				$(ele).disabled = false;
				for(var i=0; i<sb.length; i++){
					sb[i].disabled = false;
				}
				return;
			}

			$('div_point_system_player_status').update(e.responseText);
			$('tmsg').update('');
		}
	});
}

function rewrite_duelResult(id,status,ele){
	if(status==0){
        if(!confirm('Are you sure this result is wrong ? Click OK to choose again')){
			return;
		}
	}else{
        if(!confirm('Are you sure confirm this result?')){
			return;
		}
	}
	$(ele).disabled = true;
	var sb = $(ele).siblings();
	for(var i=0; i<sb.length; i++){
		sb[i].disabled = true;
	}
	
	$('tmsg').update(SMALL_LOADING+' Processing ...');
	
	new Ajax.Request('point_system.php',
	{
	    method: 'post',
	    parameters:{
			a: 'rewrite_duelResult',
			id: id,
			status: status
		},
		onComplete:function(e){
			if(e.responseText.indexOf('Error: ')>=0){
				alert(e.responseText);
				$('tmsg').update('');
				$(ele).disabled = false;
				for(var i=0; i<sb.length; i++){
					sb[i].disabled = false;
				}
				return;
			}

			$('div_point_system_player_status').update(e.responseText);
			$('tmsg').update('');
		}
	});
}

function showLadderRanking(){
	var season = document.form_point_system_player_ranking.season.value;
    openSubPage('point_system','refresh_player_ranking&season='+season,'div_point_system_player_ranking');
}

// get Mouse XY
function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		if (document.documentElement)
		{
			tempX = event.clientX + document.documentElement.scrollLeft;
			tempY = event.clientY + document.documentElement.scrollTop;
		}
		else
		{
			tempX = event.clientX + document.body.scrollLeft;
			tempY = event.clientY + document.body.scrollTop;
		}
	}
	else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
  
	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}
	return true;
}

document.onmousemove = getMouseXY;



function show_context_menu(div_id)
{
	//context_info = { test: 'test'};
	
	//$(div_id).style.left = ((document.body.scrollLeft)+tempX) + 'px';
	//$(div_id).style.top = ((document.body.scrollTop)+tempY) + 'px';
	
	if (IE) { // grab the x-y pos.s if browser is IE
   		$(div_id).style.left = ((document.body.scrollLeft)+tempX) + 'px';
		$(div_id).style.top = ((document.body.scrollTop)+tempY) + 'px';
  } else {  // grab the x-y pos.s if browser is NS
    	$(div_id).style.left = (tempX) + 'px';
		$(div_id).style.top = (tempY) + 'px';
  }

	$(div_id).show();

	$('ul_menu').onmouseout = function() {
		context_info.timer = setTimeout('hide_context_menu(\''+div_id+'\')', 100);
	}

	$('ul_menu').onmousemove = function() {
		if (context_info.timer!=undefined) clearTimeout(context_info.timer);
		context_info.timer = undefined;
	}
	return false;
}

function hide_context_menu(div_id)
{
	try{
        $('ul_menu').onmouseout = undefined;
		$('ul_menu').onmousemove = undefined;
	}catch(ex){

	}

	$(div_id).hide();
}

function user_context_info(user_u,user_id){
	$('div_user_name').update(user_u);
	
	// avatar
	var avatar_path = user_avatar[user_id];
	if(typeof(avatar_path)!='undefined'){
		$('div_avatar_path').update('<img src="'+avatar_path+'">');
	}else   $('div_avatar_path').update('');
	
	// qualified option
	if(can_qualified_duelist){
        var already_qualified = user_qualified[user_id];
        if(already_qualified)	$('li_qualifed_player').hide();
        else    $('li_qualifed_player').show();
	}
	
	
    context_info = {
		user_id: user_id,
        receiver: user_id,
        username: user_u
	};
	
	if(user_id==my_id){
		$('ul_menu').hide();
	}else   $('ul_menu').show();
}

function replyMessageContentInfo(user_id){
    context_info = {
        receiver: user_id
	};
}


function showTournament(){
	var tournament_code = document.tournament_list.tournament_code.value;
	
    openpage('tournament','index&tournament_code='+tournament_code);
}

function setTournamentResult(tournament_code,stage_num,node_num,place_num,user_id,result,stage_status){
	if(!confirm('Are you sure ?')){
		return;
	}
	
	$('tmsg').update(SMALL_LOADING+' Processing ...');
	new Ajax.Request('tournament.php',
	{
	    method: 'post',
	    parameters:{
			a: 'setTournamentResult',
			tournament_code: tournament_code,
			stage_num: stage_num,
			node_num: node_num,
			place_num: place_num,
			user_id: user_id,
			result: result,
			stage_status: stage_status
		},
		onComplete:function(e){
			if(e.responseText.indexOf('Error: ')>=0){
				alert(e.responseText);
				$('tmsg').update('');
				return;
			}

			$('div_content').update(e.responseText);
			$('tmsg').update('');
		}
	});
}

function joinTournament(tournament_code){
    if(!confirm('Are you sure to participate this tournament ? Once confirm system will randomly allocate a place to you.')){
		return;
	}
	
	$('tmsg').update(SMALL_LOADING+' Processing ...');
	new Ajax.Request('tournament.php',
	{
	    method: 'post',
	    parameters:{
			a: 'joinTournament',
			tournament_code: tournament_code
		},
		onComplete:function(e){
			if(e.responseText.indexOf('Error: ')>=0){
				alert(e.responseText);
				$('tmsg').update('');
				return;
			}

			$('div_content').update(e.responseText);
			$('tmsg').update('');
		}
	});
}


function deleteMessage(msg_id,view_type){
	openSubPage('profile','deleteMessage&msg_id='+msg_id+'&view_type='+view_type,'div_message_content');
}

function int(expr)
{
	expr = new String(expr).replace(/,/g, '');
	var i = parseInt(expr);
	if (isNaN(i))
	    return 0;
	else
	    return i;
}

function mi(obj,z) {
	if (obj.value=='') return;

	obj.value = int(obj.value);
	if (z == 1 && obj.value==0) obj.value = '';
}

function miz(obj) {
	mi(obj,1);
}
function showClassRank(desc,point,display){
	var div_id = 'class_rank_desc';
    if (IE) { // grab the x-y pos.s if browser is IE
   		$(div_id).style.left = ((document.body.scrollLeft)+tempX+5) + 'px';
		$(div_id).style.top = ((document.body.scrollTop)+tempY) + 'px';
  } else {  // grab the x-y pos.s if browser is NS
    	$(div_id).style.left = (tempX)+5 + 'px';
		$(div_id).style.top = (tempY) + 'px';
  }

	$('class_header').update(desc);
	var minp = parseInt(point)+1;
	if(point==0)    nextp = '1300';
	else var nextp = parseInt(point)+100;
	$('class_desc').update(minp+' - '+nextp);
	$(div_id).style.display = display;
}

function center_div(div){
    var point = window.size();
	var offset = window.center();

    $(div).style.top = int(offset.y + (point.height-int($(div).style.height))/2)+'px';
	$(div).style.left = int(offset.x + (point.width-int($(div).style.width))/2)+'px';
}

function curtain(v)
{
	if (v)
	{
		// create a top top level div
		$('curtain').style.width = document.body.scrollWidth+'px';
		$('curtain').style.height = document.body.scrollHeight+'px';
		$('curtain').show();
		//new Effect.Opacity($('curtain'),{duration:0.3, to:0.8});
		Effect.Appear('curtain',{speed:0.2, to:0.8, afterFinishInternal:function(){}})
	}
	else
	{
		new Effect.Opacity($('curtain'),{duration:0.2, to:0,
    		afterFinish: function() { $('curtain').hide(); }
		});
	}
}

function default_curtain_clicked(){
    new Effect.Opacity($('curtain'),{duration:0.2, to:0,
    	afterFinish: function() { $('curtain').hide(); }
	});
		
    try{
        curtain_clicked();
	}catch(ex){
		// nop
	}
}

window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

window.center = function()
{
	var offsetX = 0;
	var offsetY = 0;

	//IE
	if(!window.pageYOffset)
	{
		//strict mode
		if(!(document.documentElement.scrollTop == 0))
		{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else
		{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else
	{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}

	return{x:offsetX,y:offsetY};
}

function fade_in(div){
    Effect.Appear(div,{speed:0.05, afterFinishInternal:function(){}});
}

function fade_out(div){
    Effect.Fade(div,{speed:0.05, afterFinishInternal:function(){
		$(div).hide();
	}});
}

function active_tab(menu_id, ele){
	var tab = $(menu_id).select('a.tab_m');
	for(var i=0; i<tab.length; i++){
		$(tab[i]).removeClassName('tab_m_sel');
	}
	$(ele).addClassName('tab_m_sel');
}

function login_as(){
	var u = prompt('Please enter username');
	if(u){
	    u = u.trim();
	    if(u=='')   return;
		document.f_login_as['u'].value = u;
		document.f_login_as.submit();
	}
}
