/**
 * @author Nicolas Desy
 * Copyright � 2005-2006 Les solutions Net-Logik. All rights reserved.
 */

Delegate = {
    create : function(o,f){
        return function(){ return f.apply(o,arguments); };
    }
};


/**
 * Classe qui g la communication avec le serveur
 *
 * METHODES
 * reset()
 * setAttribute(key, value)
 * setData(data)
 * addListener(listener)
 * sendAndLoad(url)
 */
XML = function(){				
    this._listener = [];	
    this.reset();
    this.asyn = true;
}

XML.SPECIAL_CHARS = [
    {code:8211, value:"-"},
    {code:8217, value:"'"},
    {code:339, value:"oe"},
    {code:37, value:"%25"},
    {code:38, value:"&amp;"},
    {code:43, value:"%2B"},
    {code:37, value:"%2F;"} 
];


/* idea :
 
function callback(response){
 
}
 
XML.sendAndLoad("loadText.do", {textId:12, lang:"fr"}, callback, "POST");
 */




XML.sendAndLoad = function(){
    
}

XML.prototype.setAsyn = function(value)
{
    this.asyn = value;
}

XML.prototype.reset = function(){
    this._params = null;
    this._method = "GET";
}

XML.prototype.setAttribute = function(/*String*/ key, /*String*/ value){		
    
    if(this._params == null){
        this._params = {};
    }
    
    
    

    
   // if(typeof value == "string"){   
        var chars = XML.SPECIAL_CHARS;
        var nbchars = chars.length;
        var size = value.length;
        for(var i=0; i<size; i++){
            for(var j=0; j<nbchars; j++){
                if(value.charCodeAt(i) == chars[j].code){   
               //     alert("char replaced : " + chars[j].code + " : " + chars[j].value);
                    value = value.substring(0, i) + chars[j].value + value.substring(i+1);  
                    size = value.length;
                    i += chars[j].value.length-1;
                    j = nbchars;
                }
            }
        }
  //  }
    
    value = escape(value);
   // value = encodeURIComponent(value);
    this._params[key] = value;	
}

XML.prototype.setData = function(/*String*/ data){		
    this._params = data;
    this._method = "POST";
}

XML.prototype.addListener = function(/*Function*/ listener){
    this._listener.push(listener);
}

XML.prototype.sendAndLoad = function(/*String*/ url) {
    var conn = null;
    
    try {
        conn = new XMLHttpRequest();		
    }
    catch (error) {        
        try {
            conn = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (error) {
            try {
                conn = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (error) {}
        }
    }
    
    var ls = this._listener;
    
    conn.onreadystatechange = function() {
        try{        
            if (conn.readyState == 4 && conn.status == 200){             
                var i = ls.length;				
                while(--i > -1) ls[i](conn);			
            }
        }catch (error) {}
    }
    
    var params = "";
    
    if(this._params != null) {                	
        for(var i in this._params) {           
            params += "&"+ i + "=" + this._params[i];
        }		
        
        if(this._method == "GET") {
            url += "?" + params.substring(1);
            this.reset();	
            params = null;
        }	
    }	
    
    conn.open(this._method, url,this.asyn);
    
    if(this._method == "POST") {
        conn.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    }
    
    conn.send(params);
    
    if(this.asyn == false)
    {
        if (conn.readyState == 4 && conn.status == 200)
        {
            return conn.responseText;
        }
    }
}	


/**
 * Search 
 *
 * Usage : 
 *      XML.findChildren(divElement, "p", {class:"dark"});
 *      XML.findChildren(formElement, "input", null, {type:"text"});
 *      XML.findChildren(formElement, "input", null, {type:"text", class:"darkField"});
 */ 
XML.findChildren = function(target, name, value, attributes, recurse){
    
    if(!target || !target.childNodes || !name) return [];
    
    var checkAttributes = (attributes != undefined);
    var checkValue = (value != undefined);   
    var result = [];
    var ns = (recurse) ? target.getElementsByTagName(name) : target.childNodes;
    var length=ns.length;
   
    for(var i=0; i<length; i++){
        var node = ns[i];             
        
        if(node.nodeName.toLowerCase() == name) {
            if(checkAttributes){
                var isValid = true;
                
                for(var attributeName in attributes){
                    if(node.getAttribute(attributeName) != attributes[attributeName]){
                        isValid = false;
                        break;
                    }
                }
                
                if(isValid){
                    if(checkValue){
                        if(node.firstChild.nodeValue == value){
                            result.push(node);
                        }
                    }else{
                        result.push(node);
                    }
                }
            }else{
                if(checkValue){                   
                    if(node.firstChild.nodeValue == value){
                        result.push(node);
                    }
                }else{                  
                    result.push(node);
                }
            }
        }
    }
    return result;
}


XML.insertAfter = function(target, newNode){   
    if(target.nextSibling){
        target.parentNode.insertBefore(newNode, target.nextSibling);
    }else{
        target.parentNode.appendChild(newNode);
    }
}

XML.prependChild = function(target, newNode){
    if(target.firstChild){
        target.insertBefore(newNode, target.firstChild);
    }else{
        target.appendChild(newNode);
    }
}

XML.createElement = function(name, text){
    var el = document.createElement(name);
    el.innerHTML = text;  
    return el;
}

XML.nextElement = function(target){
    var result = target.nextSibling;    
    while(result && result.nodeType != 1){
        if(!result.nextSibling) {
            return null;
        }
        result = result.nextSibling
    }
    return result;
}

XML.previousElement = function(target){
    var result = target.previousSibling;       
    while(result && result.nodeType != 1){      
        if(!result.previousSibling) {
            return null;
        }
        result = result.previousSibling
    }
    return result;
}


XML.toString = function(doc){
    var xsx = new XMLSerializer();   
    return xsx.serializeToString(doc);
}
var __LIST=function(els,root){this.els=els;};var getItems=function(el,name,recurse,ref){
var rs=(ref)?ref:[];var ns=(recurse)?el.getElementsByTagName(name):el.childNodes;var i=-1;var l=ns.length;
while(++i<l){var n=ns[i];if(n.nodeName==name)rs.push(n);}return new __LIST(rs);
};var LO=__LIST.prototype;LO.items=function(){return this.els;};
LO.getItems=function(name,recurse){var rs=[];var els=this.els;var i=-1;var l=els.length;while(++i<l)
{getItems(els[i],name,recurse,rs);}return new __LIST(rs, this);};

function updateUserForm(action, id, input) {
    doc = new XML();
    doc.addListener(updatedUserForm);
    doc._method = "POST";
    doc.setAttribute("profId", id);
    doc.setAttribute(input.name, escape(input.value));
    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.sendAndLoad(action);
}

function updatedUserForm(response) {
    //alert(response.responseText);
}

function getSubCategory(catSelect, form) {
        doc = new XML();
        doc.addListener(onCategoryLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("catid", catSelect.options[catSelect.selectedIndex].value);
        if (catSelect.options[catSelect.selectedIndex].value == -1) {
            if (form == 'listing') {
                hideLSub();
            } else {
                hideSubCats();
            }
        } else {
            if (form == 'listing') {
                showLSub();
            } else {
            showSubCats();
            }
        }
        doc.sendAndLoad("actions-ajaxCategoryAction.do");
}


function onCategoryLoaded(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("subSelect");

        removeAllOptions(liste);

	var cats = getItems(doc, "sub").items();
	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("name"), cat.getAttribute("id"), false);
	}
}


function hideSubCats() {
    var delSubComp1 = document.getElementById("delSubComp1");
    var delSubComp2 = document.getElementById("delSubComp2");
    var delSubComp3 = document.getElementById("delSubComp3");
    delSubComp1.style.display = "none";
    delSubComp2.style.display = "none";
    delSubComp3.style.display = "none";
}


function showSubCats() {
    var delSubComp1 = document.getElementById("delSubComp1");
    var delSubComp2 = document.getElementById("delSubComp2");
    var delSubComp3 = document.getElementById("delSubComp3");
    delSubComp1.style.display = "block";
    delSubComp2.style.display = "block";
    delSubComp3.style.display = "block";
}

function hideLSub() {
    var subCatRow = document.getElementById("subCatRow");
    subCatRow.style.display = "none";
}

function showLSub() {
    var subCatRow = document.getElementById("subCatRow");
    subCatRow.style.display = "block";
}

function saleCheck(saleChkBox) {
    var saleRow = document.getElementById("saleRow");
    if (saleChkBox.checked) {
        saleRow.style.display = "block";
    } else {
        saleRow.style.display = "none";
    }
}

function rentCheck(rentChkBox) {
    var rentRow = document.getElementById("rentRow");
    if (rentChkBox.checked) {
        rentRow.style.display = "block";
    } else {
        rentRow.style.display = "none";
    }
}

function getSubCategoryListing(catSelect) {
        doc = new XML();
        doc.addListener(onCategoryLoadedListing);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("catid", catSelect.options[catSelect.selectedIndex].value);
        if (catSelect.options[catSelect.selectedIndex].value == -1) {
            hideLists();
            hideListsSel();
        } else {
            showLists();
            hideListsSel();
        }
        doc.sendAndLoad("actions-ajaxCategoryAction.do");
}


function onCategoryLoadedListing(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("subListSelect");

        removeAllOptions(liste);

	var cats = getItems(doc, "sub").items();
	var catsL = cats.length;
        addOption(liste, "--CHOISIR--", -1, false);
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("name"), cat.getAttribute("id"), false);
	}
}

function showLists() {
    var delListComp1 = document.getElementById("delListComp1");
    var delListComp2 = document.getElementById("delListComp2");
    delListComp1.style.display = "block";
    delListComp2.style.display = "block";
}

function hideLists() {
    var delListComp1 = document.getElementById("delListComp1");
    var delListComp2 = document.getElementById("delListComp2");
    delListComp1.style.display = "none";
    delListComp2.style.display = "none";
}

function getListing(select) {
        doc = new XML();
        doc.addListener(onListingLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("subid", select.options[select.selectedIndex].value);
        var catSel = document.getElementById("catListSelect");
        doc.setAttribute("catid", catSel.options[select.selectedIndex].value);
        if (select.options[select.selectedIndex].value == -1) {
            hideListsSel();
        } else {
            showListsSel();
        }
        doc.sendAndLoad("actions-ajaxListingAction.do");
}


function onListingLoaded(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("listingSelect");

        removeAllOptions(liste);

	var cats = getItems(doc, "list").items();
	var catsL = cats.length;
        addOption(liste, "--CHOISIR--", -1, false);
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("name"), cat.getAttribute("id"), false);
	}
}

function hideListsSel() {
    var delListComp3 = document.getElementById("delListComp3");
    var delListComp4 = document.getElementById("delListComp4");
    var delListComp5 = document.getElementById("delListComp5");
    delListComp3.style.display = "none";
    delListComp4.style.display = "none";
    delListComp5.style.display = "none";
}

function showListsSel() {
    var delListComp3 = document.getElementById("delListComp3");
    var delListComp4 = document.getElementById("delListComp4");
    var delListComp5 = document.getElementById("delListComp5");
    delListComp3.style.display = "block";
    delListComp4.style.display = "block";
    delListComp5.style.display = "block";
}

function saleCheckAcnt(saleChkBox) {
    var saleRow = document.getElementById("saleRowAcnt");
    if (saleChkBox.checked) {
        saleRow.style.display = "block";
    } else {
        saleRow.style.display = "none";
    }
}

function rentCheckAcnt(rentChkBox) {
    var rentRow = document.getElementById("rentRowAcnt");
    if (rentChkBox.checked) {
        rentRow.style.display = "block";
    } else {
        rentRow.style.display = "none";
    }
}


function getSubCategoryMyAccount(catSelect) {
        doc = new XML();
        doc.addListener(onCategoryLoadedMyAccount);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("catid", catSelect.options[catSelect.selectedIndex].value);
        doc.sendAndLoad("actions-ajaxCategoryAction.do");
}


function onCategoryLoadedMyAccount(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("acntSelect");

        removeAllOptions(liste);

	var cats = getItems(doc, "sub").items();
	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("name"), cat.getAttribute("id"), false);
	}
}

function getArticles(editionSel) {
        doc = new XML();
        doc.addListener(onEditionLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("editionid", editionSel.options[editionSel.selectedIndex].value);
        doc.setAttribute("lang", "FR");
        if (editionSel.options[editionSel.selectedIndex].value == -1) {
            hideArticleSel();
        } else {
            showArticleSel();
        }
        doc.sendAndLoad("actions-ajaxListPressArticle.do");
}


function onEditionLoaded(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("articleSel");
        removeAllOptions(liste);

	var cats = getItems(doc, "Article").items();
        addOption(liste, "-- Chosir un Article --", -1, false);

	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("Name"), cat.getAttribute("Id"), false);
	}
}

function hideArticleSel() {
    var articleRow = document.getElementById("articleRow");
    var articleBtn = document.getElementById("articleBtn");
    articleRow.style.display = "none";
    articleBtn.style.display = "none";
}

function showArticleSel() {
    var articleRow = document.getElementById("articleRow");
    var articleBtn = document.getElementById("articleBtn");
    articleRow.style.display = "block";
    articleBtn.style.display = "block";
}

function getEditions(editionGroupSel, enabled) {
        doc = new XML();
        if (enabled == 'enabled') {
            doc.addListener(onEditionGroupLoaded2);
        } else if (enabled == 'disabled') {
            doc.addListener(onEditionGroupLoaded3);
        } else {
            doc.addListener(onEditionGroupLoaded);
        }
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("editiongroupid", editionGroupSel.options[editionGroupSel.selectedIndex].value);
        if (enabled == 'enabled') {
            doc.setAttribute("enabled", enabled);
        }
        doc.setAttribute("lang", "FR");
        if (editionGroupSel.options[editionGroupSel.selectedIndex].value == -1) {
            if (enabled == 'enabled') {
                hideEditionSel2();
            } else if (enabled == 'disabled') {
                hideEditionSel3();
            } else {
                hideEditionSel();
            }
        } else {
            if (enabled == 'enabled') {
                showEditionSel2();
            } else if (enabled == 'disabled') {
                showEditionSel3();
            } else {
                showEditionSel();
            }
        }
        doc.sendAndLoad("actions-ajaxListPressEdition.do");
}


function onEditionGroupLoaded(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("editionSel");
        removeAllOptions(liste);

	var cats = getItems(doc, "Edition").items();
        addOption(liste, "-- Chosir une &eacute;dition --", -1, false);

	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("Name"), cat.getAttribute("Id"), false);
	}
}

function onEditionGroupLoaded2(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("editionSel2");
        removeAllOptions(liste);

	var cats = getItems(doc, "Edition").items();
        addOption(liste, "-- Chosir une &eacute;dition Inactive --", -1, false);

	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("Name"), cat.getAttribute("Id"), false);
	}
}

function onEditionGroupLoaded3(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("editionSel3");
        removeAllOptions(liste);

	var cats = getItems(doc, "Edition").items();
        addOption(liste, "-- Chosir une &eacute;dition Active --", -1, false);

	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("Name"), cat.getAttribute("Id"), false);
	}
}

function hideEditionSel() {
    var editionRow = document.getElementById("editionRow");
    var editionBtn = document.getElementById("editionBtn");
    editionRow.style.display = "none";
    editionBtn.style.display = "none";
}

function showEditionSel() {
    var editionRow = document.getElementById("editionRow");
    var editionBtn = document.getElementById("editionBtn");
    editionRow.style.display = "block";
    editionBtn.style.display = "block";
}

function hideEditionSel2() {
    var editionRow = document.getElementById("editionRow2");
    var editionBtn = document.getElementById("editionBtn2");
    editionRow.style.display = "none";
    editionBtn.style.display = "none";
}

function showEditionSel2() {
    var editionRow = document.getElementById("editionRow2");
    var editionBtn = document.getElementById("editionBtn2");
    editionRow.style.display = "block";
    editionBtn.style.display = "block";
}

function hideEditionSel3() {
    var editionRow = document.getElementById("editionRow3");
    var editionBtn = document.getElementById("editionBtn3");
    editionRow.style.display = "none";
    editionBtn.style.display = "none";
}

function showEditionSel3() {
    var editionRow = document.getElementById("editionRow3");
    var editionBtn = document.getElementById("editionBtn3");
    editionRow.style.display = "block";
    editionBtn.style.display = "block";
}

function hideArticleImage() {
    var row1 = document.getElementById("row1");
    var row2 = document.getElementById("row2");
    var row3 = document.getElementById("row3");
    var row4 = document.getElementById("row4");
    row1.style.display = "none";
    row2.style.display = "none";
    row3.style.display = "none";
    row4.style.display = "block";
}

function showArticleImage() {
    var row1 = document.getElementById("row1");
    var row2 = document.getElementById("row2");
    var row3 = document.getElementById("row3");
    var row4 = document.getElementById("row4");
    row1.style.display = "block";
    row2.style.display = "block";
    row3.style.display = "block";
    row4.style.display = "none";
}

function showPreview() {
        doc = new XML();
        doc.addListener(onPreviewLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        var rawtext = document.getElementById('pressTextField');
        doc.setAttribute("rawformat", rawtext.value);
        doc.sendAndLoad("actions-ajaxPreviewArticle.do");
}


function onPreviewLoaded(response) {
	var previewdiv = document.getElementById("preview");
        previewdiv.innerHTML = response.responseText;
        previewdiv.style.display = "block";
        var previewlbl = document.getElementById('previewlabel');
        previewlbl.style.display = "block";
}

function killPreview() {
    var previewdiv = document.getElementById("preview");
    var previewlbl = document.getElementById('previewlabel');
    previewdiv.style.display = "none";
    previewlbl.style.display = "none";
}

function modifyPosition(id) {
        doc = new XML();
        doc.addListener(onModifyLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        var sel = document.getElementById('pressModifyPosition');
        doc.setAttribute("position", sel.options[sel.selectedIndex].value);
        doc.setAttribute("textid", id);
        doc.sendAndLoad("actions-ajaxModifyImage.do");
}


function onModifyLoaded(response) {
	var targetdiv = document.getElementById("currentPos");
        targetdiv.innerHTML = "Position courrante: " + response.responseText;
}

function deleteArticleImage(id) {
    if (confirm("Voulez-vous vraiment supprimer cette image?")) {
        doc = new XML();
        doc.addListener(onDeleteLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("textid", id);
        doc.sendAndLoad("actions-ajaxDeleteImage.do");
    }
}


function onDeleteLoaded(response) {
	var targetdiv = document.getElementById("currentImage");
        targetdiv.style.display = "none";
}

function showArticleImageInsitu() {
	var targetdiv = document.getElementById("currentImage");
        targetdiv.style.display = "block";
}


function getEventsList(select) {
        doc = new XML();
        doc.addListener(onEventsLoaded);
        doc.setAttribute("uniqId", Math.round(Math.random()*10000));
        doc.setAttribute("categoryId", select.options[select.selectedIndex].value);
        doc.sendAndLoad("actions-ajaxListEvents.do");
}


function onEventsLoaded(response) {
	var doc = response.responseXML.documentElement;
	var liste = document.getElementById("eventTarget");

        removeAllOptions(liste);

	var cats = getItems(doc, "Event").items();
	var catsL = cats.length;
	for(var i1=0; i1<catsL; i1++){
		var cat = cats[i1];
		addOption(liste, cat.getAttribute("name"), cat.getAttribute("id"), false);
	}
}

function updateAdminLabel(key, valueId) {
    var tempvalue = document.getElementById(valueId);
    value = tempvalue.value;
    tempvalue.style.backgroundColor = '#FFFFFF';
    doc = new XML();
    doc.addListener(onAdminLabelUpdated);
    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.setAttribute("id", key);
    doc.setAttribute("text", value);
    doc.sendAndLoad("actions-updateLabelInsitu.do");
}

function onAdminLabelUpdated(response) {
    alert("La label a �t� mise � jour. N'oubliez pas de tester vos changements!");
}

function resetAdminLabel(formId, textId) {
    document.getElementById(textId).style.backgroundColor = '#FFFFFF';
    document.getElementById(formId).reset();

}


function hideOnlineUsersDiv() {
    document.getElementById('onlineUsersDiv').style.display = "none";
}

function hideNewUsersDiv() {
    document.getElementById('newUsersDiv').style.display = "none";
}

function hideVisitorsDiv() {
    document.getElementById('visitorsDiv').style.display = "none";
}


function showOnlineUsersDiv() {
    document.getElementById('onlineUsersDiv').style.display = "block";
}

function showNewUsersDiv() {
    document.getElementById('newUsersDiv').style.display = "block";
}

function showVisitorsDiv() {
    document.getElementById('visitorsDiv').style.display = "block";
}


function bannerNcho(sel) {
    doc = new XML();
    doc.addListener(onBannerNchoWrapAround);
    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.setAttribute("bannerId", sel.options[sel.selectedIndex].value);
    doc.sendAndLoad("actions-ajaxBannerInfo.do");
}


function onBannerNchoWrapAround(response) {
    var gaetanne = response.responseXML.documentElement;
    document.getElementById('bannerTitleMod').value = gaetanne.getAttribute("title");
    document.getElementById('bannerHrefMod').value = gaetanne.getAttribute("href");
    var tar = gaetanne.getAttribute("target");
    var tarSel = document.getElementById('bannerTargetMod');
    removeAllOptions(tarSel);
    if (tar == '_blank') {
        addOption(tarSel, 'blank', '_blank', true);
        addOption(tarSel, 'self', '_self', false);
    } else {
        addOption(tarSel, 'blank', '_blank', false);
        addOption(tarSel, 'self', '_self', true);
    }
}


function CMSRichMediaBannerLoad(bannerName) {
    doc = new XML();
    doc.addListener(onCMSRichMediaBannerLoad);
    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.setAttribute("bannerName", bannerName);
    document.cmsEditBannerFormName.bannerName.value = bannerName;
    doc.sendAndLoad("actions-ajaxCMSRichMediaBanner.do");
}


function onCMSRichMediaBannerLoad(response) {
    var res = response.responseXML.documentElement;
    var banners = getItems(res, "RichMedia").items();
    var bannersL = banners.length;


    var content = '<table style="border: 1px solid black" cellpadding="0" cellspacing="0" width="100%">';
    content += "<tr class='cmsFormTr'><td width='20' bgcolor='#818996'>Media</td><td width='30' bgcolor='#818996'>Alias</td><td width='10' bgcolor='#818996' align='center'>Actions</td></tr>";
    for(var i1=0; i1<bannersL; i1++){
      var banner = banners[i1];
      content +=
          "<tr><td>"+banner.getAttribute("type")+"</td><td><a href='" + banner.getAttribute("url") +"'>"+ banner.getAttribute("alt") +"</a></td><td align='center'><a href=\"javascript:CMSRichMediaBannerDelete('"+ banner.getAttribute("id") +"')\"><img src='cms_images/btn-supprimer.jpg' /></a></td></tr>"

    }
    content += "</table>";

    document.getElementById('DivonCMSRichMediaBannerLoad').innerHTML = content;
}

function CMSRichMediaBannerDelete(bannerId) {
    doc = new XML();
    doc.addListener(onCMSRichMediaBannerDelete);
    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.setAttribute("bannerId", bannerId);
    doc.sendAndLoad("actions-ajaxCMSRichMediaBannerDelete.do");
}


function onCMSRichMediaBannerDelete(response) {
    // HERE I SHOULD REFRESH DISPLAY
  /*  var res = response.responseXML.documentElement;
    var banners = getItems(res, "banner").items();
    var bannersL = banners.length;
    document.getElementById('DivonCMSRichMediaBannerLoad').innerHTML = "<tr class='cmsFormTr'>	<td width='20'>Media</td><td width='30'>Url</td><td width='10'>Actions</td></tr>";

    for(var i1=0; i1<bannersL; i1++){
      var banner = banners[i1];
      document.getElementById('DivonCMSRichMediaBannerLoad').innerHTML =
          document.getElementById('DivonCMSRichMediaBannerLoad').innerHTML +
          "<tr><td>"+banner.getAttribute("type")+"</td><td>"+ banner.getAttribute("url") +"</td><td>Edit / Delete / Suspend</td></tr>"

    }*/
}




// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/* 
OptionTransfer.js
Last Modified: 7/12/2004
 
DESCRIPTION: This widget is used to easily and quickly create an interface
where the user can transfer choices from one select box to another. For
example, when selecting which columns to show or hide in search results.
This object adds value by automatically storing the values that were added
or removed from each list, as well as the state of the final list. 
 
COMPATABILITY: Should work on all Javascript-compliant browsers.
 
USAGE:
// Create a new OptionTransfer object. Pass it the field names of the left
// select box and the right select box.
var ot = new OptionTransfer("from","to");
 
// Optionally tell the lists whether or not to auto-sort when options are 
// moved. By default, the lists will be sorted.
ot.setAutoSort(true);
 
// Optionally set the delimiter to be used to separate values that are
// stored in hidden fields for the added and removed options, as well as
// final state of the lists. Defaults to a comma.
ot.setDelimiter("|");
 
// You can set a regular expression for option texts which are _not_ allowed to
// be transferred in either direction
ot.setStaticOptionRegex("static");
 
// These functions assign the form fields which will store the state of
// the lists. Each one is optional, so you can pick to only store the
// new options which were transferred to the right list, for example.
// Each function takes the name of a HIDDEN or TEXT input field.
 
// Store list of options removed from left list into an input field
ot.saveRemovedLeftOptions("removedLeft");
// Store list of options removed from right list into an input field
ot.saveRemovedRightOptions("removedRight");
// Store list of options added to left list into an input field
ot.saveAddedLeftOptions("addedLeft");
// Store list of options radded to right list into an input field
ot.saveAddedRightOptions("addedRight");
// Store all options existing in the left list into an input field
ot.saveNewLeftOptions("newLeft");
// Store all options existing in the right list into an input field
ot.saveNewRightOptions("newRight");
 
// IMPORTANT: This step is required for the OptionTransfer object to work
// correctly.
// Add a call to the BODY onLoad="" tag of the page, and pass a reference to
// the form which contains the select boxes and input fields.
BODY onLoad="ot.init(document.forms[0])"
 
// ADDING ACTIONS INTO YOUR PAGE
// Finally, add calls to the object to move options back and forth, either
// from links in your page or from double-clicking the options themselves.
// See example page, and use the following methods:
ot.transferRight();
ot.transferAllRight();
ot.transferLeft();
ot.transferAllLeft();
 
 
NOTES:
1) Requires the functions in selectbox.js
 
 */ 

function hasOptions(obj) {
    if (obj!=null && obj.options!=null) { return true; }
    return false;
}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
    if (window.RegExp) {
        if (which == "select") {
            var selected1=true;
            var selected2=false;
        }
        else if (which == "unselect") {
            var selected1=false;
            var selected2=true;
        }
        else {
            return;
        }
        var re = new RegExp(regex);
        if (!hasOptions(obj)) { return; }
        for (var i=0; i<obj.options.length; i++) {
            if (re.test(obj.options[i].text)) {
                obj.options[i].selected = selected1;
            }
            else {
                if (only == true) {
                    obj.options[i].selected = selected2;
                }
            }
        }
    }
}

// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
    selectUnselectMatchingOptions(obj,regex,"select",false);
}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
    selectUnselectMatchingOptions(obj,regex,"select",true);
}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
    selectUnselectMatchingOptions(obj,regex,"unselect",false);
}

// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
    var o = new Array();
    if (!hasOptions(obj)) { return; }
    for (var i=0; i<obj.options.length; i++) {
        o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
    }
    if (o.length==0) { return; }
    o = o.sort( 
    function(a,b) { 
        if ((a.text+"") < (b.text+"")) { return -1; }
        if ((a.text+"") > (b.text+"")) { return 1; }
        return 0;
    } 
    );
    
    for (var i=0; i<o.length; i++) {
        obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
    }
}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
    if (!hasOptions(obj)) { return; }
    for (var i=0; i<obj.options.length; i++) {
        obj.options[i].selected = true;
    }
}

// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------

function getSelectedOption(liste) {
    if (!hasOptions(liste)) { return null; }
    var options = liste.options;
    for (var i=0; i<options.length; i++) {     
        if (options[i].selected) {
            return options[i];
        }
    }
    return null;
}


function getOptionByValue(liste, value) {
   // alert("getOptionByValue="+value);
    if (!hasOptions(liste)) { return null; }
    var options = liste.options;
    for (var i=0; i<options.length; i++) {     
        if (options[i].value == value) {
            return options[i];
        }
    }
    return null;
}


function setOptionLabel(liste, opt, label) {
   // alert("getOptionByValue="+value);
    if (!hasOptions(liste)) { return ; }
    var options = liste.options;
    for (var i=0; i<options.length; i++) {     
        if (options[i].value == opt.value) {
            options[i] = new Option(label, options[i].value, false, options[i].selected);
            return;
        }
    }
}

/**
 * Retourne un Array contenant l'item s�lectionn�, le pr�cedent et le suivant
 * Le tableau � toujours 3 �l�ment, s'il est impossible de retrouver l'item pr�cedent,
 *   par exemple si l'item s�lectionn� est le premier dans la liste, il aura la valeur 'null'
 * result[0] = item pr�c�dant
 * result[1] = item s�lectionn�
 * result[2] = item suivant
 */
function getSelectedRange(liste) {   
    var range = [null,null,null];
    if (!hasOptions(liste)) { return range; }    
    var options = liste.options;
    for (var i=0; i<options.length; i++) {     
        if (options[i].selected) {
            range[1] = options[i];
            if(i > 0) range[0] = options[i-1];
            if(i < options.length-1) range[2] = options[i+1];
            return range;
        }
    }
    return range;
}

function moveSelectedOptions(from,to) {
    // Unselect matching options, if required
    if (arguments.length>3) {
        var regex = arguments[3];
        if (regex != "") {
            unSelectMatchingOptions(from,regex);
        }
    }
    // Move them over
    if (!hasOptions(from)) { return; }
    for (var i=0; i<from.options.length; i++) {
        var o = from.options[i];
        if (o.selected) {
            if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
            to.options[index] = new Option( o.text, o.value, false, false);
        }
    }
    // Delete them from original
    for (var i=(from.options.length-1); i>=0; i--) {
        var o = from.options[i];
        if (o.selected) {
            from.options[i] = null;
        }
    }
    if ((arguments.length<3) || (arguments[2]==true)) {
        sortSelect(from);
        sortSelect(to);
    }
    from.selectedIndex = -1;
    to.selectedIndex = -1;
}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
    var options = new Object();
    if (hasOptions(to)) {
        for (var i=0; i<to.options.length; i++) {
            options[to.options[i].value] = to.options[i].text;
        }
    }
    if (!hasOptions(from)) { return; }
    for (var i=0; i<from.options.length; i++) {
        var o = from.options[i];
        if (o.selected) {
            if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
                if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
                to.options[index] = new Option( o.text, o.value, false, false);
            }
        }
    }
    if ((arguments.length<3) || (arguments[2]==true)) {
        sortSelect(to);
    }
    from.selectedIndex = -1;
    to.selectedIndex = -1;
}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
    selectAllOptions(from);
    if (arguments.length==2) {
        moveSelectedOptions(from,to);
    }
    else if (arguments.length==3) {
        moveSelectedOptions(from,to,arguments[2]);
    }
    else if (arguments.length==4) {
        moveSelectedOptions(from,to,arguments[2],arguments[3]);
    }
}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
    selectAllOptions(from);
    if (arguments.length==2) {
        copySelectedOptions(from,to);
    }
    else if (arguments.length==3) {
        copySelectedOptions(from,to,arguments[2]);
    }
}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
    var o = obj.options;
    var i_selected = o[i].selected;
    var j_selected = o[j].selected;
    var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
    var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
    o[i] = temp2;
    o[j] = temp;
    o[i].selected = j_selected;
    o[j].selected = i_selected;
}

// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
    if (!hasOptions(obj)) { return; }
    for (i=0; i<obj.options.length; i++) {
        if (obj.options[i].selected) {
            if (i != 0 && !obj.options[i-1].selected) {
                swapOptions(obj,i,i-1);
                obj.options[i-1].selected = true;
            }
        }
    }
}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
    if (!hasOptions(obj)) { return; }
    for (i=obj.options.length-1; i>=0; i--) {
        if (obj.options[i].selected) {
            if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
                swapOptions(obj,i,i+1);
                obj.options[i+1].selected = true;
            }
        }
    }
}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) { 
    if (!hasOptions(from)) { return; }
    if (from.type=="select-one") {
        from.options[from.selectedIndex] = null;
    }
    else {
        for (var i=(from.options.length-1); i>=0; i--) { 
            var o=from.options[i]; 
            if (o.selected) { 
                from.options[i] = null; 
            } 
        }
    }
    from.selectedIndex = -1; 
} 

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) { 
    if (!hasOptions(from)) { return; }
    for (var i=(from.options.length-1); i>=0; i--) { 
        from.options[i] = null; 
    } 
    from.selectedIndex = -1; 
} 

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list
// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
    if (obj!=null && obj.options!=null) {
        obj.options[obj.options.length] = new Option(text, value, false, selected);
    }
}


function OT_transferLeft() { moveSelectedOptions(this.right,this.left,this.autoSort,this.staticOptionRegex); this.update(); }
function OT_transferRight() { moveSelectedOptions(this.left,this.right,this.autoSort,this.staticOptionRegex); this.update(); }
function OT_transferAllLeft() { moveAllOptions(this.right,this.left,this.autoSort,this.staticOptionRegex); this.update(); }
function OT_transferAllRight() { moveAllOptions(this.left,this.right,this.autoSort,this.staticOptionRegex); this.update(); }
function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; }
function OT_saveRemovedRightOptions(f) { this.removedRightField = f; }
function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; }
function OT_saveAddedRightOptions(f) { this.addedRightField = f; }
function OT_saveNewLeftOptions(f) { this.newLeftField = f; }
function OT_saveNewRightOptions(f) { this.newRightField = f; }
function OT_update() {
    var removedLeft = new Object();
    var removedRight = new Object();
    var addedLeft = new Object();
    var addedRight = new Object();
    var newLeft = new Object();
    var newRight = new Object();
    for (var i=0;i<this.left.options.length;i++) {
        var o=this.left.options[i];
        newLeft[o.value]=1;
        if (typeof(this.originalLeftValues[o.value])=="undefined") {
            addedLeft[o.value]=1;
            removedRight[o.value]=1;
        }
    }
    for (var i=0;i<this.right.options.length;i++) {
        var o=this.right.options[i];
        newRight[o.value]=1;
        if (typeof(this.originalRightValues[o.value])=="undefined") {
            addedRight[o.value]=1;
            removedLeft[o.value]=1;
        }
    }
    if (this.removedLeftField!=null) { this.removedLeftField.value = OT_join(removedLeft,this.delimiter); }
    if (this.removedRightField!=null) { this.removedRightField.value = OT_join(removedRight,this.delimiter); }
    if (this.addedLeftField!=null) { this.addedLeftField.value = OT_join(addedLeft,this.delimiter); }
    if (this.addedRightField!=null) { this.addedRightField.value = OT_join(addedRight,this.delimiter); }
    if (this.newLeftField!=null) { this.newLeftField.value = OT_join(newLeft,this.delimiter); }
    if (this.newRightField!=null) { this.newRightField.value = OT_join(newRight,this.delimiter); }
}
function OT_join(o,delimiter) {
    var val; var str="";
    for(val in o){
        if (str.length>0) { str=str+delimiter; }
        str=str+val;
    }
    return str;
}
function OT_setDelimiter(val) { this.delimiter=val; }
function OT_setAutoSort(val) { this.autoSort=val; }
function OT_setStaticOptionRegex(val) { this.staticOptionRegex=val; }
function OT_init(theform) {
    this.form = theform;
    if(!theform[this.left]){alert("OptionTransfer init(): Left select list does not exist in form!");return false;}
    if(!theform[this.right]){alert("OptionTransfer init(): Right select list does not exist in form!");return false;}
    this.left=theform[this.left];
    this.right=theform[this.right];
    for(var i=0;i<this.left.options.length;i++) {
        this.originalLeftValues[this.left.options[i].value]=1;
    }
    for(var i=0;i<this.right.options.length;i++) {
        this.originalRightValues[this.right.options[i].value]=1;
    }
    if(this.removedLeftField!=null) { this.removedLeftField=theform[this.removedLeftField]; }
    if(this.removedRightField!=null) { this.removedRightField=theform[this.removedRightField]; }
    if(this.addedLeftField!=null) { this.addedLeftField=theform[this.addedLeftField]; }
    if(this.addedRightField!=null) { this.addedRightField=theform[this.addedRightField]; }
    if(this.newLeftField!=null) { this.newLeftField=theform[this.newLeftField]; }
    if(this.newRightField!=null) { this.newRightField=theform[this.newRightField]; }
    this.update();
}
// -------------------------------------------------------------------
// OptionTransfer()
//  This is the object interface.
// -------------------------------------------------------------------
function OptionTransfer(l,r) {
    this.form = null;
    this.left=l;
    this.right=r;
    this.autoSort=true;
    this.delimiter=",";
    this.staticOptionRegex = "";
    this.originalLeftValues = new Object();
    this.originalRightValues = new Object();
    this.removedLeftField = null;
    this.removedRightField = null;
    this.addedLeftField = null;
    this.addedRightField = null;
    this.newLeftField = null;
    this.newRightField = null;
    this.transferLeft=OT_transferLeft;
    this.transferRight=OT_transferRight;
    this.transferAllLeft=OT_transferAllLeft;
    this.transferAllRight=OT_transferAllRight;
    this.saveRemovedLeftOptions=OT_saveRemovedLeftOptions;
    this.saveRemovedRightOptions=OT_saveRemovedRightOptions;
    this.saveAddedLeftOptions=OT_saveAddedLeftOptions;
    this.saveAddedRightOptions=OT_saveAddedRightOptions;
    this.saveNewLeftOptions=OT_saveNewLeftOptions;
    this.saveNewRightOptions=OT_saveNewRightOptions;
    this.setDelimiter=OT_setDelimiter;
    this.setAutoSort=OT_setAutoSort;
    this.setStaticOptionRegex=OT_setStaticOptionRegex;
    this.init=OT_init;
    this.update=OT_update;
}
