var XML = {}
XML.Utils = {};
XML.Utils.getFirstTextNodeValue =  function(node,tagName,nsprefix,nsuri) {
		Assert.assertNotNull(node);
		Assert.assertNotNull(tagName);
		var nodeList = this.getElementsByTagNameNS(node,tagName,nsprefix);
		var first = nodeList[0];
		if(first && first.firstChild) {
			return first.firstChild.nodeValue;
		} else {
			return null;
		}
}

XML.Utils.getElementsByTagNameNS = function(parentnode,tagname,nsprefix,nsuri){
    Assert.assertNotNull(parentnode);
    if(parentnode.getElementsByTagNameNSZZZZZ) {//correct dom implementors
			if(nsuri != undefined) {
				return parentnode.getElementsByTagNameNS(nsuri,tagname);
			}else {
				//mozilla happens to return everything, including elements not in default NS
				return parentnode.getElementsByTagName(tagname);
			}
	} else {//IE is teh suk	
		//IE doesn't even have getElementsByTagNameNS
		//so if we pass a prefix, it will have to handle it as if the element name was prefix:localname
		//otherwise, look in default namespace
		if(nsprefix != undefined) {
			//we passed a prefix
			return parentnode.getElementsByTagName(nsprefix + ':' + tagname);
		} else {
			//looking for tags in default NS
			return parentnode.getElementsByTagName(tagname);
		}
	}
}

/**
 * A StringBuffer implementation.
 */
var StringBuffer = Class.create();
StringBuffer.prototype = Object.extend(new Object(), {
    initialize : function(){
       this.buffer = new Array();
   },
   append : function(string) {
        this.buffer.push(string);
        return this;
   },
   toString : function() {
        return this.buffer.join("");
   }
});

var Graph = Class.create();
Graph.prototype = Object.extend(new Object(), {
   initialize : function(){
       this.bars = new Array();
       this.maxPercentage = 0;
   },
   addBar : function(bar) {
       this.bars.push(bar);
   },
   getMaxBarValue : function() {
       var min = 1;
       for(var i = 0; i < this.bars.length; i++) {
           min = Math.min(min,this.bars[i].values[0]);
       }
       return (1 - (min < 0.3 ? 0.3 : min)) + 0.1;
   }
});

Graph.Bar = Class.create();
Graph.Bar.prototype = Object.extend(new Object(), {
   initialize : function(barLabel, values, valuesLabel) {
    this.label = barLabel;
    this.values = values;
    Assert.assertNotNull(valuesLabel);
    this.valuesLabel = valuesLabel;
    this.title = valuesLabel;
   }
});

var ContentUpdater = Class.create();

ContentUpdater.prototype = Object.extend(new Object(),{
       initialize : function(interval) {
           this.updaters = new Array();
           var self = this;
           setInterval(function(){self.execute();},interval);
       },
       addUpdater : function(name,updater) {
           Assert.assertNotNull(name);
           Assert.assertNotNull(updater);
           //als het al aanwezig is, update gewoon de updater onder die naam
           var orgupdater = this.findupdater(name);
           if(orgupdater) {
               orgupdater.updater = updater;
               debug("updater with name '"+name+"' was already present, switching to new updater instance");
           } else {
                this.updaters.push({"name" : name, "updater" : updater});
           }
           debug("added contentUpdater: '"+name+"', total updater elements: " +this.updaters.length);
       },
       removeupdater : function(name) {
           //implement me if necessary
       },
       clear : function() {
           debug("ContentUpdater.clear()");
           this.updaters = new Array();
       },
       execute : function() {
           debug("will have to call '"+this.updaters.length+"' updaters");
            this.updaters.each(function(element){
                try {
                   debug('calling update for "'+element.name+'"');
                   element.updater();
               } catch(e) {
                   debug(e);
               }
            });
       },
       isPresent : function(name) {
            debug("contentUpdater.isPresent("+name+")");
           for(var i = 0;i< this.updaters.length;i++) {
                if(this.updaters[i].name == name) {
                    debug("was present");
                    return true;
                }
           }
           debug("was not present");
           return false;
       },
       clearExcept : function(name){
           debug("contentUpdater.clearExcept('"+name+"')");
           var updatersCopy = [];
           try{
            for(var i = 0; i < this.updaters.length; i++) {
                if(this.updaters[i].name == name) {
                    debug("not removing updater '"+name+"'");
                    updatersCopy.push(this.updaters[i]);
                } else {
                    debug("removing updater '"+name+"'");
                }
            }
           this.updaters = updatersCopy;
           }catch(e) {
               debug("error bij clearen updaters; ");
               debug(e.message);
           }
       },
       findupdater : function(name) {
           for(var i = 0; i< this.updaters.length; i++) {
               if(this.updaters[i].name == name) {
                   return this.updaters[i];
               }
           }
           return null;
       },
       toString : function() {
           return "contentUpdater : interval = "+this.interval;
       }
});


var MessageManager = Class.create();


MessageManager.prototype = Object.extend(new Object(),{
    initialize : function(holder,options) {
        this.holder = $(holder);
        Assert.assertNotNull(this.holder);
        this.setOptions(options);
        //preload image
        this.image = new Image();
        this.image.src = this.options.imageSrc;
        this.showingMessage = false;
    },
    setOptions : function(options) {
         this.options = {
          imageSrc:       'images/indicator.gif',
          alt: "vooruitgangsindicator"
        }
        Object.extend(this.options, options || {});
    },
    startProgress : function(description) {
        var img = this.image;
		//img.src=this.options.imageSrc;
        img.alt = this.options.alt;
        img.title = description || "";
        this.holder.innerHTML = "";
        this.holder.appendChild(img);
    },
    stopProgress : function(description) {
        description = description || "";
        this.showMessage(description);

    },
    showMessage : function(message) {
        if(message != "") {
            this.showingMessage = true;
            this.holder.innerHTML = "";
            var span = document.createElement("span");
            var txt = document.createTextNode(message);
            span.style.display="none";
            span.appendChild(txt);
            this.holder.appendChild(span);
            var self = this;
            //na het blurren van de message tonen we die niet meer
            new Effect.Peek(span,{'afterFinish' : function(){self.showingMessage = false}});
            debug('showing message "'+message+'"');
            //new Effect.Appear(span,{"duration" :  4, "afterFinish" : function(){new Effect.Fade(span,{"duration" :  4})}});
        } else {
            //enkel clearen indien  we niet bezig zijn met een boodschap te tonen aan de gebruiker
            if(! this.showingMessage) {
                this.holder.innerHTML = "";
            }
        }
    }
});

MessageManager.getDefaultManager = function(){
    if(MessageManager.defaultManager == null) {
        MessageManager.defaultManager = new MessageManager('messagePane');
    }
    return MessageManager.defaultManager;
}

var PageNavigator = {}
PageNavigator.openStartPage = function() {
    var newWindow = window.open('index.html', 'start');
    newWindow.focus();
    return false;
}
PageNavigator.openOverviewPage = function() {
    var newWindow = window.open('overzicht.html', 'overzicht');
    newWindow.focus();
    return false;
}

/**
* Tries to create and load an url with the passed nistype/niscode
* Will be in the form of 'GE-12002.xml'
*/
PageNavigator.openResultsPage = function(nisType, nisCode, openNewWindow) {

    if(nisCode == null) {
        /*Dialog.alert("<h2>Fout</h2><br/>Je moet een geldige gemeente of stadsdistrict naam intikken. <br/>",
                {windowParameters: {width:300, height:150, opacity:1}, okLabel: "OK"});*/
        new Lightbox.base('<h2>Fout</h2>Je moet een geldige gemeente of stadsdistrict naam intikken.');
        return false;
    } else {
        if (document.forms["gemeenteForm"] != undefined && document.forms["gemeenteForm"] != null) {
            var fields = document.forms["gemeenteForm"].elements["nisType"];
            for (var i = 0; i < fields.length; i++) {
                if (fields[i].checked) {
                    nisType = fields[i].value;
                }
            }
        }
      //user has typed something himself, without pressing enter or selecting via the dropdown
      if(nisType == null) {
        nisType = "GE";
      }
      if(openNewWindow) {
        var newWindow = window.open('lijsten.html?type=' + nisType + '&nis=' + nisCode);
        newWindow.focus();
      } else {
        window.location.href = 'lijsten.html?type=' + nisType + '&nis=' + nisCode;
      }
      return false;
    }
}

/**
* Tries to create and load an url with the passed nistype/niscode
* Will be in the form of 'GE-12002.xml'
*/
PageNavigator.openResultsWindow = function(nisCode) {
    if(nisCode == null) {
        alert("Geef eerst een geldige gemeente in.");
        return false;
    } else {
        if (document.forms["gemeenteForm"] != undefined && document.forms["gemeenteForm"] != null) {
            var fields = document.forms["gemeenteForm"].elements["nisType"];
            for (var i = 0; i < fields.length; i++) {
                if (fields[i].checked) {
                    nisType = fields[i].value;
                }
            }
        }

        //var newWindow = window.open('lijsten.html?type='+nisType+'&nis='+nisCode, nisCode);
        //newWindow.focus();
        createWindow();
        return false;
    }
}

PageNavigator.openSearchPane = function() {
    var element = $('searchPanel');
    new Effect.SlideDown(element, { afterFinish : function(){
        document.gemeenteForm.gemeentes.focus();
        PageNavigator.showingSearchPane = true;}
    });

}

PageNavigator.closeSearchPane = function() {
    var element = $('searchPanel');
    PageNavigator.showingSearchPane = false;
    new Effect.SlideUp(element);
}
//default refresh message
function showDoNotRefreshMessage() {
    debug('showing do not refresh diag');
    //Dialog.alert("<h2>Info</h2><br/>Onnodig de pagina te vernieuwen/refreshen.  De gegevens worden automatisch herladen op de achtergrond.<br/>",{windowParameters: {width:300, height:200}, okLabel: "OK"});
    new Lightbox.base('<h2>Info</h2>Onnodig de pagina te vernieuwen/refreshen.  De gegevens worden automatisch herladen op de achtergrond.<br/>');
}

var Assert = Class.create();
Assert.assertNotNull = function(arg) {
	if(arg == null) {
		//throw("arg was null");
        debug("arg was null");
    }
}