/*
 * jQuery replaceText - v1.1 - 11/21/2009
 * http://benalman.com/projects/jquery-replacetext-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);

(function($){
	$.fn.capsulePreview = function(options){
		options = $.extend({  
                         'xOffset' : 30,
						 'yOffset' : 30
                    },options || {});
			var $this = $(this); 
			$this.each(function(i, obj){				
				$(obj).mouseenter(function(e){
					$("#lightbox").remove();
					var capsshow = $(this).find('.capsshow').html();
					
					if($(this).find('.capsshow').length != 0 ){
						
						$("body").append('<div id="lightbox"><div class="capsshow">'+capsshow+'</div></div>');								 
						
						var bWidth = $("body").width();
						var restWidth = bWidth - e.pageX;
						var lbWitdh = $("#lightbox").outerWidth();
	
						if( lbWitdh+170 < restWidth ){
							//debuglog('to right of the cursor');
							$("#lightbox")
							.css("top",(e.pageY - options.yOffset) + "px")
							.css("left",(e.pageX + options.xOffset) + "px")
							.fadeIn("fast");
						}
						else{
							///debuglog('to left of the cursor');
							$("#lightbox")
							.css("top",(e.pageY - options.yOffset) + "px")
							.css("left",(e.pageX - lbWitdh - options.xOffset) + "px")
							.fadeIn("fast");						
						}
					}
				})
				.mouseleave(function(e){
					
					$("#lightbox").remove();
				})
				.mousemove(function(e){
					var bWidth = $("body").width();
					var restWidth = bWidth - e.pageX;
					var lbWitdh = $("#lightbox").outerWidth();
					
					if( lbWitdh+170 < restWidth ){
						//debuglog('to left of the cursor');
						$("#lightbox")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX + options.xOffset) + "px")
						.fadeIn("fast");
					}
					else{
						//debuglog('to right of the cursor');
						$("#lightbox")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX - lbWitdh - options.xOffset) + "px")
						.fadeIn("fast");	
					}
				})
                .click(function(e){
                    $("#lightbox").remove();
                });			
			});
	};
})(jQuery);	

//display info about who's on the case    
function persosCase(me) {
	var images = $(me).find('img');
	var max = images.length;
	var A = '';
	for(var i=0; i<max; i++) {
		A += '<img src="'+images[i].src+'" /> ';
	}
	if (A!='') A = "<br /><u><?=__js(765)?></u><br />"+A;
	return A;
}
// pareil mais pour guerre
function enPresence(trucs) {
	var out = '';
	// trucs est un tableau a 5 elements
	for(var i=1; i<5; i++) {
		out += trucs[i]+" "+alliances[i]['nom']+" &nbsp;";
	}
	return out+"<br />";
}
(function($){
	$.fn.warzonePreview = function(options){
		options = $.extend({  
                         'xOffset' : 10,
						 'yOffset' : 20,
                         'tooltipStr':''
                    },options || {});
        var $this = $(this); 
        $this.each(function(i, obj){
            $(obj).mouseenter(function(e) {
                var thiscase = $(this);
                $(thiscase).css('cursor','progress');
                $('#tooltip').remove();  
                var data = $(this).metadata();
                //var who = $('#case'+data.x+data.y);
                var str = options.tooltipStr;

                var tip = str.replace('[X]', data.x).replace('[Y]', data.y).replace('[ALLIANCESGUYS]', enPresence(data.presents)
                        ).replace('[ALLIANCESSCORE]', enPresence(data.scores)
                        ).replace('[ALLIANCEWIN]',data.appartenance).replace('[ZENIS]', data.z)

                //Append the tooltip template and its value
                $('body').append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');    

                //Set the X and Y axis of the tooltip
                $('#tooltip').css('top', e.pageY + options.xOffset );
                $('#tooltip').css('left', e.pageX + options.yOffset );

                //Show the tooltip with faceIn effect
                $('#tooltip').fadeIn(300,function(){
                    $(thiscase).css('cursor','pointer');
                });
            }).mousemove(function(e) {    
                //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
                $('#tooltip').css('top', e.pageY + options.xOffset );
                $('#tooltip').css('left', e.pageX + options.yOffset );

            }).mouseleave(function() {
                //Remove the appended tooltip template      
                $('#tooltip').remove();        
            })
            .click(function(){
                 //Remove the appended tooltip template
                 $('#tooltip').remove();
            });

        });
	};
})(jQuery);	

(function($){
	$.fn.mapcasePreview = function(options){
		options = $.extend({  
                         'xOffset' : 10,
						 'yOffset' : 20,
                         'tooltipStr':''
                    },options || {});
        var $this = $(this); 
        $this.each(function(i, obj){
            $(obj).mouseenter(function(e) {
                var thiscase = $(this);
                $(thiscase).css('cursor','progress');
                $('#tooltip').remove();  
                var data = $(this).metadata();
                var who = $('#case'+data.x+data.y);
                var str = options.tooltipStr;

                var tip = str.replace('[ZENIS]', data.z).replace('[X]', data.x).replace('[Y]', data.y).replace('[PERSOS]', persosCase($(who))).replace('[LIEUX]', data.place); 

                //Append the tooltip template and its value
                $('body').append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');    

                //Set the X and Y axis of the tooltip
                $('#tooltip').css('top', e.pageY + options.xOffset );
                $('#tooltip').css('left', e.pageX + options.yOffset );

                //Show the tooltip with faceIn effect
                $('#tooltip').fadeIn(300,function(){
                    $(thiscase).css('cursor','pointer');
                });
            }).mousemove(function(e) {    
                //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
                $('#tooltip').css('top', e.pageY + options.xOffset );
                $('#tooltip').css('left', e.pageX + options.yOffset );

            }).mouseleave(function() {
                //Remove the appended tooltip template
                $('#tooltip').remove();        
            })
            .click(function(){
                 //Remove the appended tooltip template
                 $('#tooltip').remove();
            });

        });
	};
})(jQuery);	

var divname = '';
var reload_list_interval = null;
var reload_perso_interval = null;
//var warzone_countdown = null;
var iwantogothere;

var JSON;

function delete_popup_message(id){
	//getJSON('/delete_popups.php?id='+id, 'del_popups');  
    $.get('/delete_popups.php?id='+id, function(data){   
        $('#popup_window').fadeOut(500);
    });
	return false;
}

function outSponsoring(zis, id) {
	//getJSON('/getOutSponsoring.php?id='+id, 'sponsorout');
	// on doit attendre le retour de JSON pour valider, sinon il est oubil� aussi sec et pas execut�
    $.get('/getOutSponsoring.php?id='+id,function(data){
        document.location.href = zis.href;
    }); 
	return false;
}


var createAjaxObject = function(ajaxType) {
	if(window.XMLHttpRequest){
		var http_request = new XMLHttpRequest();
		if( http_request.overrideMimeType && typeof(ajaxType) != 'undefined' && ajaxType == 'text'){
			http_request.overrideMimeType('text/xml');
		}
		return http_request;
	}
	else if(window.ActiveXObject){
		var ieVersions=['Microsoft.XMLHttp','MSXML2.XMLHttp'];
		for(var i=0, j=ieVersions.length; i<j; i++ ){
			try {
				http_request = new ActiveXObject(ieVersions[i]);
				return http_request;
			}
			catch(e) {}
		}
	}
	else{
		return false;
	}
};


// should be OBSOLETE
var getJSON = function(url , somevalue) {
	var http_request=createAjaxObject('text');
	if (typeof(http_request)=='object') {
		http_request.onreadystatechange=function(){
			if (http_request.readyState==4 && http_request.status==200){
				JSON = eval('('+http_request.responseText+')');

				if (somevalue=='membres') {
					elSel = document.getElementById('selectMembre');
					elSel.style.display='';
					for (i in JSON) {
						if (i== "vide") break;
						var elOptNew = document.createElement('option');
						elOptNew.text = JSON[i];
						elOptNew.value = i;

						try {
							elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
						}
						catch(ex) {
							elSel.add(elOptNew); // IE only
						}
					}
				}
				else if (somevalue=='qcm') {
					qcmajax(JSON); //obsolete get request is in qcm.php
				}
				else if (somevalue=='qcm2') {
					qcm2ajax(JSON);
				}
				else if (somevalue=='sponsorout') {
					document.location.href = iwantogothere;
				}
				else if (somevalue=='del_popups') {
					// just delete
				}

			}
			else return false;
		};
		http_request.open('GET',url,true);
		http_request.send(null);
	}
};

function loadCapsules(idpere, idm, perso, precondition, divn, filter, issuper) {
	var idg = (divn == 'clancaps')? 'gc' : 'gr';
	$('#'+idg+''+idpere+''+issuper+'> b').html('<img src="/images/small_loader.gif" style=" width:16px !important;height:16px !important;"/>Veuillez patienter...');
    var send = {};
    send.pere = idpere;
    send.idm = idm;
    send.perso = perso;
    send.filter = filter;
    send.precondition = precondition;
    send.issuper = issuper;
	$.ajax({
        type:'GET',
        async:false,
        data:send,
        dataType:'json',
        url: 'getCapsules.php',
        success:function(caps){
            //caps = eval('('+caps+')');
            var ajoutParent = $('#'+idg+''+idpere+''+issuper).get();
            var guys = '';

            if( typeof caps.guys != 'undefined'){
                guys = caps.guys
            }
            for (i in caps) {               
                if (i!="guys"){  
                   addCapsule(caps[i], guys, ajoutParent);
                } 
            }
            $('#'+idg+''+idpere+''+issuper).remove();
	}});
	
	return false;
}

function addCapsule(capsule, guys, ajoutParent) {
	var node = $("#baseCapsule");
	var nod = $(node).clone();
	$(nod).attr('id' , 'divc' + capsule.num_mem_cap);

	// le truc d'hover
	var tmp = $(nod).find('.capsshow');
    tmp = $('<div></div>').append(tmp).html();

    $.each(capsule, function(j,obj){
        
        tmp = tmp.replace('['+j+']', obj);
    });

	if (capsule.type_capsule=='rouge'){
		tmp = tmp.replace(/<div [^>]*ac=norouge>.*?<\/div>/g, '');
    }else{
		tmp = tmp.replace(/<div [^>]*ac=rouge>.*?<\/div>/g, '');
    }
	// changer la/les tetes de perso. Actuellement il y a 1 image "� la con"
	var iconesTmp='';
    
	if (guys=='ALL'){      
		tmp = tmp.replace('class="bot"', 'class="botall"');
        tmp = tmp.replace(/<img src=\"[\/a-zA-Z0-9_ ]*\.gif\"[^>]*>/, '');
    }
	else{
		iconesTmp = guys;
        tmp = tmp.replace(/<img src=\"[\/a-zA-Z0-9_ ]*\.gif\"[^>]*>/, iconesTmp);
    }
   // console.log(iconesTmp);
   // console.log(tmp);
	// on remplace l'unique image, qui a une valeur � la con, par la/les bonne(s) tete(s)
	
//console.log(tmp);

	$(nod).append(tmp);
    $(nod).replaceText("[titre_capsule]", capsule.titre_capsule);
      
	// le reste
	Es = $(nod).find('input:first');
	$(Es).val(capsule.num_mem_cap);
    $(Es).attr('id','ic' + capsule.num_mem_cap);
	
	Es = $(nod).find('img:first');
    if(capsule.issuper=='super'){
        capsule.type_capsule = 'S'+capsule.type_capsule;
        
    }
	$(Es).attr('src' , '/images/caps/'+capsule.type_capsule+'.gif');
	//nod.childNodes[3].nodeValue = capsule.titre_capsule;
    $(nod).css('display','none');
    $(nod).insertAfter(ajoutParent);
    $(nod).fadeIn(500);
    if (capsule.caps_can_take!=undefined  &&  !capsule.caps_can_take) {
		$('#ic'+capsule.num_mem_cap).hide(0);
		$(node).find('input:first').hide(0);
	}

}

//  http://www.dustindiaz.com/top-ten-javascript
function insertAfter(node, referenceNode) {// de ttes fa�on change, mettre au dernier ajout� (?) parce que l� ils sont � l'envers
	parent = referenceNode.parentNode;
	if (referenceNode.nextSibling) {
		parent.insertBefore(node, referenceNode.nextSibling);
	} else {
		parent.appendChild(node);
	}
}

// utilis� en ad�quoition avec la fonction getmembreajax()
// choppera les infos n�cessaires

//zlati jquery rewrite
function getmembreajax(lettre) {
	// destruction du dernier au 2e �l�ment du select
	//var elSel = document.getElementById('selectMembre');
	//var i;
	//for (i = elSel.length - 1; i>0; i--) elSel.remove(i);
	// choppage des nouveaux
	//getJSON('/getMembres.php?lettre='+lettre, 'membres');
    var elSel = $('#selectMembre');
    $(elSel).empty();
    var send = {};    
    send.lettre = lettre;
    
    $.get('/getMembres.php', send, function(data){
        if(typeof data != 'undefined'){
            var $elSel = $('#selectMembre');
            $elSel.css('display','');
            $elSel.empty();
            
            data = $.parseJSON(data);
            $.each(data,function(i, obj){
               if(i!='vide'){
                    var elOptNew = $('<option value="'+i+'">'+data[i]+'</option>');
                    $elSel.append(elOptNew);
               }
               else{
                   $elSel.hide();
               }
            });
        }
    });
}


//OBSOLETE get request is in qcm.php
function qcmajax(JSON) {
	qid = JSON['question']['id'];
	bulle.id = bulle.id.replace(/\d+tmp$/, qid);
	bulle.innerHTML = JSON['question']['txt'];

	if (JSON['reponses']) {
		//divreponse
		aaa = document.getElementById('reponse0').cloneNode(true);
		aaa.id = "reponse"+qid;
		aaa.style.display = '';
		container.appendChild(aaa);
		// dedans
		brep = document.getElementById('boutonrep');
		srep = document.getElementById('spanrep');
		nrep = document.getElementById('brrep');
		for (i in JSON['reponses']) {
			//alert("rep "+i+" : "+JSON['reponses'][i]);
			// ajouter les r�ponses possibles
			b = brep.cloneNode(true);
			b.style.display = '';
			b.name = i;
			b.id = 'osef_b_'+qid+i;
			aaa.appendChild(b);

			// texte aussi

			//c = document.createNode(1, "span", "");
			b = srep.cloneNode(true);
			b.style.display = '';
			b.id = 'osef_s_'+qid+i;
			b.innerHTML = " "+JSON['reponses'][i];
			aaa.appendChild(b);

			// ajouter BR
			b = nrep.cloneNode(true);
			b.style.display = '';
			b.id = 'osef_n_'+qid+i;
			aaa.appendChild(b);
		}
	}
	else if (JSON['lienfin']) {
		b = srep.cloneNode(true);
		b.style.display = '';
		b.id = 'osef_s_'+qid;
		b.innerHTML = "<h4><a href='"+JSON['lienfin']+"'>T'as m�rit� une r�compense ! Clique ici...</a></h4>";
		container.appendChild(b);
	}
	else {
		b = srep.cloneNode(true);
		b.style.display = '';
		b.id = 'osef_s_'+qid;
		b.innerHTML = "<h4>Votre rendez-vous est fini je crois !...</h4>";
		container.appendChild(b);
	}

	document.location.href = '#'+bulle.id;
}


/////////////// for index

var msgBan='www.2fight.com - Premier MMORPG dragon ball en ligne gratuit !';
var posBan=0, timerBan;

function doOnLoad() {
	var espaces = '                            ';
	msgBan = espaces+msgBan+espaces+msgBan+espaces+msgBan+espaces+msgBan;
	timerBan = setInterval('banniere()', 300);
}

function banniere() {
	if (posBan >= msgBan.length-128) posBan = 0;
	window.status = msgBan.substring(posBan);
	posBan++;
}

function viewhelp(page){
    if($('#Show'+page).is(':hidden')){
        $('#Show'+page).show(0);
        $('#Help'+page).hide(0);
    }
    else{
        $('#Show'+page).hide(0);
        $('#Help'+page).show(0);
    }
}

//////////////// (What's over this is old shit - jQuery now FTW)

// update fighter list
function reloadListFighters() {
	$("#listFighters").load('/fights/listFighters.php?jsmode=1');
}

//////////// update perso
function updateLeftPerso(p) {
	$.ajax({
		async: true,
		dataType:'json',
		data:'perso='+p,
		type:'get',
		url:'/getPersoData.php',
		cache: false,
		success:function(data){
			//console.log(data);
                        if( typeof data != 'undefined' && data != null ){
                            var $viebar = $('#lmenubarvie');
                            var vie = Math.round( 100*data.vie_now/data.vie);
                            $viebar.find('th').html(write_number( data.vie_now )) ;
                            $viebar.find('td:first').find('div.lmenubarvie').find('div').width(vie+'%');

                            var $manabar = $('#lmenubarmana');
                            var mana = Math.round( 100*data.mana_now/data.mana);
                            $manabar.find('th').html(write_number( data.mana_now ));
                            $manabar.find('td:first').find('div.lmenubarmana').find('div').width(mana+'%');

                            if( typeof data.pinfo != 'undefined') {
                                    $('#popup_window').show();
                                    $('#pinfo').html( data.pinfo );
                            }
                        }
			
		}
	});

}
function write_number(n) {
	n = ""+n+""; // int 2 str
	n = n.split(''); // str 2 array
	var a='';
	var j=0;
	for (var i=n.length-1; i>=0; i--) {
		j++;
		a = n[i]+a;
		if (!(j%3) && i) a = '&nbsp;'+a;
	}
	return a;
}
function sharingLink(obj)
{
    obj = $(obj);
    var title = obj.attr('title');
    $("#facebook_share").find(".direct_link > ul > li").each(function(){
        if($(this).attr('title') == title)
            $(this).toggleClass('current', true);
        else
            $(this).toggleClass('current', false);
    });

    $("#facebook_share").find(".showing_links > textarea").each(function(){
        if( $(this).attr('id') == title )
            $(this).toggleClass('showing', true);
        else
            $(this).toggleClass('showing', false);
    });
}
/* DEPRECATED
function checkWarzoneCoundown(){
    $.ajax({
            type:'GET',
            async:false,
            dataType:'json',
            url:'/getWarzoneCounter.php',
            success:function(response){
                if( typeof response.countdown != 'undefined' ){
                    if(response.countdown=='00:00:00'){
                        $(".warzoneCounter").parent().empty().text('The Warzone is closed');
                        $('#warzonemap').fadeOut(3000,function(){
                            $(this).addClass('ui-helper-hidden');
                        });
                        warzone_countdown = clearInterval(warzone_countdown);
                    }
                    else{
                        $(".warzoneCounter").text(response.countdown);
                    }
                    
                }
            }
        });
}
jQuery(document).ready(function(){
    //DEPRECATED
    if( $(".warzoneCounter").length != 0){
            warzone_countdown = setInterval("checkWarzoneCoundown()",1000);
    }
})

*/

jQuery(document).ready(function(){ 
        $('.ui-state-default').live('mouseover mouseout', function(ev){
            if(ev.type == 'mouseover'){
                $(this).addClass('ui-state-hover');
            }
            else
            {
                $(this).removeClass('ui-state-hover');
            }      
        });

        $('.jqButton').button();
        $('.jqButtonPrev').button({
            icons: {
                primary: "ui-icon-carat-1-w"
                
            }
        });
        $('.jqButtonNext').button({
            icons: {
                primary: "",
                secondary: "ui-icon-carat-1-e"
            }
        });
        
        
        

        $('#freezeList').click(function(ev){
            ev.preventDefault();
            $(this).fadeOut(300);
            clearTimeout(reload_list_interval);
        });


    $(".direct_link").find('ul > li').click(function(){
        sharingLink(this);
    });
    $(".direct_link").find('ul > li:first').triggerHandler('click');

    $("a", $(".social_sites")).click(function(e){
        e.preventDefault();       
        window.open($(this).attr('href'), "<?= __(2140) ?>", "width=700, height=500,scrollbars=1");
    });

    $("a.sharebutton").click(function(e){
        e.preventDefault();
        window.open($(this).attr('href'), "<?= __(2140) ?>", "width=700, height=500,scrollbars=1");
    });
       
    $('div.unecapsule').livequery(function(){ 
        $(this).capsulePreview(); 
    });
    
    $('.tipsy_nw').tipsy({
        gravity: 'nw',
        fade: true
    })
    .hover(function(){
        $(this).addClass('hover');
    },function(){
       $(this).removeClass('hover'); 
    });
    
    
    $('.spoiler_link').live('click',function(){
       $(this).hide(0);
       $(this).next('.spoiler').show(0);
       return false;
    });

})
