var theSelection = false;

var phpBBroot = "";

// The text field to update
var formName = "document.post";

// The text field to update
var textFieldName = "message";

var theDocument = this.document;

// Navigateur safari
var isSafari = navigator.userAgent.toLowerCase().indexOf("safari") != -1;

function setPhpBBRoot(path)
{
   phpBBroot = path;
}

function setTextFieldName(formTextFieldName)
{
   textFieldName = formTextFieldName;
}

function setFormName(zeFormName, floating)
{
   if (floating)
      theDocument = window.opener.document;
   else
      theDocument = document;

   formName = zeFormName;
}

function getTextField()
{
    var flds = document.getElementsByName(textFieldName); 
    
    if (flds.length == 1) return flds[0];
    
    for (var idx = 0; idx < flds.length; idx++)
    {
        if (flds[idx].nodeName == "TEXTAREA") return flds[idx];
    }
    // return eval(textFieldName);
}

function bbcode(openTag, closeTag, helpText, imageId)
{
    this.openTag = openTag;
    this.closeTag = closeTag;
    this.helpText = helpText;
    this.imageId = imageId;

    this.isOpened = false;
}

function bbcodeProcessSelection()
{
    if (tagSelection(this.openTag, this.closeTag)) return;

    if (! this.isOpened)
    {
        insertText(this.openTag);

        eval(formName + "." + this.imageId + ".src = '" + phpBBroot + "bbcode_box/images/" + this.imageId + "1.gif'");

        this.isOpened = true;
    }
    else
    {
        insertText(this.closeTag);

        eval(formName + "." + this.imageId + ".src = '" + phpBBroot + "bbcode_box/images/" + this.imageId + ".gif'");

        this.isOpened = false;
    }
}

bbcode.prototype.processSelection  = bbcodeProcessSelection;


var bbcodeHelp = new Array();

// Adding all simple BB codes
// --------------------------

bbcodeHelp['b']       = new bbcode("[b]", "[/b]", "Gras: [b]text[/b]", "bold");
bbcodeHelp['i']       = new bbcode("[i]", "[/i]", "Italique: [i]text[/i]", "italic");
bbcodeHelp['u']       = new bbcode("[u]", "[/u]", "Souligne: [u]text[/u]", "under");
bbcodeHelp['y']       = new bbcode("[pre]", "[/pre]", "Texte preformatté (pas de modification des espaces et sauts de ligne): [pre]texte[/pre]", "pre");
bbcodeHelp['list']    = new bbcode("[list][*]", "[/list]", "Créer une liste: [list][*]texte 1[*]texte 2 ... [/list]", "list");
bbcodeHelp['quote']   = new bbcode("[quote]", "[/quote]", "Citation: [quote]text[/quote]", "quote");
bbcodeHelp['hr']      = new bbcode("[hr]", "", "Insérer un séparateur horizontal: [hr]", "");
bbcodeHelp['code']    = new bbcode("[code]", "[/code]", "Code: [code]code[/code]", "code");
bbcodeHelp['marqu']   = new bbcode("[marq=up]", "[/marq]", "Défilement vers le haut: [marq=up]texte[/marq]", "marqu");
bbcodeHelp['marqd']   = new bbcode("[marq=down]", "[/marq]", "Défilement vers le bas: [marq=down]texte[/marq]", "marqd");
bbcodeHelp['marql']   = new bbcode("[marq=left]", "[/marq]", "Défilement vers la gauche: [marq=left]texte[/marq]", "marql");
bbcodeHelp['marqr']   = new bbcode("[marq=right]", "[/marq]", "Défilement vers la droite: [marq=right]texte[/marq]", "marqr");
bbcodeHelp['fade']    = new bbcode("[fade]", "[/fade]", "Texte estompé: [fade]texte[/fade]", "fade");
bbcodeHelp['justify'] = new bbcode("[align=justify]", "[/align]", "Justifier le texte: [align=justify]texte[/align]", "justify");
bbcodeHelp['left']    = new bbcode("[align=left]", "[/align]", "Aligner le texte à gauche: [align=left]texte[/align]", "left");
bbcodeHelp['right']   = new bbcode("[align=right]", "[/align]", "Aligner le texte à droite: [align=right]texte[/align]", "right");
bbcodeHelp['center']  = new bbcode("[align=center]", "[/align]", "Centrer le texte: [align=center]texte[/align]", "center");
bbcodeHelp['indent']  = new bbcode("[indent]", "[/indent]", "Indenter le texte: [indent]texte[/indent]", "indent");

bbcodeHelp['moderation'] = new bbcode("[moderation]", "[/moderation]", "Insérer un message de modération: [moderation]texte[/moderation]", "moderation");
bbcodeHelp['s']  = new bbcode("[s]", "[/s]", "Barrer le texte: [s]texte[/s]", "strike");

// Additional help
// ---------------
var helpDef = new Array();

helpDef['img']    = "Insérer une image: [img]http://adresse web l'image[/img]";
helpDef['url']    = "Insérer un lien Web: [url]http://adresse web du site[/url] ou [url=http://adresse web du site]nom du site[/url]";
helpDef['fc']     = "Couleur du texte: [color=red]texte[/color] Vous pouvez utiliser les codes de couleur HTLM color=#FF0000";
helpDef['fs']     = "Taille du texte: [size=9]texte[/size]";
helpDef['ft']     = "Police de caractères: [font=Arial]texte[/font]";
helpDef['mail']   = "Insérer une adresse e-mail: [email]Adresse e-mail[/email]";
helpDef['grad']   = "Insérer du texte multicolore";
helpDef['stream'] = "Insérer un flux audio/vidéo: [stream]adresse web du flux[/stream]";
helpDef['ram']    = "Insérer un fichier Real Média: [ram]adresse web du fichier Real[/ram]";
helpDef['web']    = "Insérer une page Web : [web]adresse web de la page[/web]";
helpDef['plain']  = "Enlever le BBCode du texte sélectionné";
helpDef['hr']     = "Insérer un séparateur horizontal[hr]";
helpDef['video']  = "Insérer un fichier vidéo: [video width=largeur height=hauteur]adresse web du fichier video[/video]";
helpDef['flash']  = "Insérer un fichier Flash: [flash width=largeur height=hauteur]adresse web du fichier Flash[/flash]";
helpDef['yt']     = "Insérer une vidéo Youtube: [youtube]code de la video[/youtube]";
helpDef['dm']     = "Insérer une vidéo Dailymotion: [dailymotion]code de la video[/dailymotion]";


function BBCbold()    { bbcodeHelp['b'].processSelection(); }
function BBCitalic()  { bbcodeHelp['i'].processSelection(); }
function BBCunder()   { bbcodeHelp['u'].processSelection(); }
function BBCpre()     { bbcodeHelp['y'].processSelection(); }
function BBClist()    { bbcodeHelp['list'].processSelection(); }
function BBCquote()   { bbcodeHelp['quote'].processSelection(); }

function BBCmoderation() { bbcodeHelp['moderation'].processSelection(); }

// HR is specific (no close tag)
function BBChr()      { insertText(bbcodeHelp['hr'].openTag); }

function BBCcode()    { bbcodeHelp['code'].processSelection(); }
function BBCmarqu()   { bbcodeHelp['marqu'].processSelection(); }
function BBCmarqd()   { bbcodeHelp['marqd'].processSelection(); }
function BBCmarql()   { bbcodeHelp['marql'].processSelection(); }
function BBCmarqr()   { bbcodeHelp['marqr'].processSelection(); }
function BBCcenter()  { bbcodeHelp['center'].processSelection(); }
function BBCright()   { bbcodeHelp['right'].processSelection(); }
function BBCleft()    { bbcodeHelp['left'].processSelection(); }
function BBCjustify() { bbcodeHelp['justify'].processSelection(); }
function BBCfade()    { bbcodeHelp['fade'].processSelection(); }
function BBCindent()  { bbcodeHelp['indent'].processSelection(); }
function BBCstrike()  { bbcodeHelp['s'].processSelection(); }

// Processing specific BB Codes
// ----------------------------

function BBCplain()
{
   text = getTextField().value;

   if (text != '')
   {
      temp = text;
      temp = temp.replace(/\[FLASH=([^\]]*)\]WIDTH=[0-9]{0,4} HEIGHT=[0-9]{0,4}\[\/FLASH\]/gi,"$1");
      temp = temp.replace(/\[VIDEO=([^\]]*)\]WIDTH=[0-9]{0,4} HEIGHT=[0-9]{0,4}\[\/VIDEO\]/gi,"$1");

      getTextField().value = temp.replace(/\[[^\]]*\]/gi,"");
   }
}

function BBCft()
{
    openTag  = "[font=" + eval(formName + ".ft.value") + "]";
    closeTag = "[/font]";

    eval(formName + ".ft.selectedIndex = 0");

    if (tagSelection(openTag, closeTag)) return;

    insertText(openTag + " " + closeTag);
}

function BBCfs()
{
    openTag  = "[size=" + eval(formName + ".fs.value") + "]";
    closeTag = "[/size]";

    eval(formName + ".fs.selectedIndex = 0");

    if (tagSelection(openTag, closeTag)) return;

    insertText(openTag + " " + closeTag);
}

function BBCfc()
{
    openTag  = "[color=" + eval(formName + ".fc.value") + "]";
    closeTag = "[/color]";

    eval(formName + ".fc.selectedIndex = 0");

    if (tagSelection(openTag, closeTag)) return;

    insertText(openTag + " " + closeTag);
}

function BBCflash()
{
    url = userInput("Indiquez l'adresse Web du fichier Flash", "http://",
                    "Vous n'avez pas indiqué d'adresse Web du fichier Flash");

    if (url === '') return;

    width = userInput("Indiquez la largeur de la fenêtre Flash", "250",
                    "Vous n'avez pas indiqué la largeur de la fenêtre Flash");

    if (width === '') return;

    height = userInput("Indiquez la hauteur de la fenêtre Flash", "250",
                    "Vous n'avez pas indiqué la hauteur de la fenêtre Flash");

    if (height === '') return;

    insertText("[flash width="+width+" height="+height+"]"+url+"[/flash]");
}

function BBCyoutube()
{
    url = userInput("Copiez ci-dessous l'adresse de la vidéo YouTube", "",
                    "Vous n'avez pas indiqué l'adresse de la video");

    if (url === '') return;

    var reg = new RegExp("v=[A-Za-z0-9_\-]+");

    var code = "" + reg.exec(url);

    if (code != null && code != '')
    {
        insertText("[youtube]"+code.substring(2)+"[/youtube]");
    }
    else
    {
        alert("La vidéo ne peut pas être insérée. Merci de vérifier l'adresse Web");
    }
}

function BBCdailymotion()
{
    url = userInput("Copiez ci-dessous l'adresse de la vidéo Dailymotion", "",
                    "Vous n'avez pas indiqué l'adresse de la video");

    if (url === '') return;

    var reg = new RegExp("video/([a-zA-Z0-9]+)_.*$");

    var code = "" + reg.exec(url);

    if (code != null && code != '')
    {
        insertText("[dailymotion]"+code.replace(reg, "$1")+"[/dailymotion]");
    }
    else
    {
        alert("La vidéo ne peut pas être insérée. Merci de vérifier l'adresse Web");
    }
}

function BBCurl()
{
    url = userInput("Indiquez l'adresse Web", "http://",
                    "Vous n'avez pas indiqué d'adresse Web");

    if (url === '') return;

    title = userInput("Indiquez le nom de la page Web", "Nom de la page",
                    "Vous n'avez pas indiqué le nom de la page");

    if (title === '') return;

    insertText("[url="+url+"]"+title+"[/url]");
}

function BBCimg()
{
    url = userInput("Indiquez l'adresse Web de l'image", "http://",
                    "Vous n'avez pas indiqué d'adresse Web de l'image");

    if (url === '') return;

    insertText("[img]"+url+"[/img]");
}

function BBCgrad()
{
   if (! theDocument.selection)
   {
      alert("Désolé, cette fonction n'est accessible que depuis Internet Explorer.");

      return;
   }

   var oSelect,oSelectRange;

   getTextField().focus();

   oSelect = theDocument.selection;
   oSelectRange = oSelect.createRange();

   if (oSelectRange.text.length < 1)
   {
      alert("Sélectionnez d'abord une portion de texte");

      return;
   }

   if (oSelectRange.text.length > 120)
   {
      alert("Ah, ça ne marche pas si il y a plus de 120 caractères sélectionnés...");

      return;
   }

   showModalDialog(phpBBroot + "bbcode_box/grad.htm",oSelectRange,"help:no; center:yes; status:no; dialogHeight:50px; dialogWidth:50px");
}

function BBCram()
{
    url = userInput("Indiquez l'adresse Web du fichier Réal Média", "http://",
                    "Vous n'avez pas indiqué d'adresse Web du fichier Réal Média");

    if (url === '') return;

    insertText("[ram]"+url+"[/ram]");
}

function BBCstream()
{
    url = userInput("Indiquez l'adresse Web du flux audio/vidéo", "http://",
                    "Vous n'avez pas indiqué d'adresse Web du flux audio/vidéo");

    if (url === '') return;

    insertText("[stream]"+url+"[/stream]");
}

function BBCvideo()
{
    url = userInput("Indiquez l'adresse Web du fichier vidéo", "http://",
                    "Vous n'avez pas indiqué d'adresse Web du fichier vidéo");

    if (url === '') return;

    width = userInput("Indiquez la largeur de la fenêtre vidéo", "320",
                    "Vous n'avez pas indiqué la largeur de la fenêtre vidéo");

    if (width === '') return;

    height = userInput("Indiquez la hauteur de la fenêtre vidéo", "200",
                    "Vous n'avez pas indiqué la hauteur de la fenêtre vidéo");

    if (height === '') return;

    insertText("[video width="+width+" height="+height+"]"+url+"[/video]");
}

function BBCweb()
{
    url = userInput("Indiquez l'adresse de la page Web", "http://",
                    "Vous n'avez pas indiqué l'adresse de la page Web");

    if (url === '') return;

    insertText("[web]"+url+"[/web]");
}

function BBCmail()
{
    url = userInput("Indiquez une adresse e-mail", "",
                    "Vous n'avez pas indiqué d'adresse e-mail");

    if (url === '') return;

    insertText("[email]"+url+"[/email]");
}

// --------------------------------------------------------------------------
// General functions
// --------------------------------------------------------------------------

function storeCaret(textEl)
{
    if (textEl.createTextRange) textEl.caretPos = theDocument.selection.createRange().duplicate();
}

function helpline(help)
{
    if (bbcodeHelp[help])
    {
       helpText = bbcodeHelp[help].helpText;
    }
    else if (helpDef[help])
    {
       helpText = helpDef[help];
    }
    else
    {
        helpText = "";
    }

    eval(formName + ".helpbox.value = helpText");

    eval(formName + ".helpbox.readOnly = 'true'");
}

function checkForm()
{
    formErrors = false;

    if (getTextField().value.length < 2)
    {
        formErrors = "Vous devez entrer un message pour poster !";
    }

    if (formErrors)
    {
        alert(formErrors);
        return false;
    }
    else
    {
        document.getElementById("submit_btn").displaed = true;
        document.getElementById("preview_btn").displaed = true;

        return true;
    }
}

function emoticon(text)
{
    insertText(text);
}


function userInput(message, defaultValue, error)
{
    var userData = prompt(message, defaultValue);

    if (userData == '')
    {
       alert(error);

       return "";
    }
    else if (userData == null)
    {
        return "";
    }

    return userData;
}

function tagSelection(startTag, endTag)
{
    var textarea = getTextField();

    // Internet Explorer ou Safari
    if (theDocument.selection || isSafari)
    {

    	if (textarea.createTextRange && textarea.caretPos)
        {
            theSelection = theDocument.selection.createRange().text;

            if (theSelection != '')
            {
                theDocument.selection.createRange().text = startTag + theSelection + endTag;

                textarea.focus();

                return true;
            }
    	}
	}
	// Mozilla
	else if (textarea.selectionStart | textarea.selectionStart == 0)
	{
        if (textarea.selectionEnd > textarea.value.length)
        {
            textarea.selectionEnd = textarea.value.length;
        }

        var selStart = textarea.selectionStart;
        var selEnd   = textarea.selectionEnd;

        if (selStart == selEnd) return;

        var beginText    = textarea.value.substring(0, selStart);
        var selectedText = textarea.value.substring(selStart, selEnd);
        var endText      = textarea.value.substring(selEnd);

        textarea.value = beginText + startTag + selectedText + endTag + endText;

        selStart += startTag.length;
        selEnd   += startTag.length;

        textarea.setSelectionRange(selStart, selEnd);

        textarea.focus();

        return true;
	}

	return false;
}

function insertText(text)
{
    var textarea = getTextField();

    // Internet Explorer
    if (theDocument.selection || isSafari)
    {
        if (textarea.createTextRange && textarea.caretPos)
        {
  		      var caretPos = textarea.caretPos;

            caretPos.text = text;

            textarea.focus();
        }
        else
        {
           textarea.value  += text;

           textarea.focus();
        }
   }
   // Mozilla
   else if (textarea.selectionStart | textarea.selectionStart == 0)
   {
        var selStart = textarea.selectionStart;

        textarea.value = textarea.value.substring(0, selStart) + text + textarea.value.substring(selStart);

        selStart = selStart + text.length;

        textarea.setSelectionRange(selStart, selStart);

        textarea.focus();
   }
   // Autre navigateur inconnu
   else
   {
        textarea.value  += text;

        textarea.focus();
   }
}
