/*global GLOBADMEDIA, console */
window.GLOBADMEDIA = window.GLOBADMEDIA || {};

GLOBADMEDIA = function(){
    var that = {},          //pour acceder aux variables et methodes globales
    
    debug = true,       // pour le debogage
    log   = function(){ if( console && debug && console.log  ){ console.log.apply(null, arguments);  } },
    info  = function(){ if( console && debug && console.info ){ console.info.apply(null, arguments); } },
    warn  = function(){ if( console && debug && console.warn ){ console.warn.apply(null, arguments); } },
    error = function(){ if( console && debug && console.error){ console.error.apply(null, arguments);} },
    dir   = function(){ if( console && debug && console.dir  ){ console.dir.apply(null, arguments);  } },
    
    fld,                // Noeud DOM du champs de recherche
    sInp   = "",        // chaine actuellement tapee dans le champs de recherche
    nInpC  = 0,         // nombre de caracteres de cette chaine
    aSug   = [],        // liste des suggestion actuellement affichées ?
    suggestCache = [],
    iHigh  = 0,         // Suggestion actuellement mise en valeur (highlighted)
    
    ajID,               // ID du timeout pour l'envoi de la requete de suggestions
    
    head,               // balise head de la page web, ou inserer le JS
    
    idAs,               // id de l'element HTML d'autosuggestions
    
    oP,                 // Parametres
    
    def = {             // Valeurs par defaut des parametres
        baseUrl : "http://api.globadmedia.com",
        minchars:2,
        className:"autosuggest",
        timeout:2500,
        delay:50,
        offsety:0,
        json: true,
        minWidth: 200,
        shownoresults: false,
        maxheight: 250,
        cache: true,
        maxentries: 10,
        idx:0
    },
    
    getSuggestions = function (val){
        var ol, l, i, arr, input;
        // if input stays the same, do nothing
        if (val == sInp){ return 0; }
        sInp = val;
        
        // kill list. TODO : ne pas supprimer la liste, mais filtrer en arriere en remettant les resultats du cache
        //GLOBADMEDIA.DOM.remE(idAs);
        
        // input length is less than the min required to trigger a request : do nothing
        if (val.length < oP.minchars) {
            GLOBADMEDIA.DOM.remE(idAs);
            aSug = [];
            nInpC = val.length;
            return 0;
        }
        
        // maj du nb de caracteres tapes
        ol = nInpC; // old length
        nInpC = (val && val.length) || 0;
        
        
        l = aSug.length;
        if (nInpC > ol && l && l < oP.maxentries && oP.cache){
            // if caching enabled, and user is typing (ie. length of input is increasing) filter results out of aSuggestions from last request
            // TODO : afficher quand meme les resultats supplementaires quand ils arrivent
            arr = [];
            for (i=0;i<l;i++){
                if (aSug[i].value.substr(0,val.length).toLowerCase() === val.toLowerCase()){ arr.push( aSug[i] ); }
            }
            aSug = arr;
            createList(aSug);
            return false;
        }
        
        // faire la requete pour avoir de nouvelles suggestions
        input = sInp;
        clearTimeout(ajID);
        ajID = setTimeout( function() { doAjaxRequest(input); }, oP.delay );
        
        refreshBox();
        return false;
    },
    
    doAjaxRequest = function (input){
        var url, script_tag;
        // check that saved input is still the value of the field
        if (input != fld.value){ return false; }

        // create ajax request
        url = oP.baseUrl + "/" + oP.partnerFeed + "/?";
        url = url + "keywords=" + escape(input); /*encodeURIComponent(input);*/
        if(oP.charEncoding){
            url = url + "&outputCharEnc=" + oP.charEncoding;
        }
        if(oP.idx){
            url = url + "&idx=" + oP.idx;
        }
        
        // lancer la requete
        script_tag = document.createElement("script");
        script_tag.setAttribute("src", url);
        head.appendChild(script_tag);
        
    },
    refreshBox = function(){
        aSug = [];
        var kw = fld.value;
        if(kw.length<2) {return; }
        var suggestions = suggestCache[kw.substring(0,2)] || [];
        //var regex = new RegExp(fld.value.replace(""), 'i');
        var field_value = fld.value.toLowerCase();
        for (i=0; i < suggestCache.length; i++) {
            var suggestion = suggestions[i];
            //if(regex.test(suggestion)){
            if(suggestion.toLowerCase().indexOf(field_value) != -1){
                aSug.push({
                    'id' : suggestion,
                    'value':suggestion
                });
            }
        }
        /*if(req.ads && req.ads.length){
            ad = req.ads[0];
            aSug.push({
                'value':ad.title,
                'description': ad.description,
                'info': ad.description,
                'sponso' : true,
                'url' : ad.siteHost,
                'clickUrl' : ad.url
                
            });
        }*/
        //console.dir(req.ad);
        idAs = "as_" + fld.id;
        if(aSug && aSug.length){
            createList(aSug);
        }
    },
    setSuggestions = function (req, input){
        var ad, i;
        // if field input no longer matches what was passed to the request, don't show the suggestions
        if (input != fld.value) { return false; }
        
        // TODO : ici faire la meme chose avec le JSON-P qu'initialement prevu
        //debugger; 
        aSug = [];
        for (i=0; i < req.results.length; i++) {
            aSug.push({
                'id' : req.results[i],
                'value':req.results[i]
            });
        }
        if(req.ads && req.ads.length){
            ad = req.ads[0];
            aSug.push({
                'value':ad.title,
                'description': ad.description,
                'info': ad.description,
                'sponso' : true,
                'url' : ad.siteHost,
                'clickUrl' : ad.url
                
            });
            
        }
        
        //console.dir(req.ad);
        idAs = "as_" + fld.id;
        createList(aSug);

    },
    
    createList = function(arr) {
        var div, hcorner, hbar, header, ul, i, a, suggest_object, suggestion, sponso, start, span, br, small, tl, tr, li, fcorner, fbar, footer, pos;
        
        
        // get rid of old list and clear the list removal timeout
        // TODO : changer le contenu de la liste plus en douceur
        //GLOBADMEDIA.DOM.remE(idAs);
        
        if (arr.length === 0){ return false; }
        
        // create holding div
        div     = GLOBADMEDIA.DOM.cE("div", {id:idAs, className:oP.className});   
        hcorner = GLOBADMEDIA.DOM.cE("div", {className:"as_corner"});
        hbar    = GLOBADMEDIA.DOM.cE("div", {className:"as_bar"});
        header  = GLOBADMEDIA.DOM.cE("div", {className:"as_header"});
        
        header.appendChild(hcorner);
        header.appendChild(hbar);
        div.appendChild(header);
        
        // create and populate ul
        ul = GLOBADMEDIA.DOM.cE("ul", {id:"as_ul"});
        
        // loop throught arr of suggestions, creating an LI element for each suggestion
        for (i=0; i< Math.min(arr.length, oP.maxentries+1); i++) {
            // format output with the matching letters enclosed in a EM element
            suggest_object = arr[i];
            suggestion = suggest_object.value;
            sponso = suggest_object.sponso;
            if((i == Math.min(arr.length, oP.maxentries+1) - 1) && !sponso){
                while(!sponso && i < arr.length){
                    suggest_object = arr[i];
                    if(!suggest_object){ break; }
                    suggestion = suggest_object.value;
                    sponso = suggest_object.sponso;
                    i++;
                    
                }
                if(!sponso){ break; }
            }
            
            if(!sponso){
                start = suggestion.toLowerCase().indexOf( sInp.toLowerCase() );
                suggestion = suggestion.substring(0, start) + "<em>" + suggestion.substring(start, start + sInp.length) + "</em>" + suggestion.substring(start + sInp.length);
            }
            span = GLOBADMEDIA.DOM.cE("span", {}, suggestion, true);
            if (suggest_object.description) {
                br = GLOBADMEDIA.DOM.cE("br", {});
                span.appendChild(br);
                small = GLOBADMEDIA.DOM.cE("small", {}, '');
                small.innerHTML = suggest_object.description;
                span.appendChild(small);
            }
            
            if(sponso){
                a = GLOBADMEDIA.DOM.cE("a", { href: suggest_object.clickUrl, target : "_blank" , className: "sponso" });
            }else{
                a = GLOBADMEDIA.DOM.cE("a", { href:"#" });
                a.onclick = function () { setHighlightedValue(); return false; };
            }
            
            tl = GLOBADMEDIA.DOM.cE("span", {className:"tl"}, " ");
            tr = GLOBADMEDIA.DOM.cE("span", {className:"tr"}, " ");
            a.appendChild(tl);
            a.appendChild(tr);
            a.appendChild(span);
            a.name = i+1;
            
            //a.onkeypress     = function(ev){ return GLOBADMEDIA.onSuggestKeyPress(ev); };
            a.onkeydown     = function(ev){ return GLOBADMEDIA.onSuggestKeyDown(ev); };
            a.onkeyup       = function(ev){ return GLOBADMEDIA.onSuggestKeyUp(ev); };
            a.onkeypress    = function(ev){ return GLOBADMEDIA.onSuggestKeyPress(ev); };
            if(!sponso){
                a.onclick       = function(ev){ return GLOBADMEDIA.onSuggestClick(ev); };
            }
            a.onmouseover = function () {
                setHighlight(this.name);
            };
            
            ul.appendChild(  GLOBADMEDIA.DOM.cE(  "li", sponso?{}:{ className : ((i%2 === 0) ? "ligne_paire" : "ligne_impaire") }, a  ));
        }
        
        
        div.appendChild( ul );
        fcorner = GLOBADMEDIA.DOM.cE("a", {className:"as_globad_link", href: "http://www.globadmedia.com"});
        fbar = GLOBADMEDIA.DOM.cE("div", {className:"as_bar"});
        footer = GLOBADMEDIA.DOM.cE("div", {className:"as_footer"});
        footer.appendChild(fcorner);
        footer.appendChild(fbar);
        div.appendChild(footer);
        
        // get position of target textfield, position holding div below it, set width of holding div to width of field
        pos = GLOBADMEDIA.DOM.getPos(fld);
        div.style.top       = ( pos.y + fld.offsetHeight + oP.offsety ) + "px";
        if(fld.offsetWidth > oP.minWidth){
            div.style.left      = pos.x + "px";
            div.style.width     = fld.offsetWidth + "px";
        }else{
            var marge = oP.minWidth - fld.offsetWidth;
            div.style.left = pos.x - Math.floor(marge/2) + "px";
            div.style.width = oP.minWidth + "px";
        }

        GLOBADMEDIA.DOM.remE(idAs);
        
        // add DIV to document
        document.getElementsByTagName("body")[0].appendChild(div);
        
        div.onclick = function(event){
            var e = event || window.event;
            if (e.stopPropagation) {
              e.stopPropagation();
            }
            e.cancelBubble = true;
        };
        
        // currently no item is highlighted
        iHigh = 0;
    },
    
    
    
    clearSuggestions = function(){
        GLOBADMEDIA.DOM.remE(idAs);
        //var ele = GLOBADMEDIA.DOM.gE(idAs);
        //if (ele){ var fade = new GLOBADMEDIA.Fader(ele,1,0,250,function () { _b.DOM.remE(idAs); }); }
    },
    
    
    

    changeHighlight = function(key){
        
        /*var ghost = document.getElementById("ghost");
        if(ghost){
            YAHOO.util.Event.removeListener(ghost, "mouseout");
            ghost.parentNode.removeChild(ghost);
        }*/
        
        var list = GLOBADMEDIA.DOM.gE("as_ul"), n = iHigh;
        if (!list){ return false; }
        
        if (key == 40){ n = n + 1; }
        else if (key == 38){ n = n - 1; }
        
        // TODO : on doit revenir dans le champs de recherche au lieu de bloquer a la premiere suggestion ?
        if (n > list.childNodes.length){ n = list.childNodes.length; }
        if (n < 1){ 
            // on se met dans le champs de recherche 
            // => plus de : "n = 1;"
            clearSuggestions();
            fld.focus();
        }
        
        setHighlight(n);
        
    },
    
    setHighlight = function(n){
        var li, a, list = GLOBADMEDIA.DOM.gE("as_ul");
        if (!list){ return false; }
        if (iHigh > 0){ clearHighlight(); }
        iHigh = +n;
        li = list.childNodes[iHigh-1];
        li.className = li.className  + " as_highlight";
        a = li.getElementsByTagName('A')[0];
        //console.log("a : ", a);
        a.focus();
//        focus();
    },
    
    clearHighlight = function(){
        var list = GLOBADMEDIA.DOM.gE("as_ul");
        if (!list){ return false; }
        if (iHigh > 0){
            list.childNodes[iHigh-1].className = list.childNodes[iHigh-1].className.replace("as_highlight", "");
            iHigh = 0;
        }
    },
    
    setHighlightedValue = function (){
        if (iHigh){
            //close box
            clearSuggestions();
            
            // move cursor to end of input (safari)
            fld.focus();
            if (fld.selectionStart){ fld.setSelectionRange(sInp.length, sInp.length); }
        }
    };
    
    
    
    
    // ====================================================================================================
    // = Methodes publiques                                                                               =
    // ====================================================================================================
    that.onKeyPress = function(ev){
        var key = ((window.event) ? window.event.keyCode : ev.keyCode) || ev.charCode,
        target,
        lettre = String.fromCharCode(key),
        agt=navigator.userAgent.toLowerCase(),
        is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false,
        RETURN = 13, TAB = 9, ESC = 27, ARRUP = 38, ARRDN = 40, bubble = true, suggestion, nouveau_contenu;
        
        ev = ev || window.event;
        if (ev.target) {
            target = (ev.target.nodeType == 3) ? ev.target.parentNode : ev.target;
        } else {
            target = ev.srcElement;
        }
        
        // set responses to keydown events in the field : allows the user to use the arrow keys to scroll through the results
        // ESCAPE clears the list; TAB sets the current highlighted value
        switch(key){
           case ESC:
                clearSuggestions();
                break;
            case ARRUP:
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                ev.cancelBubble = true;
                bubble=0;
                break;
            case ARRDN:
                // /console.log("ARRDN in search field");
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                ev.cancelBubble = true;
                bubble=0;
                
                createList(aSug);
                
                break;
            case TAB:
            case RETURN:
                lettre = "";
                if(is_safari){ bubble = false;}
                if(target.tagName === "A"){
                    bubble = false;
                    suggestion = aSug[ iHigh - 1 ];
                    if(suggestion && suggestion.sponso){
                        bubble=true;
                    }
                    
                    //window.status = "enter typed in";
                }
            default:
                //setHighlightedValue();
                //console.log("lettre : '"+ lettre + "'");
                if(target.tagName === "A"){
                    suggestion = aSug[iHigh-1];
                    nouveau_contenu = suggestion.value + (is_safari ? "" : lettre);
                    fld.value = nouveau_contenu;
                    //window.status += " " + nouveau_contenu;
                    fld.focus();
                    if (fld.setSelectionRange || fld.selectionStart){
                        fld.setSelectionRange(nouveau_contenu.length, nouveau_contenu.length); 
                    }
                }
                break;
        }
        return bubble;
    };
    
    that.onKeyUp = function(ev){
        var key = (window.event) ? window.event.keyCode : ev.keyCode, ARRUP = 38, ARRDN = 40, bubble = 1;
        ev = ev || window.event;
        
        // set responses to keydown events in the field :  allows the user to use the arrow keys to scroll through the results
        // ESCAPE clears the list; TAB sets the current highlighted value
        switch(key){
            case ARRUP:
                changeHighlight(key);
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                bubble = 0;
                ev.cancelBubble = true;
                break;
            case ARRDN:
                changeHighlight(key);
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                ev.cancelBubble = true;
                bubble = 0;
                break;
            default:
                getSuggestions(fld.value);
        }
        return bubble;
    };

    that.onSuggestKeyPress = function(ev){
        //console.log("onSuggestKeyPress");
        var key = ((window.event) ? window.event.keyCode : ev.keyCode) || ev.charCode, target,
        lettre = String.fromCharCode(key),
        agt=navigator.userAgent.toLowerCase(),
        is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false,
        RETURN = 13, TAB = 9, ESC = 27, ARRUP = 38, ARRDN = 40, BACKSPACE = 8, bubble = true, suggestion, nouveau_contenu;
        
        ev = ev || window.event;
        if (ev.target) {
            target = (ev.target.nodeType == 3) ? ev.target.parentNode : ev.target;
        } else {
            target = ev.srcElement;
        }
        
        switch(key){
            case ARRUP:
                changeHighlight(key);
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                bubble = 0;
                ev.cancelBubble = true;
                break;
            case ARRDN:
                changeHighlight(key);
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                bubble = 0;
                ev.cancelBubble = true;
                break;
            case BACKSPACE:
                if(ev.preventDefault){
                    ev.preventDefault();
                }else{
                    ev.returnValue = false;
                }
                bubble = 0;
                suggestion = aSug[iHigh-1];
                nouveau_contenu = suggestion.value.slice(0, suggestion.value.length);
                fld.value = nouveau_contenu;
                //window.status += " " + nouveau_contenu;
                fld.focus();
                if (fld.setSelectionRange || fld.selectionStart){
                    fld.setSelectionRange(nouveau_contenu.length, nouveau_contenu.length); 
                }
                
                break;
            default:
                //alert(key);
                //getSuggestions(fld.value);
                if(target.tagName === "A"){
                    //suggestion = aSug[iHigh-1];
                    //nouveau_contenu = suggestion.value + (is_safari ? "" : lettre);
                    nouveau_contenu = fld.value + (is_safari ? "" : lettre);
                    fld.value = nouveau_contenu;
                    //window.status += " " + nouveau_contenu;
                    fld.focus();
                    if (fld.setSelectionRange || fld.selectionStart){
                        fld.setSelectionRange(nouveau_contenu.length, nouveau_contenu.length); 
                    }
                }
                
        }
        return bubble;
    };
    
    that.onSuggestKeyUp = function(ev){
        //console.log("onSuggestKeyUp");
        ev = ev || window.event;
        if(ev.preventDefault){
            ev.preventDefault();
        }
        if(ev.stopPropagation){
            ev.stopPropagation();
        }
        ev.cancelBubble = true;
        ev.returnValue = false;
        return false;
    };
    
    that.onSuggestKeyDown = function(ev){
        ev = ev || window.event;
        //console.log("onSuggestKeyDown");
        var key = (window.event) ? window.event.keyCode : ev.keyCode, ARRUP = 38, ARRDN = 40, ESC = 27, bubble = 1;
        switch(key){
            case ESC:
                 clearSuggestions();
                 fld.focus();
                 if(ev.preventDefault){
                     ev.preventDefault();
                 }
                 if(ev.stopPropagation){
                     ev.stopPropagation();
                 }
                 ev.cancelBubble = true;
                 ev.returnValue = false;
                 break;
            case ARRUP:
                if(window.event){
                    changeHighlight(key);
                }
                if(ev.preventDefault){
                    ev.preventDefault();
                }
                if(ev.stopPropagation){
                    ev.stopPropagation();
                }
                ev.cancelBubble = true;
                ev.returnValue = false;
                break;
            case ARRDN:
                if(window.event){
                    changeHighlight(key);
                }
                if(ev.preventDefault){
                    ev.preventDefault();
                }
                if(ev.stopPropagation){
                    ev.stopPropagation();
                }
                ev.cancelBubble = true;
                ev.returnValue = false;
                break;
            default:
                getSuggestions(fld.value);
        }
        return bubble;
    };
    
    that.onSuggestClick = function(ev){
        var target, suggestion, nouveau_contenu;
        ev = ev || window.event;
        if(ev.preventDefault){
            ev.preventDefault();
        }else{
            ev.returnValue = false;
        }
        
        if (ev.target) {
            target = (ev.target.nodeType == 3) ? ev.target.parentNode : ev.target;
        } else {
            target = ev.srcElement;
        }
        if(target.tagName === "EM"){
            target = target.parentNode;
        }
        if(target.tagName === "SPAN"){
            target = target.parentNode;
        }
        //console.log(target);
        
        //suggestion = aSug[(+target.name)-1];
        //console.log(suggestion);
        //nouveau_contenu = suggestion.value /*+ (is_safari ? "" : lettre)*/;
        nouveau_contenu = target.textContent || target.innerText;
        nouveau_contenu = nouveau_contenu.replace(/^\s+|\s+$/g,"");
        fld.value = nouveau_contenu;
        //window.status += " " + nouveau_contenu;
        fld.focus();
        if (fld.setSelectionRange || fld.selectionStart){
            fld.setSelectionRange(nouveau_contenu.length, nouveau_contenu.length); 
        }
        
        getSuggestions(fld.value);
        
        return false;
        
        /*if(ev.target.tagName === "A"){
            var suggestion = ev.target;
            nouveau_contenu = suggestion.value / *+ (is_safari ? "" : lettre)* /;
            fld.value = nouveau_contenu;
            //window.status += " " + nouveau_contenu;
            fld.focus();
            if (fld.setSelectionRange || fld.selectionStart){
                fld.setSelectionRange(nouveau_contenu.length, nouveau_contenu.length); 
            }
        }*/
        
        
    };
    
    
    that.a = {
        cb : function(req){
            setSuggestions(req, fld.value);
        }
    };
    
    that.init = function(place, params){
        var k, input, inputs,
            type = typeof place;
        
        if (!document.getElementById){ return 0; }
        
        // recuperer la balise head pour y mettre les balises script 
        head = document.getElementsByTagName("head")[0];
        
        // get field via DOM
        // TODO: add className and xpath methods for field localization
        if(type === "string"){ /* on considere que c'est un id */
            fld = GLOBADMEDIA.DOM.gE(place);
        }else if(type === "object" && typeof place['id'] === "string"){
            fld = GLOBADMEDIA.DOM.gE(place['id']);
        }else if(type === "object" && typeof place['name'] === "string"){
            inputs = document.getElementsByTagName("input");
            for (var i=0; i < inputs.length; i++) {
                input = inputs[i];
                if(input.name && input.name === place['name']){
                    fld = input;
                    break;
                }
            }
        }
        
        
        if (!fld){ return 0; }
        
        // apply default parameters
        oP = params || {};
        for (k in def){
            if (oP[k] === undefined){
                oP[k] = def[k];
            }
        }
        
        var selectors = {
            logo:[{ selector : 'div.autosuggest div.as_footer .as_bar', name : 'background',
                    template : 'transparent url($logo_url) no-repeat scroll 6px center !important', var_name : "$logo_url" } ],
            border:[
                { selector : 'div.autosuggest ul', name : 'border-top', template : '1px solid #$color !important', var_name : "$color" },
                { selector : 'div.autosuggest ul', name : 'border-left', template : '1px solid #$color !important', var_name : "$color" },
                { selector : 'div.autosuggest ul', name : 'border-right', template : '1px solid #$color !important', var_name : "$color" },
                { selector : 'div.autosuggest div.as_footer .as_bar', name : 'border-bottom', template : '1px solid #$color !important', var_name : "$color" },
                { selector : 'div.autosuggest div.as_footer .as_bar', name : 'border-left', template : '1px solid #$color !important', var_name : "$color" },
                { selector : 'div.autosuggest div.as_footer .as_bar', name : 'border-right', template : '1px solid #$color !important', var_name : "$color" }
            ],
            backEven:[ { selector : 'div.autosuggest .ligne_paire', name : 'background', template : '#$color none repeat scroll 0 0 !important', var_name : "$color" } ],
            frontEven:[ { selector : 'div.autosuggest ul li.ligne_paire a', name : 'color', template : '#$color !important', var_name : "$color" } ],
            frontUneven:[ { selector : 'div.autosuggest ul li.ligne_impaire a', name : 'color', template : '#$color !important', var_name : "$color" } ],
            backUneven:[ { selector : 'div.autosuggest .ligne_impaire', name : 'background', template : '#$color none repeat scroll 0 0 !important',var_name : "$color" } ],
            backHover:[ 
                { selector : 'div.autosuggest ul li a:hover', name : 'background-color', template : '#$color !important', var_name : "$color" },
                { selector : 'div.autosuggest ul li.as_highlight a', name : 'background-color', template : '#$color !important', var_name : "$color" }
            ],
            textHover:[
                { selector : 'div.autosuggest ul li a:hover', name : 'color', template : '#$color !important', var_name : "$color" },
                { selector : 'div.autosuggest ul li.as_highlight a', name : 'color', template : '#$color !important', var_name : "$color" }
            ]
        };
        
        var css_rules = "";
        if(oP.colors){
            for(var colorname in oP.colors){
                var colorvalue = oP.colors[colorname];
                for(var j=0; selectors[colorname] && j < selectors[colorname].length; j++){
                    var rule = selectors[colorname][j];
                    css_rules += rule.selector + " { " + rule.name + " : " + rule.template.replace(rule.var_name, colorvalue) + " } \n";
                }
            }
        }
        if(oP.logo){
            var logo_url = "http://com.globad.logos.s3.amazonaws.com/" + oP.logo;
            for(var l=0; l < selectors.logo.length;l++){
                var logo_rule = selectors.logo[l];
                css_rules += logo_rule.selector + " { " + logo_rule.name + " : " + logo_rule.template.replace(logo_rule.var_name, logo_url) + "; } \n";
            }
        }
        if(css_rules !== ""){
            var stylesheet = GLOBADMEDIA.DOM.cE( 'style', { type: 'text/css'});
            try{
                //stylesheet.innerHTML = css_rules;
                var styleTextNode = document.createTextNode(css_rules);
                stylesheet.appendChild(styleTextNode);
            }catch(except){
                var parts = css_rules.split(/\s*[{}]\s*/);
                for (var m=0; m<parts.length; m+=2){
                    stylesheet.styleSheet.addRule(parts[m],parts[m+1]);
                }
            }
            //document.body.appendChild(stylesheet);
            document.getElementsByTagName("head")[0].appendChild(stylesheet);
        }
        
        // set keyup handler for field and prevent autocomplete from client
        // NOTE: not using addEventListener because UpArrow fired twice in Safari
        //GLOBADMEDIA.DOM.addEvent( fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
        fld.onkeypress     = function(ev){ return GLOBADMEDIA.onKeyPress(ev); };
        fld.onkeyup        = function(ev){ return GLOBADMEDIA.onKeyUp(ev); };
        fld.setAttribute("autocomplete","off");
        
        var ancien_onclick = document.body.onclick || function() {};
        document.body.onclick = function() {
            ancien_onclick();
            GLOBADMEDIA.DOM.remE(idAs);
        };
        
        var ancien_onresize = window.onresize;
        window.onresize=function(){
            clearSuggestions();
            if(ancien_onresize){
                ancien_onresize();
            }
        };
        /*
        log("Test du logging :");
        info("info");
        warn("warning");
        error("error");
        dir(GLOBADMEDIA);*/
        
    };
    
    that.test_debug = function(){
        log("log message");
        info("info message");
        warn("warning message");
        error("error message");
        dir(window);
    };
    
    return that;
    
    
    
}();
    
GLOBADMEDIA.DOM = GLOBADMEDIA.DOM || {};
/* create element */
GLOBADMEDIA.DOM.cE = function ( type, attr, cont, html ){
        var a, t, ne = document.createElement( type );
        if (!ne){ return 0; }
        
        for (a in attr){ ne[a] = attr[a]; }
        
        t = typeof(cont);
        if (t === "string" && !html) { ne.appendChild( document.createTextNode(cont) ); }
        else if (t === "string" && html) { ne.innerHTML = cont; }
        else if (t === "object"){ ne.appendChild( cont ); }

        return ne;
};

/* get Element by Id */
GLOBADMEDIA.DOM.gE = function (e){
        var re, t = typeof(e);
        if (t === "undefined"){ return 0; }
        else if (t === "string"){
            re = document.getElementById( e );
            if (!re){ return 0;}
            else if (typeof(re.appendChild) !== "undefined" ) { return re; }
            else { return 0; }
        }
        else if (typeof(e.appendChild) != "undefined"){ return e; }
        else { return 0; }
};
    
/* remove element */
GLOBADMEDIA.DOM.remE = function (ele){
        var e = GLOBADMEDIA.DOM.gE(ele);
        if (!e) { return 0; }
        else if (e.parentNode.removeChild(e)) { return true; }
        else { return 0;}
};
    
/* get position */
GLOBADMEDIA.DOM.getPos = function (e){
        var el = GLOBADMEDIA.DOM.gE(e), obj, curleft = 0, curtop = 0;
        obj = el;
        if (obj.offsetParent){
            while (obj.offsetParent){
                curleft += obj.offsetLeft;
                obj = obj.offsetParent;
            }
        }else if (obj.x){
            curleft += obj.x;
        }
        obj = el;
        if (obj.offsetParent){
            while (obj.offsetParent){
                curtop += obj.offsetTop;
                obj = obj.offsetParent;
            }
        }else if (obj.y){
            curtop += obj.y;
        }
        return { x : curleft, y : curtop};
};

GLOBADMEDIA.COOKIES = {
    create : function(name,value,days) {
        var expires = "", date;
        if (days) {
            date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            expires = "; expires="+date.toGMTString();
        }
        document.cookie = name+"="+value+expires+"; path=/";
    },
    
    read : function(name) {
        var nameEQ = name + "=", ca = document.cookie.split(';'), i, c;
        for(i=0;i < ca.length;i++) {
            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;
    },
    
    erase : function (name) {
        createCookie(name,"",-1);
    },
    
    addSearch : function(search){
        
    }
    
};




