// browser detect script from: http://www.quirksmode.org/js/detect.html
var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)
                    return data[i].identity;}
                else if(dataProp)
                    return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};
        BrowserDetect.init();
        var executeAjax = true

        var myBrowser;

        function init() {
            myBrowser =	BrowserDetect.browser + ' ' + BrowserDetect.version;
        }
        init();


        /* stretch the page to full screen window */
        function resizeBoxes() {
    
            var myWindow	= getWindowSize();
    
            var ff		= {sidebar: 150, pagecontent: 202, obleft: 240, obtop: 151, obwidth: 250, obbottom: 10 }; // firefox
            var ie7		= {sidebar: 134, pagecontent: 202, obleft: 240, obtop: 151, obwidth: 250, obbottom: 10 }; // internet explorer 7
            var chrome  = {sidebar: 150, pagecontent: 201, obleft: 240, obtop: 151, obwidth: 250, obbottom: 10 }; // google chrome
    
            var s; // sizes to be used
            // reference correct browser sizes to s
            //myBrowser.split(" ")
            switch (myBrowser.split(" ")[0]) {
                case 'Firefox':
                case 'Safari':
                    s = ff;
                    break;
                case 'Explorer':
                    s = ie7;
                    break;
                case 'Mozilla':
                    s = chrome;
                    break;
                default:
                    s = ff; // default take standards values (firefox)
            }
            if ($('messagebar') == undefined)
                s.pagecontent -= 111;
    
            // add/substract exceptions
            if($('switchtree_button')) s.sidebar += 30;
            if($('actionbar')){
                s.pagecontent += -12;
                s.obbottom += 29;
            } 
            if($('standard_flash')) {
                s.sidebar += 45;
                s.pagecontent += 45;
                s.obtop += 45;
            }
    
            if($('sidebartreeview')) {
                $('sidebartreeview').style.height = (myWindow.height - s.sidebar) + 'px';
                if($('standard_flash')) {
                    $('sidebar').style.top = '125px';
                } else {
                    $('sidebar').style.top = '80px';
                }	
            }
            $('pagecontent').style.height = (myWindow.height - s.pagecontent) + 'px';
            if ($('messagebar')) {
               $('messagebar').style.bottom = s.obbottom + 'px';
                $('messagebar').style.left = s.obleft + 'px';
                $('messagebar').style.width = (myWindow.width - s.obwidth) + 'px';
				if ($('messages')) $('messages').style.width = parseInt($('messagebar').style.width) - 42 + 'px';
            }
            if ($('dashboardalertbar')) {
                $('dashboardalertbar').style.bottom = s.obbottom + 'px';
                $('dashboardalertbar').style.left = s.obleft + 'px';
                $('dashboardalertbar').style.width = (myWindow.width - s.obwidth) + 'px';
				
				if ($('alerts')) $('alerts').style.width = parseInt($('dashboardalertbar').style.width) - 42 + 'px';
            }
            if ($('reportbar')) {
                $('reportbar').style.top = s.obtop + 'px';
                $('reportbar').style.left = s.obleft + 'px';
                $('reportbar').style.width = (myWindow.width - s.obwidth) + 'px';
            }
            if($('reportsboard'))
            {
                $('pagecontent').style.height = (myWindow.height - s.pagecontent) - 40 + 'px';
            }

            //correct gap between mainnav and pagetoolbar for Google Chrome, Safari and Explorer 8
            if ($('mainnav')) {
                if ((myBrowser == 'Mozilla an unknown version') || (myBrowser == 'Safari 525.21') || (myBrowser == 'Explorer 8')){
                    $('mainnav').style.height =  '29px';
                }
            }
            setMovieTab();
            fixIEScrollbar();

            /*
        Google Chrome beta doesn't recognize setStyle from prototype yet.
        disable setStyle for now.
             */
            /*
    // set heights
    if($('sidebartreeview')) {
        $('sidebartreeview').setStyle({ height: (myWindow.height - s.sidebar) + 'px' });
        if($('standard_flash')) {
            $('sidebar').setStyle({top:'125px'});
        } else {
            $('sidebar').setStyle({top:'80px'});
        }	
    }
    $('pagecontent').setStyle({ height: (myWindow.height - s.pagecontent) + 'px' });
    if ($('messagebar')) {
      $('messagebar').setStyle({
        bottom: s.obbottom + 'px',
        left: s.obleft + 'px',
        width: (myWindow.width - s.obwidth) + 'px'
      });
    }
    if ($('dashboardalertbar')) {
      $('dashboardalertbar').setStyle({
        bottom: s.obbottom + 'px',
        left: s.obleft + 'px',
        width: (myWindow.width - s.obwidth) + 'px'
      });
    }
    if ($('reportbar')) {
      $('reportbar').setStyle({
        top: s.obtop + 'px',
        left: s.obleft + 'px',
        width: (myWindow.width - s.obwidth) + 'px'
      });
    }
    
    //correct gap between mainnav and pagetoolbar for Google Chrome
    if ($('mainnav')) {
	if (myBrowser == 'Mozilla an unknown version') {
		$('mainnav').setStyle({
			height: '29px'
		});
	}
    }
             */
    
        }


        /*
         *  Selects the option with given value for a selectbox
         */
        Element.addMethods('select', {
            selectValue: function(element, value) {
                element = $(element);
                for(i = 0; i < element.options.length; i++) {
                    if(element.options[i].value == value) element.options[i].selected = true;
                }
                return element;
            }
        });


        /* get the window size  */
        function getWindowSize() {
    
            var windowWidth, windowHeight;
    
            switch (myBrowser.split(" ")[0]) {
                case 'Firefox':
                case 'Mozilla':
                case 'Safari':
                    windowWidth = self.innerWidth;
                    windowHeight = self.innerHeight;
                    break;
                case 'Explorer':
                    windowWidth = document.body.clientWidth;
                    windowHeight = document.documentElement.clientHeight;
                    break;
                default:  // invalid browser
                    return null;
                    break;
            }
    
            return { width: windowWidth, height: windowHeight };
        }


        /* opens a menu div  */
        function openMenu(elId, event, opts) {
            var myWindow		= getWindowSize();
            var	elDimensions	= $(elId).getDimensions();
            var windowOffset	= 20;
		
            pxLeft = (event.clientX + elDimensions.width > myWindow.width) ? myWindow.width - elDimensions.width - windowOffset : event.clientX;
            pxTop = (event.clientY + elDimensions.height > myWindow.height) ? myWindow.height - elDimensions.height - windowOffset : event.clientY;
		
            pxLeft	+= 'px';
            pxTop		+= 'px';

            // set the position for the element
            $(elId).setStyle({left: pxLeft, top: pxTop});
            Effect.Appear(elId, { duration: 0.1, from: 0, to: 0.8 });
	
            // add event handler for mouseout of menu
            Event.observe($(elId), 'mouseout',  function(e) {
                if(Position.within( $(elId), Event.pointerX(e), Event.pointerY(e))) return;
                closeMenu(elId);
            });
        }

        /* closes a menu div and detaches event handler */
        function closeMenu(elId) {
	
            Effect.Fade(elId, { duration: 0.2, from: 0.8, to :0 });
	
            // remove event handler for mouseout of menu DRY WHEN THERE'S SOME TIME
            Event.stopObserving($(elId), 'mouseout',  function(e) {
                if(Position.within( $(elId), Event.pointerX(e), Event.pointerY(e))) return;
                closeMenu(elId);
            });
        }



        /*
         * Make an element act as a submit button, when no formId is given, the first
         * ancester form is submitted
         */
        function actAsSubmit(elem, formId) {
            if(formId) $(formId).submit();
            else {
                ancestors = elem.ancestors();
                ancestors.each(function(ancestor) {
                    if($(ancestor).tagName == 'FORM') {
                        $(ancestor).submit();
                        return true;
                    }
                });
                return false;
            }
        }

        function showFlash(string) {
            removeFlash();
            new Insertion.Top('content', '<div id=\'standard_flash\' class=\'flash success\' onclick=\'removeFlash();\'>' + string + '</div>');
            resizeBoxes();
        }

        function removeFlash() {
            $('content').removeChild($('standard_flash')); 
            resizeBoxes();
        }

        function setMovieTab() {
             var _el = $('movietab');
             var _tb = $('pagetoolbar');

             if (!_el || !_tb) return;

             var _px = _tb.viewportOffset().top - parseInt(_el.getStyle('height'));
             _el.style.top = _px + 'px';
             _el.style.width = getMovieWidth() + 'px';
        }

        function getLastTabsLeft() {
            var _lt = $$('#mainnav li').last();
            if (!_lt) return 100;
            return (_lt.viewportOffset().left + parseInt(_lt.getStyle('width')));
        }

        function getMovieWidth() {
            var _width = (screen.width - 40 /* padding from tab + offset-right */ - getLastTabsLeft());
            if (/*@cc_on!@*/0) { _width -= 4}
            return _width;
        }

        
        
        // code makes sure the scrollbar on the bottom of the 
        // treeview is visible in IE, in all other browsers
        // this seems to work fine
        function fixIEScrollbar() {
             
             // only apply to IE  note the comments is a hack
             if (!/*@cc_on!@*/0) return;  
             
             // make the sidebar view 15px shorter 
             // (the width of a scrollbar in IE)
             var _el =$('sidebartreeview')
             if (!_el) return;
             var _px = parseInt(_el.getStyle('height').sub('px', ''));
             
             _el.style.height = (_px - 15) + 'px';
             
             // and set the boxfooter to a margin of the same 15px, so the 
             // scrollbar seems to be in between
             _el = $('tree_boxfooter');
             _el.setStyle({ marginTop:  '15px' });

            
             
         }
        






/**
*
s*  This makes a sprintf method for javascript.
*  This is used to translate the frase to be sprintf'd
*  Javascript sprintf
*  http://www.webtoolkit.info/
*
**/

sprintfWrapper = {

	init : function () {

		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }

		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;

		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }

			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);

		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }

		var code = null;
		var match = null;
		var i = null;

		for (i=0; i<matches.length; i++) {

			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}

			newString += strings[i];
			newString += substitution;

		}
		newString += strings[i];

		return newString;

	},

	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}

sprintf = sprintfWrapper.init;





        /**
         * The notifier can be used for notification of messages such as "loading"
         * when retrieving new points.
         * 
         * This could actually use some refactoring and prototype utility methods
         * What also could be implemented: remove duplicates from list.
         * For some reason the uniq() method doesn't work.
         */
        Notifier = Class.create();
        Notifier.prototype = {
            initialize: function(opts) {
        
                // set in middle of screen using the Position object of prototype
                this.elId           = 'notifier';
                this.notId          = 'notification';
                this.opacity        = 0.8;
                this.queue          = [];
                this.alertDelayTime	= 5;
                this.showing        = false;           // indicates if notifier is shown
                this.showingMsg     = false;           // indicates if currently message is shown
                this.showingEndless = false;           // indicates if endless message is open
                this.ENDLESS        = 'ENDLESS';
            },
  
            /**
             * Update the contents for the notifier
             */
            update: function(a) {
                $(this.notId).update(a);
            },
  
            /**
             * Queue a new notification and show the notifier if neccesary
             */
            show: function(msg, opts) {
        
                opts					= opts || {};
                opts.duration	= opts.duration || this.alertDelayTime;

                this.queue.push({message: msg, duration: opts.duration});
                if(!this.showing) Effect.Appear(this.elId, {from: 0, to: this.opacity});
                this.startHandler();		
            },
  
            /**
             * Hide the notifier
             */
            hide: function() {
                Effect.Fade(this.elId, {from: this.opacity, to: 0});
            },
    
            /**
             * Stop showing an endless message
             */
            stop: function(message) {
        
                message = message.toLowerCase().strip();		
                index = -1;
        
                // find message in queue
                for(i = 0; i < this.queue.length; i++) {
                    if(this.queue[i].message.toLowerCase().strip() == message) {
                        index = i;
                        break;
                    }
                }
        
                // if found remove from queue
                if(index >=  0) {
                    this.queue[index] = null;
                    this.queue = this.queue.compact();
                    this.showingEndless = false;
                }
        
                this.startHandler();
            },
    
            /**
             * Private function for showing a new notification in the notifier
             */
            showMessage: function(msgObj) {
                this.update(msgObj.message);
                // optional for visual effect when changing message
            },
    
            /**
             * Private function for hiding the current message
             */
            hideMessage: function() {
                // optional for visual effect when changing message
            },
    
            /**
             * Start the message handler or stop it if queue is empty
             */
            startHandler: function() {		
                this.showing = true;
        
                if(this.queue.length > 0) {
                    if(!this.showingMsg) this.handleQueue();
                }
                else if(!this.showingMsg) this.stopHandler();
            },
    
            /**
             * Stop the message handler
             */
            stopHandler: function() {
                this.showing = false;
                this.hide();
            },
    
            /**
             * Handle the message queue
             */
            handleQueue: function() {
        
                // get first message of the queue, if endless is shown it's this one
                msgObj = Object.clone(this.queue[0]);
        
                // check if duration is endless and not showing endless
                if(msgObj.duration == this.ENDLESS && !this.showingEndless) {
                    // show new endless message
                    this.showMessage(msgObj);
                    this.showingEndless = true;
                    this.startHandler();
                }
                else {
                    // show durable message
                    index = 0;
            
                    // find first durable message in queue
                    for(i = 0; i < this.queue.length; i++) {
                        if(this.queue[i].duration != this.ENDLESS) {
                            index = i;
                            break;
                        }
                    }
            
                    if(index > 0 || !this.showingEndless) {
                        // show new durable message
                        msgObj = Object.clone(this.queue[index]);
                        this.queue[index] = null;
                        this.queue = this.queue.compact().uniq();
                
                        this.showingMsg = true;
                        this.showMessage(msgObj);
    
                        var i = 0;
                        new PeriodicalExecuter(function(pe) {
                            if(++i > parseInt(msgObj.duration)) {
                                pe.stop();
                                this.showingMsg = false;
                                this.startHandler();
                            }
                        }.bind(this), 1);
                
                    }
                    else if (this.showingEndless) {
                        // if all durables are shown show endless message again
                        this.showMessage(this.queue[0]);
                    }
                }
            }
        }
        var notifier = new Notifier();
