var debug = false;

// Provide flag to handle lack of standard compliance in Internet Explorer.
var ie = document.all;
var doc = null;

function menuOver(o, className) {
    if (o.className != 'on')
        o.className = className;
}

function menuOut(o, className) {
    o.className = className;
}

function editText(event) {
    // Get node which fired this event.
    var target;
    if (ie) {
        o = window.event.srcElement;
    } else {
        if (event.target)
            o = event.target;
        else
            o = event;
    }
    
    // Create editable textarea.
    var input = document.createElement("textarea");
    input.setAttribute("class", "wl_edit");
    input.setAttribute("wrap", "virtual");
    input.value = o.firstChild.nodeValue;
    
    // Style textarea.
    input.style.height = o.scrollHeight + 5;
    input.style.width = o.scrollWidth;
    input.style.fontFamily = o.style.fontFamily;
    //  input.style.fontFamily = "arial";
    input.style.fontSize = o.style.fontSize;
    
    // Clear existing content.
    o.removeChild(o.firstChild);
    
    // Add editable textarea to parent.
    o.appendChild(input);
    
    // Remove onclick event handler to avoid calling this method until edit is finished.
    o.onclick = null;
    
    // Attach unedit event handler.
    input.onblur = unedit;
    
    window.setTimeout("setTextareaFocus('" + o.getAttribute("id") + "');", 100);
}

function unedit(event) {
    // Get the parent of the node which fired this event.
    var target;
    if (ie)
        o = window.event.srcElement.parentNode;
    else
        o = event.currentTarget.parentNode;
    
    // Add the text of the textarea to the parent node and delete the textarea node.
    var textArea = o.firstChild;
    o.removeChild(textArea);
    o.appendChild(document.createTextNode(textArea.value));
    
    // Set the edit event handler on the parent node.
    o.onclick = editText;
    
    //## implement delete later
    //## check for null string until bug with 3rd click is fixed
    if (textArea.firstChild.nodeValue != null) {
        pageUpdater.saveText(o.getAttribute("tid"), textArea.value, 0);
    }
    
}

function uneditAll() {
    var tags = document.getElementsByTagName("textarea");
    for (i = 0; i < tags.length; i++) {
        //
    }
}

function setTextareaFocus(id) {
    var e = document.getElementById(id);
    if (e == null)
        return;
    e.firstChild.focus();
}

function setFocus(id) {
    //alert(id);
    var e = document.getElementById(id);
    if (e == null)
        return;
    e.focus();
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getActiveStyleSheet() {
    var links = document.getElementsByTagName("link");
    for(var i=0; i<links.length; i++) {
        var a = links.item(i);
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled){
            return a.getAttribute("title");
        }
    }
    return null;
}

function setImage(id, url) {
    var img = document.getElementById('imgAboveBox');
    img.src = url;
    img.setAttribute("src", url);
}


DOMUtils = {};
DOMUtils.createToolbar = function(){
    var toolbar = document.createElement("div");    
    var length = arguments.length;
    for(var i=0; i<length; i++){
        var btn = document.createElement("input");
        btn.setAttribute("type", "button");
        btn.setAttribute("value", arguments[i].label);
        btn.onclick = arguments[i].onclick;        
        toolbar.appendChild(btn);
    }    
    return toolbar;
}
DOMUtils.appendToolbar = function(){   
    var length = arguments.length;
    for(var i=1; i<length; i++){
        var btn = document.createElement("input");
        btn.setAttribute("type", "button");
        btn.setAttribute("value", arguments[i].label);
        btn.onclick = arguments[i].onclick;        
        arguments[0].appendChild(btn);
    }    
}


Insitu = {};
Insitu._editPane = null;
Insitu._linePane = null;
Insitu.currentTask = null;

/*
 * Task
 */ 
Insitu.Task = function(textId, container, type){
    this.type = type;
    this.pane = Insitu.getEditPane(type, container);
    this.editPane = this.pane.node;
    this.textId = textId;
    this.container = container;
    this.originalText = container.firstChild.nodeValue;
    this.isModified = false;
}

Insitu.Task.LINE = 1;
Insitu.Task.PARAGRAPHE = 2;

Insitu.Task.prototype.toString = function(){
    return "Insitu.Task {textId:" + this.textId + " , container:"+ this.container + "}"; 
}


/**
 * EditPane
 */
Insitu.EditPane = function(){    
    this.node = document.createElement("div");
    this.node.className = "wl_editpane";    
    this.input = document.createElement("textarea");
    this.input.setAttribute("class", "wl_edit");
    this.input.setAttribute("wrap", "virtual");
    
    var toolbar = DOMUtils.createToolbar(
    {label:"Annuler", onclick:Insitu.cancelCurrentTask},
    {label:"Supprimer", onclick:Insitu.deleteCurrentText},
    {label:"Sauvegarder", onclick:Insitu.saveCurrentText}
    );    
    
    toolbar.className = "toolbar";    
    
    this.node.appendChild(this.input);
    this.node.appendChild(toolbar);
}


Insitu.EditPane.prototype.setTarget = function(target){   
    /*
    if(target.getElementsByTagName("img").length > 0){
        
    }
    */
    this.input.value = target.firstChild.nodeValue;   
    this.input.style.height = (target.scrollHeight + 30) + "px";   
    this.input.style.width = target.scrollWidth + "px"; 
    this.input.style.fontFamily = target.style.fontFamily;
    this.input.style.fontSize = target.style.fontSize;   
}


/**
 * LinePane
 */
Insitu.LinePane = function(){    
    this.node = document.createElement("div");
    this.node.className = "wl_editpane";    
    this.input = document.createElement("input");
    this.input.setAttribute("type", "text");
    this.input.setAttribute("class", "wl_edit");
    this.input.setAttribute("wrap", "virtual");
    
    this.node.appendChild(this.input);
    
    DOMUtils.appendToolbar(this.node, 
    {label:"Annuler", onclick:Insitu.cancelCurrentTask},
    /*{label:"Supprimer", onclick:Insitu.deleteCurrentText}, */
    {label:"Sauvegarder", onclick:Insitu.saveCurrentText}
    );    
}


Insitu.LinePane.prototype.setTarget = function(target){   
    this.input.value = target.firstChild.nodeValue;   
    //this.input.style.height = (target.scrollHeight + 30) + "px";
    this.input.style.width = "250px"; 
    this.input.style.fontFamily = target.style.fontFamily;
    this.input.style.fontSize = target.style.fontSize;   
}


Insitu.getEditPane = function(type, target){
    switch(type){
        case Insitu.Task.LINE :
            if(Insitu._linePane == null){
                Insitu._linePane = new Insitu.LinePane();                
            }
            if(target) Insitu._linePane.setTarget(target);
            return Insitu._linePane;
            
        case Insitu.Task.PARAGRAPHE :
            if(Insitu._editPane == null){
                Insitu._editPane = new Insitu.EditPane();
            }
            if(target) Insitu._editPane.setTarget(target);
            return Insitu._editPane;
    }
    
    return Insitu._editPane;
}

Insitu.editText = function(textId, container){
	if(Insitu.cancelCurrentTask()){        
        Insitu.currentTask = new Insitu.Task(textId, container, Insitu.Task.PARAGRAPHE);
        Insitu.loadRawText(textId);
    }
}

Insitu.editLine = function(textId, container){      
    if(Insitu.cancelCurrentTask()){
        Insitu.currentTask = new Insitu.Task(textId, container, Insitu.Task.LINE);
        Insitu.loadRawText(textId);
    }    
}

Insitu.deleteCurrentText = function(){   
    var task = Insitu.currentTask;   
    if(task != null && confirm("Êtes-vous sûr de vouloir supprimer ce texte ?")){
        doc = new XML(); 
        doc.addListener(Insitu.onTextDeleted);
        doc.setAttribute("id", task.textId);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.sendAndLoad("deletetext.do");
    }    
}

Insitu.saveCurrentText = function(){   
    var task = Insitu.currentTask;   
    if(task != null){
        doc = new XML(); 
        //doc._method = "POST";

        if(task.type == Insitu.Task.LINE){
            doc.addListener(Insitu.onLineSaved);
        }else{
            doc.addListener(Insitu.onTextSaved);
        }
		
		doc.setAttribute("textId", task.textId);
		doc.setAttribute("action", "saveText");
		doc.setAttribute("data", task.pane.input.value);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.sendAndLoad("insituFunctions.php");
    }    
}


Insitu.onLineSaved = function(response){
    try{
        var task = Insitu.currentTask;    
        if(task != null){     
            
            var resultDoc = response.responseXML.firstChild;
            //patch pour IE
            if(resultDoc.childNodes.length == 0){      
                resultDoc = response.responseXML.childNodes[1];
            }
            
            var texts = XML.findChildren(resultDoc, "text", null, null);              
            for(var i=0; i<texts.length; i++){
                task.container.innerHTML = texts[i].firstChild.nodeValue;
            }
            Insitu.cancelCurrentTask();
        }   
    }catch(e){
        alert("Exception in in-situ.js [onLineSaved]: " + e.message);
    }
}

Insitu.onTextSaved = function(response) {
    try{
		var task = Insitu.currentTask;    
		if(task != null)
		{
			var target = task.editPane.nextSibling;
			var data = response.responseText;
			
			while(data.indexOf("\n") > 0)
				data = data.replace("\n", "<br />");
			
			var newText = XML.createElement(task.container.tagName, data);
			newText.className = task.container.className;
			newText.ondblclick = function() {
				if(task.type == Insitu.Task.LINE)
					Insitu.editLine(task.textId, this);
				else
					Insitu.editText(task.textId, this); 
			}

			if(target == null)
				task.parent.appendChild(newText);
			else
				task.parent.insertBefore(newText, target);
		}

		task.parent.removeChild(task.editPane);
		Insitu.currentTask = null;
    }
	catch(e) {
        alert("Exception in in-situ.js [onTextSaved]: " + e.message);
    }
}

Insitu.onTextDeleted = function(response){
    if(response.responseText == "true"){
        var task = Insitu.currentTask;    
        if(task != null){                        
            task.parent.removeChild(task.editPane);
            Insitu.currentTask = null;
        }
    }else{
        alert("Un erreur est survenu lors de la suppression du texte!  Veuillez réessayer plus tard ou contacter l'administration de Net-Logik.");
    }
}

Insitu.onRawTextLoaded = function(response){
    var task = Insitu.currentTask;
    if(task != null){      
        task.rawText = response.responseText;      
        task.pane.input.value = task.rawText;
        task.parent = task.container.parentNode;             
        task.parent.insertBefore(task.editPane, task.container);
        task.parent.removeChild(task.container);
    }
}

Insitu.loadRawText = function(textId){
	try {
	    doc = new XML(); 
	    doc.addListener(Insitu.onRawTextLoaded);
	    doc.setAttribute("textId", textId);
		doc.setAttribute("action", "getRawText");
	    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
	    doc.sendAndLoad("insituFunctions.php");
	}
	catch(e) {
		alert(e.message);
	}
}

Insitu.cancelCurrentTask = function(){
    var task = Insitu.currentTask;    
    if(task != null){            
        task.parent.insertBefore(task.container, task.editPane);
        task.parent.removeChild(task.editPane);
        Insitu.currentTask = null;
    }
    return true;
}