
if (screen && screen.width) {
	var screenWidth=screen.width;
	var screenHeight=screen.height;
}

function openWindow(theUrl, windowId, width, height, windowOptions, anchor) {
	if (theUrl.indexOf('?') < 0) {
		theUrl += '?';
	} else {
		theUrl += '&';
	}

	if (screenWidth && width > screenWidth+32) {
		if (width > screenWidth+182)
			theUrl += '&resizedX=2';
		else
			theUrl += '&resizedX=1';
		width=screenWidth-8;
	}
	if (screenHeight && height > screenHeight+32) {
		height=screenHeight-40;
		theUrl += '&resizedY=1';
	}
	theUrl += 'width='+width+'&height='+height;

    if (navigator && !navigator.javaEnabled())
        theUrl += '&nojava=1';
    else
        theUrl += '&java=1';

    if (anchor != '')
        theUrl += '#'+anchor;
        
	var theWindow = window.open(theUrl, windowId, 'width='+width+',height='+height+','+windowOptions);
    if (theWindow.focus)
        theWindow.focus();
}

function setValue(obj, value) {
	if (obj.firstChild && obj.firstChild.nodeValue != null)
		obj.firstChild.nodeValue = value;
	else
		obj.innerText = value;
}

function getValue(obj) {
	if (obj.firstChild && obj.firstChild.nodeValue != null)
		return obj.firstChild.nodeValue;
	else
		return obj.innerText;
}

function createDojoWindow(event, title, url) {
	var dW = dojo.widget.createWidget("FloatingPane", {title: title, href: url, hasShadow: true, displayCloseAction: true, parseContent: false, loadingMessage: 'Chargement en cours...'});
	document.body.appendChild(dW.domNode);
	dW.resizeTo(300,400);
	if (window.innerWidth) {
		w = window.innerWidth;
		h = window.innerHeight;
	} else {
		w = document.body.offsetWidth;
		h = document.body.offsetHeight;
	}
	dW.domNode.style.left = Math.max(0, Math.min(w-300, (event.layerX-10)))+"px";
	dW.domNode.style.top = Math.max(0, Math.min(h-400, (event.layerY-30)))+"px";
	return dW;
}

function toggleHideShow(hide, show) {
    $('#'+show).css('display', 'block');
    $('#'+hide).css('display', 'none');
    return false;
}

function changeOnglet(name) {
	$('#'+name).css('display', 'block');
	if (oldOnglet != '' && oldOnglet != name) {
		$('#'+oldOnglet).css('display', 'none');
	}
	oldOnglet = name;
}

function changeOngletAjax(name) {
	if (oldOnglet != name) {
		if (oldOnglet != '') {
            $('#'+oldOnglet).hide();
            $('#'+name).height($('#'+oldOnglet).height());
		}
        $('#'+name).show();
        if ($('#'+name).attr('loaded') != 'ok') {
            $('#'+name).load('/ajax.php?tpl=onglet&mode=plain&onglet='+name);
            $('#'+name).attr('loaded', 'ok');
        }
	}
	oldOnglet = name;
    return false;
}

function createWindow(element, url) {
	$.getJSON(url, function(json) {
                var title = json.title;
				var subtitle;
                if (json.subtitle != "") {
                    subtitle = "<h3>" + json.subtitle + "</h3>";
                    json.height += 34;
                    $('#window-title').html(subtitle);
                    $('#window-title').show();
                } else {
                    $('#window-title').hide();
                }
                var html = json.html;
                $('#window-content').html(html);
                $('#window-content').css('height', json.height);
                if (json.image != "") {
                    $('#window-image').attr('src', json.image);
                    $('#window-image').show();
                } else {
                    $('#window-image').hide();
                }
				$('#window').css('display','inline');
				$('#window').dialog({title:title, width:(json.width+8), height:(json.height+36)});
//				$('#window').fadeIn('normal')
                //Effect.Appear('window', {duration: 0.25});
//                window.setTimeout('closeWindow()', 60000);
//				$('#window').dialog('open');
            }
        );
/*    else
        openWindow(url+'&ow', 'ow', 500, 500);*/
}

function closeWindow() {
    Effect.Fade('window', {duration: 0.25});
}

function sprintf() {
if (!arguments || arguments.length < 1 ||!RegExp) {return;}
var str = arguments[0];
var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
var a = b = [], numSubstitutions = 0, numMatches = 0;
while (a = re.exec(str)) {
var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
var pPrecision = a[5], pType = a[6], rightPart = a[7];numMatches++;
if (pType == '%') {
subst = '%';
} else {
numSubstitutions++;
if (numSubstitutions >= arguments.length) {
alert('Error! Not enough function arguments (' +
(arguments.length - 1) + ', excluding the string)\n' +
'for the number of substitution parameters in string (' +
numSubstitutions + ' so far).');
}
var param = arguments[numSubstitutions];
var pad = '';
if (pPad && pPad.substr(0,1) == "'") {
pad = leftpart.substr(1,1);
} else if (pPad) {
pad = pPad;
}
var justifyRight = true;
if (pJustify && pJustify === "-") justifyRight = false;
var minLength = -1;
if (pMinLength) minLength = parseInt(pMinLength);
var precision = -1;
if (pPrecision && pType == 'f') {
precision = parseInt(pPrecision.substring(1));
}
var subst = param;
switch (pType) {
case 'b':subst = parseInt(param).toString(2);break;
case 'c':subst = String.fromCharCode(parseInt(param));break;
case 'd':subst = parseInt(param)? parseInt(param) : 0;break;
case 'u':subst = Math.abs(param);break;
case 'f':subst = (precision > -1)?
Math.round(parseFloat(param) * Math.pow(10, precision)) /
Math.pow(10, precision) : parseFloat(param);break;
case 'o':subst = parseInt(param).toString(8);break;
case 's':subst = param;break;
case 'x':subst = ('' +
parseInt(param).toString(16)).toLowerCase();break;
case 'X':subst = ('' +
parseInt(param).toString(16)).toUpperCase();break;
}
var padLeft = minLength - subst.toString().length;
if (padLeft > 0) {
var arrTmp = new Array(padLeft+1);
var padding = arrTmp.join(pad?pad:" ");
} else {
var padding = "";}}
str = leftpart + padding + subst + rightPart;
}
return str;
}

// Notes

function removeNote(noteid) {
    if (!confirm('Etes-vous sūr de vouloir effacer cette note ?'))
        return false;
    updateNotes("remove", noteid);
    return false;
}

function hideNote(noteid) {
    if (!confirm('Etes-vous sūr de vouloir masquer cette note ?'))
        return false;
    updateNotes("hide", noteid);
    return false;
}

function updateNotes(action, noteid) {
    var target = $("#notedialog ul");
    var targetId = $(".notes a").attr("targetId");
    var targetClass = $(".notes a").attr("targetClass");
    target.load("/ajax.php?tpl=notelist&mode=plain", {action: action, note: noteid, targetId: targetId, targetClass: targetClass}, function (data) {
        if (data.length == 0) {
            if ($(".newnote").css('display') != "none") {
                $(".noteplus").hide();
                $("#notedialog").slideDown();
            } else {
                $("#notedialog").slideUp();
            }
        } else {
            $(".noteplus").show();
            $("#notedialog").slideDown();
        }
    });
}

function addNote() {
    var target = $("#notedialog ul");
    target.append("<li><img src='/static/img/ajax-loader.gif' /></li>");
    target.load("/ajax.php?tpl=notelist&mode=plain", { action: "add", note: $('#addnote input[name=note]').val(),
                visibilite: $('#addnote [name=visibilite]').val(),
                targetId: $('#addnote [name=targetId]').val(), targetClass: $('#addnote input[name=targetClass]').val() });
    $(".noteplus").show();
    $(".newnote").slideUp();
    return false;
}
// portraits

var origPortrait,idPortrait;
var sexe,torse,tete,casque;

function initPortrait(id, theSexe, portrait) {
    idPortrait = id;
    origPortrait = portrait;
    if (portrait.length > 1)
        sexe = portrait.substr(0, 1);
    else
        sexe = theSexe;
    if (portrait.length > 3)
        torse = parseInt(portrait.substr(1, 3));
    else
        torse = 0;
    if (portrait.length > 6)
        tete = parseInt(portrait.substr(4, 3));
    else
        tete = 0;
    if (portrait.length > 8)
        casque = parseInt(portrait.substr(7, 3));
    else
        casque = 0;
}

function changePortrait() {
    var offset = $('#portrait').offset();
    $('#portrait-image').attr('src',  $('#portrait').attr('src'));
    $('#portrait-window').css({top: (offset.top-16), left: (offset.left-32)});
    $('#portrait-window').show();
}
function changeTete(mod) {
    if (sexe == 'H')
        tete = (tete+mod+18)%18;
    else
        tete = (tete+mod+11)%11;
    updateImagePortrait();
}
function changeTorse(mod) {
    if (sexe == 'H')
        torse = (torse+mod+10)%10;   
    else
        torse = (torse+mod+7)%7;   
    updateImagePortrait();
}
function changeCasque(mod) {
    if (sexe == 'H')
        casque = (casque+mod+7)%7;   
    else
        casque = (casque+mod+4)%4;   
    updateImagePortrait();
}
function getPortrait() {
    var portrait = sprintf('%s%03d%03d', sexe, torse, tete);
    if (casque > 0)
        portrait += sprintf('%03d', casque);
    return portrait;
}
function updateImagePortrait() {
    var portrait = getPortrait();
    var img = '/graph/portrait.php?id='+portrait;
    $('#portrait-image').attr('src', img);
}
function closePortrait() {
    var portrait = getPortrait();
    if (portrait != origPortrait) {
    	$.getJSON('/ajax.php?tpl=savePortrait&id='+idPortrait+'&portrait='+portrait, function(json) {
                var portrait = json.image;
                $('#portrait').attr('src', '/graph/portrait.php?id='+portrait);
        });
    }
    $('#portrait-window').hide();
}
function toggleCheckbox(name) {
    item = $(name);
    if (item.attr('checked')) {
        item.attr('checked', false);
    } else {
        item.attr('checked', true);
    }
}

// tactiques

function hideShowLink(select) {
    var selected = $('#'+select.id+' option:selected').val();
    if (selected)
        $('#'+select.id+'-link').show();
    else
        $('#'+select.id+'-link').hide();
}

function changeTooltip(id, type) {
    if (!$.fn.qtip) return;
	$('#'+id).qtip("destroy", true);
	$('#'+id).qtip({
        style: {name: 'SetS', width: {min: 350, max: 680}},
        position: {adjust: {screen: true}},
        content: {
            url: '/ajax.php',
            data: {tpl: type+'resume', mode: 'plain', id: $('#'+id).val()}
            }
        });
}

function changeTactique(tactique) {
  //$('#tactique-'+tactique).css('display', 'block');
  $('#tactique-'+tactique).show();
  $('#tacTitre-'+tactique).hide();
  $('#tacTitreSel-'+tactique).show();
  if (curTactique != tactique) {
    $('#tactique-'+curTactique).hide();
    $('#tacTitre-'+curTactique).show();
    $('#tacTitreSel-'+curTactique).hide();
  }
  curTactique = tactique;
  recompteTactique(curTactique, null, null);
  recompteMax(curTactique);
  updatePrevisions();
  return false;
}

function updatePrevisions() {
    $('#loaderPrevisions').addClass('loaderon');
    $.post( 
        "/ajax.php?mode=plain&tpl=updatePrevisions&tactique="+curTactique, 
        $('form#tacticPerso').serialize(), 
        function(data){ 
            if (data.success) {
                //$("span#enc").html(data.enc);
                $("div#equipementimg").html(data.equipement);
                $("span#previsions").html(data.previsions);
            }
        }, 
        "json" 
    ); 
}

function ajouteTactique() {
    if (nbTactiques >= nbTactiquesMax)
        return false;

    if (nbTactiques == 1) {
        $('#moins').show();
    }

    if (nbTactiques == nbTactiquesMax-1) {
        $('#plus').hide();
    }

    $('#tacTitre-'+nbTactiques).show();
    nbTactiques++;
    $('#nbTactiques').val(nbTactiques);
    changeSpeciales();
    recompteTactique(curTactique, null, null);
    recompteMax(curTactique);
    return false;
}
function supprimeTactique() {
    if (nbTactiques <= 1)
        return false;

    if (nbTactiques == nbTactiquesMax) {
        $('#plus').show();
    }

    if (nbTactiques == 2) {
        $('#moins').hide();
    }
    nbTactiques--;
    $('#nbTactiques').val(nbTactiques);
    if (curTactique >= nbTactiques)
        changeTactique(curTactique-1);
    $('#tacTitre-'+nbTactiques).hide();
    $('#tacTitreSel-'+nbTactiques).hide();
    changeSpeciales();
    recompteTactique(curTactique, null, null);
    recompteMax(curTactique);
    return false;
}

function recompteMax(numTactique) {
  $('#pointsMax-'+numTactique).val(nbPointsMax+1-nbTactiques);
}

function changeValeurTactique(numTactique, prevId, selValue) {
    resetSpeciale(numTactique);
    recompteTactique(numTactique, prevId, selValue);
}

function recompteTactique(numTactique, prevId, selValue) {
  var obj;
  var used = 0;
  for (var radioNum=0; radioNum < radioList.length; radioNum++) {
    var radioName = radioList[radioNum];
    for (var i = 0; i <= 4; i++) {
      var objId = radioName+'-'+numTactique+'-'+i;
      obj = $('#'+objId);
      if (obj.attr('checked')) {
         used += parseInt(obj.val());
      }
    }
  }
  if (used > nbPointsMax+1-nbTactiques && selValue != null) {
    needSelect = selValue - used + (nbPointsMax+1-nbTactiques);
    if (needSelect < 0)
      needSelect = 0;
    $('#'+prevId+'-'+needSelect).attr("checked", true);
    used += needSelect-selValue;
  }
  var left = nbPointsMax+1-nbTactiques - used;
  $('#pointsRestant-'+numTactique).text(left);
  if (left < 0)
    $('#tacFlag-'+numTactique).show();
  else
    $('#tacFlag-'+numTactique).hide();
}

function verifieTactiques() {
  for (var index=0; index < nbTactiques; index++) {
    var reste = parseInt($('#pointsRestant-'+index).text());
    if (reste < 0) {
      alert('ERREUR : Une de vos tactiques utilise plus de points que ceux disponibles.')
      return false;
    }
  }
  return true;
}

function changeSpeciales() {
    for (var index=0; index < nbTactiques; index++) {
        changeSpeciale(index);
    }
}

function changeSpeciale(numTactique) {
    var valeur = $('#speciale-'+numTactique+' option:selected').val();
    var tactiques = null;
    var distance=0;
    if (valeur == "berserk") {
       tactiques = ['force', 'vitesse', 'deplacement', 'precision'];
    }
    if (valeur == "degats") {
       tactiques = ['force', 'precision', 'deplacement', 'vitesse'];
    }
    if (valeur == "pluie") {
       tactiques = ['vitesse', 'deplacement', 'precision', 'force'];
    }
    if (valeur == "toucher") {
       tactiques = ['precision', 'deplacement', 'vitesse', 'force'];
    }
    if (valeur == "spectaculaire") {
       tactiques = ['style', 'deplacement', 'vitesse', 'precision'];
    }
    if (valeur == "riposte") {
       tactiques = ['defense', 'precision', 'deplacement', 'vitesse'];
    }
    if (valeur == "tortue") {
       tactiques = ['defense', 'deplacement', 'precision', 'vitesse'];
    }
    if (tactiques == null) {
        return;
    }
    /*if (distance != null) {
       distObj = $('#distance-'+numTactique);
       distObj.selectedIndex = distance;
    }*/
    for (var radioNum=0; radioNum < radioList.length; radioNum++) {
       var radioName = radioList[radioNum];
       var objId = radioName+'-'+numTactique+'-0';
       $('#'+objId).attr('checked', true);
    }
    var left = nbPointsMax+1-nbTactiques;
    for (var radioNum=0; radioNum < tactiques.length && left > 0; radioNum++) {
       var radioName = tactiques[radioNum];
       if (left >= 4)
        num = 4;
       else
        num = left;
       var objId = radioName+'-'+numTactique+'-'+num;
       $('#'+objId).attr('checked', true);
       left -= num;
    }
    //select.selectedIndex = selectedIndex;
    recompteTactique(numTactique, null, null);
}
function resetSpeciale(numTactique) {
    $('#speciale-'+numTactique).val("");
}