GreenboxOptions = Object.extend({
    fileLoadingImage:        '/greenbox/loading.gif',     
    fileBottomNavCloseImage: '/greenbox/close.png',

    overlayOpacity: 0.95,

    animate: true,
    resizeSpeed: 12,

    borderSize: 21,
    
	labelImage: "Bild",
	labelOf: "von"
}, window.GreenboxOptions || {});


Greenbox = Class.create();

window.onresize = function() {
	Greenbox.windowResized();
};

Greenbox.prototype = {
	tr_author: undefined,
    tr_authorLinkUsername: undefined,
	tr_link: undefined,
	activeImage: undefined,
	imageArray: undefined,
    
    initialize: function() {    
        this.updateImageList();
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
        this.resizeDuration = GreenboxOptions.animate ? ((11 - GreenboxOptions.resizeSpeed) * 0.15) : 0;
	    this.overlayDuration = GreenboxOptions.animate ? 0.5 : 0;
        var size = (GreenboxOptions.animate ? 250 : 1) + 'px';

		var objBody = $$('body')[0];

		objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
        objBody.appendChild(Builder.node('div',{id:'greenbox'}, 
        	Builder.node('div',{id:'elementsContainer'}, [
        		Builder.node('div',{id:'thumbnailNav'}, [
        			Builder.node('div',{id:'greenboxLogo'}),
        			Builder.node('h4', {id:'greenboxTitle'}),
                    Builder.node('img',{id:'greenboxThumb1'}),
                    Builder.node('img',{id:'greenboxThumb2'}),
                    Builder.node('img',{id:'greenboxThumb3'}),
                    Builder.node('img',{id:'greenboxThumb4'}),
                    Builder.node('img',{id:'greenboxThumb5'}),
                    Builder.node('img',{id:'greenboxThumb6'}),
                    Builder.node('img',{id:'greenboxThumb7'}),
                    Builder.node('img',{id:'greenboxThumb8'}),
                    Builder.node('img',{id:'greenboxThumb9'}),
                    Builder.node('img',{id:'greenboxThumb10'}),
                    Builder.node('img',{id:'greenboxThumb11'}),
                    Builder.node('img',{id:'greenboxThumb12'}),
                    Builder.node('img',{id:'greenboxArrowLeft', src:'/greenbox/arrow_left.png'}),
                    Builder.node('div',{id:'greenboxPagination'}),
                    Builder.node('img',{id:'greenboxArrowRight', src:'/greenbox/arrow_right.png'}),
                    //Builder.node('div',{id:'bottomNav'},
                        Builder.node('a',{id:'bottomNavClose', href: '#' },
                            Builder.node('img', { src: GreenboxOptions.fileBottomNavCloseImage })
                        )
                    //) 
                ]),
                Builder.node('div',{id:'imagePositioner'}, [
            		Builder.node('div',{id:'outerImageContainer'},
                		Builder.node('div',{id:'imageContainer'}, [
                    		Builder.node('img',{id:'greenboxImage'}), 
                    		Builder.node('div',{id:'hoverNav'}, [
                        		Builder.node('a',{id:'prevLink', href: '#' }),
                        		Builder.node('a',{id:'nextLink', href: '#' })
                    		]),
                    		Builder.node('div',{id:'loading'}, 
                       			Builder.node('a',{id:'loadingLink', href: '#' }, 
                            		Builder.node('img', {src: GreenboxOptions.fileLoadingImage})
                        		)
                    		)
                		])
            		),
            		Builder.node('div', {id:'imageDataContainer'},
                		Builder.node('div',{id:'imageData'}, [
                			Builder.node('div',{id:'locationDetails'}, [
                        		Builder.node('span',{id:'loccaption'})
                    		]),
                    		Builder.node('div',{id:'imageDetails'}, [
                        		Builder.node('span',{id:'caption'}),
                        		Builder.node('span',{id:'numberDisplay'})
                    		])
                		])
            		)
            	])
            ])
        ));


		$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('greenbox').hide().observe('click', (function(event) { if (event.element().id == 'greenbox') this.end(); }).bind(this));
		$('outerImageContainer').setStyle({ width: size, height: size });
		$('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
		$('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
		$('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		
		$('greenboxArrowLeft').observe('click', (function(event) { event.stop(); this.slideNav(false); }).bind(this));
		$('greenboxArrowRight').observe('click', (function(event) { event.stop(); this.slideNav(true); }).bind(this));
		
		$('greenboxThumb1').observe('click', (function(event) { event.stop(); this.changeImage(0 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb2').observe('click', (function(event) { event.stop(); this.changeImage(1 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb3').observe('click', (function(event) { event.stop(); this.changeImage(2 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb4').observe('click', (function(event) { event.stop(); this.changeImage(3 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb5').observe('click', (function(event) { event.stop(); this.changeImage(4 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb6').observe('click', (function(event) { event.stop(); this.changeImage(5 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb7').observe('click', (function(event) { event.stop(); this.changeImage(6 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb8').observe('click', (function(event) { event.stop(); this.changeImage(7 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb9').observe('click', (function(event) { event.stop(); this.changeImage(8 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb10').observe('click', (function(event) { event.stop(); this.changeImage(9 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb11').observe('click', (function(event) { event.stop(); this.changeImage(10 + ((this.activePage-1) * 12)); }).bind(this));
		$('greenboxThumb12').observe('click', (function(event) { event.stop(); this.changeImage(11 + ((this.activePage-1) * 12)); }).bind(this));


		$('greenboxThumb1').observe('mouseover', (function(event) { $('greenboxThumb1').addClassName('active'); }).bind(this));
		$('greenboxThumb1').observe('mouseout',  (function(event) { $('greenboxThumb1').removeClassName('active'); }).bind(this));
		$('greenboxThumb2').observe('mouseover', (function(event) { $('greenboxThumb2').addClassName('active'); }).bind(this));
		$('greenboxThumb2').observe('mouseout',  (function(event) { $('greenboxThumb2').removeClassName('active'); }).bind(this));
		$('greenboxThumb3').observe('mouseover', (function(event) { $('greenboxThumb3').addClassName('active'); }).bind(this));
		$('greenboxThumb3').observe('mouseout',  (function(event) { $('greenboxThumb3').removeClassName('active'); }).bind(this));
		$('greenboxThumb4').observe('mouseover', (function(event) { $('greenboxThumb4').addClassName('active'); }).bind(this));
		$('greenboxThumb4').observe('mouseout',  (function(event) { $('greenboxThumb4').removeClassName('active'); }).bind(this));
		$('greenboxThumb5').observe('mouseover', (function(event) { $('greenboxThumb5').addClassName('active'); }).bind(this));
		$('greenboxThumb5').observe('mouseout',  (function(event) { $('greenboxThumb5').removeClassName('active'); }).bind(this));
		$('greenboxThumb6').observe('mouseover', (function(event) { $('greenboxThumb6').addClassName('active'); }).bind(this));
		$('greenboxThumb6').observe('mouseout',  (function(event) { $('greenboxThumb6').removeClassName('active'); }).bind(this));
		$('greenboxThumb7').observe('mouseover', (function(event) { $('greenboxThumb7').addClassName('active'); }).bind(this));
		$('greenboxThumb7').observe('mouseout',  (function(event) { $('greenboxThumb7').removeClassName('active'); }).bind(this));
		$('greenboxThumb8').observe('mouseover', (function(event) { $('greenboxThumb8').addClassName('active'); }).bind(this));
		$('greenboxThumb8').observe('mouseout',  (function(event) { $('greenboxThumb8').removeClassName('active'); }).bind(this));
		$('greenboxThumb9').observe('mouseover', (function(event) { $('greenboxThumb9').addClassName('active'); }).bind(this));
		$('greenboxThumb9').observe('mouseout',  (function(event) { $('greenboxThumb9').removeClassName('active'); }).bind(this));
		$('greenboxThumb10').observe('mouseover', (function(event) { $('greenboxThumb10').addClassName('active'); }).bind(this));
		$('greenboxThumb10').observe('mouseout',  (function(event) { $('greenboxThumb10').removeClassName('active'); }).bind(this));
		$('greenboxThumb11').observe('mouseover', (function(event) { $('greenboxThumb11').addClassName('active'); }).bind(this));
		$('greenboxThumb11').observe('mouseout',  (function(event) { $('greenboxThumb11').removeClassName('active'); }).bind(this));
		$('greenboxThumb12').observe('mouseover', (function(event) { $('greenboxThumb12').addClassName('active'); }).bind(this));
		$('greenboxThumb12').observe('mouseout',  (function(event) { $('greenboxThumb12').removeClassName('active'); }).bind(this));

        var th = this;
        (function(){
            var ids = 
                'overlay greenbox outerImageContainer imageContainer greenboxImage hoverNav prevLink nextLink greenboxPagination loading loadingLink ' + 
                'imageDataContainer imageData imageDetails locationDetails caption loccaption numberDisplay bottomNav bottomNavClose thumbnailNav, elementsContainer';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
    },
    
    windowResized: function() {
    	var arrayPageSize = this.getPageSize();
    	$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
    },

    updateImageList: function() {   
        this.updateImageList = Prototype.emptyFunction;
        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=greenbox]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },
        
    start: function(imageLink) { 
    	$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: GreenboxOptions.overlayOpacity });

        var imageNum = 0;       

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var greenboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var greenboxLeft = arrayPageScroll[0];
        this.greenbox.setStyle({ top: greenboxTop + 'px', left: greenboxLeft + 'px' }).show();
            
    	this.imageArray = new Array();   
    	imageId = "";
    	for (i = 0; i < imageLink.href.length; i++) {
    		if (imageLink.href.substr(i,1) == "0"
    		 || imageLink.href.substr(i,1) == "1"
    		 || imageLink.href.substr(i,1) == "2"
    		 || imageLink.href.substr(i,1) == "3"
    		 || imageLink.href.substr(i,1) == "4"
    		 || imageLink.href.substr(i,1) == "5"
    		 || imageLink.href.substr(i,1) == "6"
    		 || imageLink.href.substr(i,1) == "7"
    		 || imageLink.href.substr(i,1) == "8"
    		 || imageLink.href.substr(i,1) == "9") {
				imageId = imageId + imageLink.href.substr(i,1);
			}
    	}         
        
        new Ajax.Request('/travelreportimage/greenbox/image/' + imageId + '/data.xml?salt=' + Math.random(),
  			{
  			    asynchronous:false,
    			method:'get',
    			onSuccess: ajaxget
    			,
    			onFailure: function(){
    			}
  			}
  		);

    },
        
    changeImage: function(imageNum) {   
        this.activeImage = imageNum;
        
        if (GreenboxOptions.animate) this.loading.show();
        this.greenboxImage.hide();
        this.hoverNav.hide();
        this.prevLink.hide();
        this.nextLink.hide();

        this.imageDataContainer.setStyle({opacity: .0001});
        this.numberDisplay.hide();      
        
        var imgPreloader = new Image();
        
        // once image is preloaded, resize image container


        imgPreloader.onload = (function(){
            this.greenboxImage.src = this.imageArray[this.activeImage][2];
            this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.imageArray[this.activeImage][2];
    },
    
    resizeImageContainer: function(imgWidth, imgHeight) {
        var widthCurrent  = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();
        var widthNew  = (imgWidth  + GreenboxOptions.borderSize * 2);
        var heightNew = (imgHeight + GreenboxOptions.borderSize * 2);
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }

        (function(){
            this.prevLink.setStyle({ height: imgHeight + 'px' });
            this.nextLink.setStyle({ height: imgHeight + 'px' });
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },
    
    showImage: function(){
        this.loading.hide();
        new Effect.Appear(this.greenboxImage, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){ this.updateDetails(); }).bind(this) 
        });
        this.updateNav();
        this.preloadNeighborImages();
    },
    
    updateDetails: function() {
    
        // if caption is not null
        if (typeof(this.imageArray[this.activeImage][3]) != "undefined"){
            this.caption.update(this.imageArray[this.activeImage][3] + "&nbsp;").show();
        } else {
        	this.caption.update("&nbsp;").show();
        }
        
        if (typeof(this.imageArray[this.activeImage][4]) != "undefined") {
        	if (typeof(this.imageArray[this.activeImage][5]) != "undefined") {
        		var mycaption = this.imageArray[this.activeImage][4] + " / " + this.imageArray[this.activeImage][5];
        	} else {
        		var mycaption = this.imageArray[this.activeImage][4];
        	}
        } else {
        	if (typeof(this.imageArray[this.activeImage][5]) != "undefined") {
        		var mycaption = this.imageArray[this.activeImage][5];
        	} else {
        		var mycaption = "&nbsp;";
        	}
        }
        
        this.loccaption.update(mycaption).show();
        
        // if image is part of set display 'Image x of x' 
        if (this.imageArray.length > 1){
            this.numberDisplay.update( GreenboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + GreenboxOptions.labelOf + '  ' + this.imageArray.length).show();
        }

        new Effect.Parallel(
            [ 
                new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
                new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) 
            ], 
            { 
                duration: this.resizeDuration, 
                afterFinish: (function() {
	                // update overlay size and update nav
	                var arrayPageSize = this.getPageSize();
	                this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
                }).bind(this)
            } 
        );
    },
    
    slideNav: function(direction) {
    	if (direction) {
        	this.activePage++;
    	} else {
    		this.activePage--;
    	}
    	$('greenboxTitle').innerHTML = '<a href="' + tr_link + '">' + tr_title + '</a>';
    	
    	for (i = 0; i < 12; i++) {
        	if ((i + ((this.activePage-1) * 12)) < this.imageArray.length) {
        		$(('greenboxThumb' + (i+1))).src = this.imageArray[(i + ((this.activePage-1) * 12))][1];
        		$(('greenboxThumb' + (i+1))).setStyle({ display: 'inline' });
        	} else {
        		$(('greenboxThumb' + (i+1))).setStyle({ display: 'none' });
        	}
        }
        
        if (this.activePage == 1) {
        	$('greenboxArrowLeft').setStyle({ display: 'none' });
        } else {
        	$('greenboxArrowLeft').setStyle({ display: 'inline' });
        }
        
        var maxPage = ((this.imageArray.length - (this.imageArray.length % 12)) / 12 ) + 1;
        $('greenboxPagination').innerHTML = this.activePage + " / " + maxPage;
         
            
		if (this.activePage == ((this.imageArray.length - (this.imageArray.length % 12)) / 12 ) + 1) {
        	$('greenboxArrowRight').setStyle({ display: 'none' });
        } else {
        	$('greenboxArrowRight').setStyle({ display: 'inline' });
        }
    },
    
    updateNav: function() {
        this.hoverNav.show();               
        if (this.activeImage > 0) this.prevLink.show();
        if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
        this.enableKeyboardNav();
        
        $('greenboxTitle').innerHTML = '<a href="' + tr_link + '">' + tr_title + '</a>';
        
        this.activePage = ((this.activeImage - (this.activeImage % 12)) / 12 ) + 1;
        for (i = 0; i < 12; i++) {
        	if ((i + ((this.activePage-1) * 12)) < this.imageArray.length) {
        		$(('greenboxThumb' + (i+1))).src = this.imageArray[(i + ((this.activePage-1) * 12))][1];
        		$(('greenboxThumb' + (i+1))).setStyle({ display: 'inline' });
        	} else {
        		$(('greenboxThumb' + (i+1))).setStyle({ display: 'none' });
        	}
        }
        
        if (this.activePage == 1) {
        	$('greenboxArrowLeft').setStyle({ display: 'none' });
        } else {
        	$('greenboxArrowLeft').setStyle({ display: 'inline' });
        }
        
        var maxPage = ((this.imageArray.length - (this.imageArray.length % 12)) / 12 ) + 1;
        $('greenboxPagination').innerHTML = this.activePage + " / " + maxPage;
            
		if (this.activePage == ((this.imageArray.length - (this.imageArray.length % 12)) / 12 ) + 1) {
        	$('greenboxArrowRight').setStyle({ display: 'none' });
        } else {
        	$('greenboxArrowRight').setStyle({ display: 'inline' });
        }    
    },
    
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction); 
    },

    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction); 
    },
    
    keyboardAction: function(event) {
        var keycode = event.keyCode;
        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }
        var key = String.fromCharCode(keycode).toLowerCase();
        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
            this.end();
        } else if ((key == 'p') || (keycode == 37)){ // display previous image
            if (this.activeImage != 0){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)){ // display next image
            if (this.activeImage != (this.imageArray.length - 1)){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage + 1);
            }
        }
    },
    
    preloadNeighborImages: function(){
        var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1){
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[this.activeImage + 1][2];
        }
        if (this.activeImage > 0){
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.activeImage - 1][2];
        }
    },

    end: function() {
    	this.disableKeyboardNav();
        this.greenbox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },
    
    getPageSize: function() {
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	},
	
	pushImage: function(arr) {
		this.imageArray.push(arr);
	}

}



function ajaxget(transport) {
    var response = transport.responseText || "no response text";
    var xotree = new XML.ObjTree();
    var tree = xotree.parseXML(response);
    
    tr_author             = tree.travelreport["-author"];
    tr_authorLinkUsername = tree.travelreport["-authorlinkusername"];
    tr_link               = tree.travelreport["-link"];
    tr_title              = tree.travelreport["-title"];
    				
    var locationName = "";
    var locationCountry = "";
    
    var imageNum = 0;
    var cnt = 0;
    				
    if (typeof tree.travelreport.location != 'undefined') {
    	if (typeof tree.travelreport.location.length != 'undefined') {
	    	for (l = 0; l < tree.travelreport.location.length; l++) {
	    		locationName    = tree.travelreport.location[l]["-name"];
	    		locationCountry = tree.travelreport.location[l]["-country"];
	
	    		if (typeof tree.travelreport.location[l].image != 'undefined') {
	    			if (typeof tree.travelreport.location[l].image.length != 'undefined') {
	    				for (i = 0; i < tree.travelreport.location[l].image.length; i++) {
	    					if (imageId == tree.travelreport.location[l].image[i]["-id"]) {
	    						imageNum = cnt;
	    					}
	    					gb.pushImage([
	    						tree.travelreport.location[l].image[i]["-id"],
	    						tree.travelreport.location[l].image[i].thumb,
								tree.travelreport.location[l].image[i].large,
								tree.travelreport.location[l].image[i].description,
								locationName,
								locationCountry
	    					]);
	    					cnt++;
	    				}
	    			} else {
	    				if (imageId == tree.travelreport.location[l].image["-id"]) {
	    					imageNum = cnt;
	    				}
	    				gb.pushImage([
	    					tree.travelreport.location[l].image["-id"],
	    					tree.travelreport.location[l].image.thumb,
							tree.travelreport.location[l].image.large,
							tree.travelreport.location[l].image.description,
							locationName,
							locationCountry
	    				]);
	    				cnt++;
	    			}
	    		}
	    	}
	    } else {
    		locationName    = tree.travelreport.location["-name"];
    		locationCountry = tree.travelreport.location["-country"];

    		if (typeof tree.travelreport.location.image != 'undefined') {
    			if (typeof tree.travelreport.location.image.length != 'undefined') {
    				for (i = 0; i < tree.travelreport.location.image.length; i++) {
    					if (imageId == tree.travelreport.location.image[i]["-id"]) {
    						imageNum = cnt;
    					}
    					gb.pushImage([
    						tree.travelreport.location.image[i]["-id"],
    						tree.travelreport.location.image[i].thumb,
							tree.travelreport.location.image[i].large,
							tree.travelreport.location.image[i].description,
							locationName,
							locationCountry
    					]);
    					cnt++;
    				}
    			} else {
    				if (imageId == tree.travelreport.location.image["-id"]) {
    					imageNum = cnt;
    				}
    				gb.pushImage([
    					tree.travelreport.location.image["-id"],
    					tree.travelreport.location.image.thumb,
						tree.travelreport.location.image.large,
						tree.travelreport.location.image.description,
						locationName,
						locationCountry
    				]);
    				cnt++;
    			}
    		}
	    }
    }
  	gb.changeImage(imageNum);
}

if ( typeof(XML) == 'undefined' ) XML = function() {};

//  constructor

XML.ObjTree = function () {
    return this;
};

//  class variables

XML.ObjTree.VERSION = "0.24";

//  object prototype

XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n';
XML.ObjTree.prototype.attr_prefix = '-';
XML.ObjTree.prototype.overrideMimeType = 'text/xml';

//  method: parseXML( xmlsource )

XML.ObjTree.prototype.parseXML = function ( xml ) {
    var root;
    if ( window.DOMParser ) {
        var xmldom = new DOMParser();
//      xmldom.async = false;           // DOMParser is always sync-mode
        var dom = xmldom.parseFromString( xml, "application/xml" );
        if ( ! dom ) return;
        root = dom.documentElement;
    } else if ( window.ActiveXObject ) {
        xmldom = new ActiveXObject('Microsoft.XMLDOM');
        xmldom.async = false;
        xmldom.loadXML( xml );
        root = xmldom.documentElement;
    }
    if ( ! root ) return;
    return this.parseDOM( root );
};

//  method: parseHTTP( url, options, callback )

XML.ObjTree.prototype.parseHTTP = function ( url, options, callback ) {
    var myopt = {};
    for( var key in options ) {
        myopt[key] = options[key];                  // copy object
    }
    if ( ! myopt.method ) {
        if ( typeof(myopt.postBody) == "undefined" &&
             typeof(myopt.postbody) == "undefined" &&
             typeof(myopt.parameters) == "undefined" ) {
            myopt.method = "get";
        } else {
            myopt.method = "post";
        }
    }
    if ( callback ) {
        myopt.asynchronous = true;                  // async-mode
        var __this = this;
        var __func = callback;
        var __save = myopt.onComplete;
        myopt.onComplete = function ( trans ) {
            var tree;
            if ( trans && trans.responseXML && trans.responseXML.documentElement ) {
                tree = __this.parseDOM( trans.responseXML.documentElement );
            } else if ( trans && trans.responseText ) {
                tree = __this.parseXML( trans.responseText );
            }
            __func( tree, trans );
            if ( __save ) __save( trans );
        };
    } else {
        myopt.asynchronous = false;                 // sync-mode
    }
    var trans;
    if ( typeof(HTTP) != "undefined" && HTTP.Request ) {
        myopt.uri = url;
        var req = new HTTP.Request( myopt );        // JSAN
        if ( req ) trans = req.transport;
    } else if ( typeof(Ajax) != "undefined" && Ajax.Request ) {
        var req = new Ajax.Request( url, myopt );   // ptorotype.js
        if ( req ) trans = req.transport;
    }
//  if ( trans && typeof(trans.overrideMimeType) != "undefined" ) {
//      trans.overrideMimeType( this.overrideMimeType );
//  }
    if ( callback ) return trans;
    if ( trans && trans.responseXML && trans.responseXML.documentElement ) {
        return this.parseDOM( trans.responseXML.documentElement );
    } else if ( trans && trans.responseText ) {
        return this.parseXML( trans.responseText );
    }
}

//  method: parseDOM( documentroot )

XML.ObjTree.prototype.parseDOM = function ( root ) {
    if ( ! root ) return;

    this.__force_array = {};
    if ( this.force_array ) {
        for( var i=0; i<this.force_array.length; i++ ) {
            this.__force_array[this.force_array[i]] = 1;
        }
    }

    var json = this.parseElement( root );   // parse root node
    if ( this.__force_array[root.nodeName] ) {
        json = [ json ];
    }
    if ( root.nodeType != 11 ) {            // DOCUMENT_FRAGMENT_NODE
        var tmp = {};
        tmp[root.nodeName] = json;          // root nodeName
        json = tmp;
    }
    return json;
};

//  method: parseElement( element )

XML.ObjTree.prototype.parseElement = function ( elem ) {
    //  COMMENT_NODE
    if ( elem.nodeType == 7 ) {
        return;
    }

    //  TEXT_NODE CDATA_SECTION_NODE
    if ( elem.nodeType == 3 || elem.nodeType == 4 ) {
        var bool = elem.nodeValue.match( /[^\x00-\x20]/ );
        if ( bool == null ) return;     // ignore white spaces
        return elem.nodeValue;
    }

    var retval;
    var cnt = {};

    //  parse attributes
    if ( elem.attributes && elem.attributes.length ) {
        retval = {};
        for ( var i=0; i<elem.attributes.length; i++ ) {
            var key = elem.attributes[i].nodeName;
            if ( typeof(key) != "string" ) continue;
            var val = elem.attributes[i].nodeValue;
            if ( ! val ) continue;
            key = this.attr_prefix + key;
            if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
            cnt[key] ++;
            this.addNode( retval, key, cnt[key], val );
        }
    }

    //  parse child nodes (recursive)
    if ( elem.childNodes && elem.childNodes.length ) {
        var textonly = true;
        if ( retval ) textonly = false;        // some attributes exists
        for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {
            var ntype = elem.childNodes[i].nodeType;
            if ( ntype == 3 || ntype == 4 ) continue;
            textonly = false;
        }
        if ( textonly ) {
            if ( ! retval ) retval = "";
            for ( var i=0; i<elem.childNodes.length; i++ ) {
                retval += elem.childNodes[i].nodeValue;
            }
        } else {
            if ( ! retval ) retval = {};
            for ( var i=0; i<elem.childNodes.length; i++ ) {
                var key = elem.childNodes[i].nodeName;
                if ( typeof(key) != "string" ) continue;
                var val = this.parseElement( elem.childNodes[i] );
                if ( ! val ) continue;
                if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
                cnt[key] ++;
                this.addNode( retval, key, cnt[key], val );
            }
        }
    }
    return retval;
};

//  method: addNode( hash, key, count, value )

XML.ObjTree.prototype.addNode = function ( hash, key, cnts, val ) {
    if ( this.__force_array[key] ) {
        if ( cnts == 1 ) hash[key] = [];
        hash[key][hash[key].length] = val;      // push
    } else if ( cnts == 1 ) {                   // 1st sibling
        hash[key] = val;
    } else if ( cnts == 2 ) {                   // 2nd sibling
        hash[key] = [ hash[key], val ];
    } else {                                    // 3rd sibling and more
        hash[key][hash[key].length] = val;
    }
};

//  method: writeXML( tree )

XML.ObjTree.prototype.writeXML = function ( tree ) {
    var xml = this.hash_to_xml( null, tree );
    return this.xmlDecl + xml;
};

//  method: hash_to_xml( tagName, tree )

XML.ObjTree.prototype.hash_to_xml = function ( name, tree ) {
    var elem = [];
    var attr = [];
    for( var key in tree ) {
        if ( ! tree.hasOwnProperty(key) ) continue;
        var val = tree[key];
        if ( key.charAt(0) != this.attr_prefix ) {
            if ( typeof(val) == "undefined" || val == null ) {
                elem[elem.length] = "<"+key+" />";
            } else if ( typeof(val) == "object" && val.constructor == Array ) {
                elem[elem.length] = this.array_to_xml( key, val );
            } else if ( typeof(val) == "object" ) {
                elem[elem.length] = this.hash_to_xml( key, val );
            } else {
                elem[elem.length] = this.scalar_to_xml( key, val );
            }
        } else {
            attr[attr.length] = " "+(key.substring(1))+'="'+(this.xml_escape( val ))+'"';
        }
    }
    var jattr = attr.join("");
    var jelem = elem.join("");
    if ( typeof(name) == "undefined" || name == null ) {
        // no tag
    } else if ( elem.length > 0 ) {
        if ( jelem.match( /\n/ )) {
            jelem = "<"+name+jattr+">\n"+jelem+"</"+name+">\n";
        } else {
            jelem = "<"+name+jattr+">"  +jelem+"</"+name+">\n";
        }
    } else {
        jelem = "<"+name+jattr+" />\n";
    }
    return jelem;
};

//  method: array_to_xml( tagName, array )

XML.ObjTree.prototype.array_to_xml = function ( name, array ) {
    var out = [];
    for( var i=0; i<array.length; i++ ) {
        var val = array[i];
        if ( typeof(val) == "undefined" || val == null ) {
            out[out.length] = "<"+name+" />";
        } else if ( typeof(val) == "object" && val.constructor == Array ) {
            out[out.length] = this.array_to_xml( name, val );
        } else if ( typeof(val) == "object" ) {
            out[out.length] = this.hash_to_xml( name, val );
        } else {
            out[out.length] = this.scalar_to_xml( name, val );
        }
    }
    return out.join("");
};

//  method: scalar_to_xml( tagName, text )

XML.ObjTree.prototype.scalar_to_xml = function ( name, text ) {
    if ( name == "#text" ) {
        return this.xml_escape(text);
    } else {
        return "<"+name+">"+this.xml_escape(text)+"</"+name+">\n";
    }
};

//  method: xml_escape( text )

XML.ObjTree.prototype.xml_escape = function ( text ) {
    return String(text).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
};

// DISABLED GREENBOX!
document.observe('dom:loaded', function () { if (enableGreenbox) { gb = new Greenbox(); } });

window.onresize = function() {
	gb.windowResized();
};
