// Heads up! August 2003
// This file now requires the javascript variable portal_url to be set 
// in the plone_javascript_variables.js file. Any other variables from Plone
// that you want to pass into these scripts should be placed there.

/* <dtml-var "enableHTTPCompression(request=REQUEST, debug=1, js=1)"> (this is for http compression) */

function afficher(division){
//script créé par ptitcali, le 08.04.05 à 1130

	//va chercher l'id de l'élément qu'on veut afficher
	id=document.getElementById(division);
	//trouve l'état de l'élément trouvé
	var etat=id.style.display;
	//si il est affiché, on le cache, sinon, on le montre
	if(etat=="none"){
		id.style.display="";
	}else{
		id.style.display="none";
	}
}

function registerPloneFunction(func){
    // registers a function to fire onload. 
	// Turned out we kept doing this all the time
	// Use this for initilaizing any javascript that should fire once the page has been loaded. 
	// 
    if (window.addEventListener) window.addEventListener("load",func,false);
    else if (window.attachEvent) window.attachEvent("onload",func);   
  }

function unRegisterPloneFunction(func){
    // uregisters a previous function to fire onload. 
    if (window.removeEventListener) window.removeEventListener("load",func,false);
    else if (window.detachEvent) window.detachEvent("onload",func);   
  }

function getContentArea(){
	// to end all doubt on where the content sits. It also felt a bit silly doing this over and over in every
	// function, even if it is a tiny operation. Just guarding against someone changing the names again, in the name
	// of semantics or something.... ;)
	node =  document.getElementById('region-content')
	if (! node){
		node = document.getElementById('content')
		}
	return node
	}

function wrapNode(node, wrappertype, wrapperclass){
    // utility function to wrap a node "node" in an arbitrary element of type "wrappertype" , with a class of "wrapperclass"
    wrapper = document.createElement(wrappertype)
    wrapper.className = wrapperclass;
    innerNode = node.parentNode.replaceChild(wrapper,node);
    wrapper.appendChild(innerNode)
}
	
// Focus on error or tabindex=1 
function setFocus() {
    var xre = new RegExp(/\berror\b/);
    // Search only forms to avoid spending time on regular text
    for (var f = 0; (formnode = document.getElementsByTagName('form').item(f)); f++) {
        // Search for errors first, focus on first error if found
        for (var i = 0; (node = formnode.getElementsByTagName('div').item(i)); i++) {
            if (xre.exec(node.className)) {
                for (var j = 0; (inputnode = node.getElementsByTagName('input').item(j)); j++) {
                    inputnode.focus();
                    return;   
                }
            }
        }
        // If no error, focus on input element with tabindex 1
        
        
        // uncomment to reactivate
        // this part works as intended, but there are too many places where this function causes pain, moving 
        // focus away from a field in whuch the user is already typing
        
        //for (var i = 0; (node = formnode.getElementsByTagName('input').item(i)); i++) {
         //   if (node.getAttribute('tabindex') == 1) {
         //       node.focus();
         //        return;   
         //   }
        //}
    }
}
registerPloneFunction(setFocus)





/********* Table sorter script *************/
// Table sorter script
// DOM table sorter originally made by Paul Sowden 

function compare(a,b)
{
    au = new String(a);
    bu = new String(b);

    if (au.charAt(4) != '-' && au.charAt(7) != '-')
    {
    var an = parseFloat(au)
    var bn = parseFloat(bu)
    }
    if (isNaN(an) || isNaN(bn))
        {as = au.toLowerCase()
         bs = bu.toLowerCase()
        if (as > bs)
            {return 1;}
        else
            {return -1;}
        }
    else {
    return an - bn;
    }
}



function getConcatenedTextContent(node) {
    var _result = "";
	  if (node == null) {
		    return _result;
	  }
    var childrens = node.childNodes;
    var i = 0;
    while (i < childrens.length) {
        var child = childrens.item(i);
        switch (child.nodeType) {
            case 1: // ELEMENT_NODE
            case 5: // ENTITY_REFERENCE_NODE
                _result += getConcatenedTextContent(child);
                break;
            case 3: // TEXT_NODE
            case 2: // ATTRIBUTE_NODE
            case 4: // CDATA_SECTION_NODE
                _result += child.nodeValue;
                break;
            case 6: // ENTITY_NODE
            case 7: // PROCESSING_INSTRUCTION_NODE
            case 8: // COMMENT_NODE
            case 9: // DOCUMENT_NODE
            case 10: // DOCUMENT_TYPE_NODE
            case 11: // DOCUMENT_FRAGMENT_NODE
            case 12: // NOTATION_NODE
                // skip
                break;
        }
        i ++;
    }
  	return _result;
}

function sort(e) {
    var el = window.event ? window.event.srcElement : e.currentTarget;

    // a pretty ugly sort function, but it works nonetheless
    var a = new Array();
    // check if the image or the th is clicked. Proceed to parent id it is the image
    // NOTE THAT nodeName IS UPPERCASE
    if (el.nodeName == 'IMG') el = el.parentNode;
    //var name = el.firstChild.nodeValue;
    // This is not very robust, it assumes there is an image as first node then text
    var name = el.childNodes.item(1).nodeValue;
    var dad = el.parentNode;
    var node;
    
    // kill all arrows
    for (var im = 0; (node = dad.getElementsByTagName("th").item(im)); im++) {
        // NOTE THAT nodeName IS IN UPPERCASE
        if (node.lastChild.nodeName == 'IMG')
        {
            lastindex = node.getElementsByTagName('img').length - 1;
            node.getElementsByTagName('img').item(lastindex).setAttribute('src',portal_url + '/arrowBlank.gif');
        }
    }
    
    for (var i = 0; (node = dad.getElementsByTagName("th").item(i)); i++) {
        var xre = new RegExp(/\bnosort\b/);
        // Make sure we are not messing with nosortable columns, then check second node.
        if (!xre.exec(node.className) && node.childNodes.item(1).nodeValue == name) 
        {
            //window.alert(node.childNodes.item(1).nodeValue;
            lastindex = node.getElementsByTagName('img').length -1;
            node.getElementsByTagName('img').item(lastindex).setAttribute('src',portal_url + '/arrowUp.gif');
            break;
        }
    }

    var tbody = dad.parentNode.parentNode.getElementsByTagName("tbody").item(0);
    for (var j = 0; (node = tbody.getElementsByTagName("tr").item(j)); j++) {

        // crude way to sort by surname and name after first choice
        a[j] = new Array();
        a[j][0] = getConcatenedTextContent(node.getElementsByTagName("td").item(i));
        a[j][1] = getConcatenedTextContent(node.getElementsByTagName("td").item(1));
        a[j][2] = getConcatenedTextContent(node.getElementsByTagName("td").item(0));		
        a[j][3] = node;
    }

    if (a.length > 1) {
	
        a.sort(compare);

        // not a perfect way to check, but hell, it suits me fine
        if (a[0][0] == getConcatenedTextContent(tbody.getElementsByTagName("tr").item(0).getElementsByTagName("td").item(i))
	       && a[1][0] == getConcatenedTextContent(tbody.getElementsByTagName("tr").item(1).getElementsByTagName("td").item(i))) 
        {
            a.reverse();
            lastindex = el.getElementsByTagName('img').length - 1;
            el.getElementsByTagName('img').item(lastindex).setAttribute('src', portal_url + '/arrowDown.gif');
        }

    }
	
    for (var j = 0; j < a.length; j++) {
        tbody.appendChild(a[j][3]);
    }
}
    
function initalizeTableSort(e) {
    var tbls = document.getElementsByTagName('table');
    for (var t = 0; t < tbls.length; t++)
        {
        // elements of class="listing" can be sorted
        var re = new RegExp(/\blisting\b/)
        // elements of class="nosort" should not be sorted
        var xre = new RegExp(/\bnosort\b/)
        if (re.exec(tbls[t].className) && !xre.exec(tbls[t].className))
        {
            try {
                var tablename = tbls[t].getAttribute('id');
                var thead = document.getElementById(tablename).getElementsByTagName("thead").item(0);
                var node;
                // set up blank spaceholder gifs
                blankarrow = document.createElement('img');
                blankarrow.setAttribute('src', portal_url + '/arrowBlank.gif');
                blankarrow.setAttribute('height',6);
                blankarrow.setAttribute('width',9);
                // the first sortable column should get an arrow initially.
                initialsort = false;
                for (var i = 0; (node = thead.getElementsByTagName("th").item(i)); i++) {
                    // check that the columns does not have class="nosort"
                    if (!xre.exec(node.className)) {
                        node.insertBefore(blankarrow.cloneNode(1), node.firstChild);
                        if (!initialsort) {
                            initialsort = true;
                            uparrow = document.createElement('img');
                            uparrow.setAttribute('src', portal_url + '/arrowUp.gif');
                            uparrow.setAttribute('height',6);
                            uparrow.setAttribute('width',9);
                            node.appendChild(uparrow);
                        } else {
                            node.appendChild(blankarrow.cloneNode(1));
                        }
    
                        if (node.addEventListener) node.addEventListener("click",sort,false);
                        else if (node.attachEvent) node.attachEvent("onclick",sort);
                    }
                }
            } catch(er) {}
        }
    }
}   
// **** End table sort script ***
registerPloneFunction(initalizeTableSort)   

 function climb(node, word){
	 // traverse childnodes
    if (! node){return false}
    if (node.hasChildNodes) {
		var i;
		for (i=0;i<node.childNodes.length;i++) {
            climb(node.childNodes[i],word);
		}
        if (node.nodeType == 3){
            checkforhighlight(node, word);
           // check all textnodes. Feels inefficient, but works
        }
}
function checkforhighlight(node,word) {
        ind = node.nodeValue.toLowerCase().indexOf(word.toLowerCase())
		if (ind != -1) {
            if (node.parentNode.className != "highlightedSearchTerm"){
                par = node.parentNode;
                contents = node.nodeValue;
			
                // make 3 shiny new nodes
                hiword = document.createElement("span");
				hiword.className = "highlightedSearchTerm";
				hiword.appendChild(document.createTextNode(contents.substr(ind,word.length)));
				
                par.insertBefore(document.createTextNode(contents.substr(0,ind)),node);
				par.insertBefore(hiword,node);
				par.insertBefore(document.createTextNode(contents.substr(ind+word.length)),node);

                par.removeChild(node);
		        }
        	} 
		}
  
}


function correctPREformatting(){
        // small utility thing to correct formatting for PRE-elements and some others
        // thanks to Michael Zeltner for CSS-guruness and research ;) 
		// currently not activated
        contentarea = getContentArea();
        if (! contentarea){return false}
        
        pres = contentarea.getElementsByTagName('pre');
        for (i=0;i<pres.length;i++){
           wrapNode(pres[i],'div','visualOverflow')
			}
               
        //tables = contentarea.getElementsByTagName('table');
        // for (i=0;i<tables.length;i++){
        //   if (tables[i].className=="listing"){
        //   wrapNode(tables[i],'div','visualOverflow')
		//  }
        //}      
}
//registerPloneFunction(correctPREformatting);

function highlightSearchTerm() {
        // search-term-highlighter function
        query = window.location.search
        // _robert_ ie 5 does not have decodeURI 
        if (typeof decodeURI != 'undefined'){
            query = unescape(decodeURI(query)) // thanks, Casper 
        }
        else {
            return false
        }
        if (query){
            var qfinder = new RegExp()
            qfinder.compile("searchterm=([^&]*)","gi")
            qq = qfinder.exec(query)
            if (qq && qq[1]){
                query = qq[1]
                
                // the cleaner bit is not needed anymore, now that we travese textnodes. 
                //cleaner = new RegExp
                //cleaner.compile("[\\?\\+\\\\\.\\*]",'gi')
                //query = query.replace(cleaner,'')
                
                if (!query){return false}
                queries = query.replace(/\+/g,' ').split(/\s+/)
                
                // make sure we start the right place and not higlight menuitems or breadcrumb
                contentarea = getContentArea();
				for (q=0;q<queries.length;q++) {
                                       // don't highlight reserved catalog search terms
                                       if (queries[q].toLowerCase() != 'not'
                                               && queries[q].toLowerCase() != 'and'
                                               && queries[q].toLowerCase() != 'or') {
                       climb(contentarea,queries[q]);
                                       }
                }
            }
        }
}
registerPloneFunction(highlightSearchTerm);

// and finally : Mike Malloch's fixes for Internet Explorer 5 - 
// These should be considered temporary, as they actually add functionality to IE5, while we just want it to not blurt errormessages... 
//

function hackPush(el){
        this[this.length] = el;
}

function hackPop(){
        var N = this.length - 1, el = this[N];
        this.length = N
        return el;
}

function hackShift(){
        var one = this[0], N = this.length;
        for (var i = 1; i < N; i++){
                this[i-1] = this[i];
        }
        this.length = N-1
        return one;
}

var testPushPop = new Array();
if (testPushPop.push){
}else{
        Array.prototype.push = hackPush
        Array.prototype.pop = hackPop
        Array.prototype.shift =hackShift;
}


