		window.currentDropImage = null;
		window.currentDropIdx = -1;
		window.currentDropAngle = 0;
		window.currentDropZoom = 0;
		window.currentDropLeft = -1;
		window.currentDropTop = -1;
        window.oldGallery = [];
        window.inSearchMode = false;
        window.searchOldHTML = '';
        window.currentObjId = -1;
        window.currentCoverageId = -1;

		var MAX_ZOOM = 21;
		var MAX_WIDTH = 443;
		var MAX_HEIGHT = 178;
		var ZOOM_STEP = 20;

		var NUM_THUMBS = 5;

		var dontShowVolvoRangeUntilMouseOut = false;

        function showChildren(obj)
        {
            var children = $(obj).immediateDescendants();
            for(var i=0;i<children.length;i++)
            {
//                if(children[i].tagName.toLowerCase()=='ul')
                    children[i].toggle();
            }
        }

		/**
		 * Build the navigation panel
		 */
		/*function buildNavigationPanel() {
            var navigationPanel = '<ul>';
            if (window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE].length > 0) {
                navigationPanel += '<li class="navigationLink" onclick="jumpToGallery(\'#foto\')">Foto</li>';
            }
            if (window.galleryItemsByType[MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO].length > 0) {
                navigationPanel += '<li class="navigationLink" onclick="jumpToGallery(\'#video\')">Video</li>';
            }
            if (window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE_WITH_OVERLAY].length > 0) {
                navigationPanel += '<li class="navigationLink" onclick="jumpToGallery(\'#volvo\')">Poze salvate concurs Volvo</li>';
            }
            navigationPanel += '</ul>';
            $('navigationPanel').innerHTML = navigationPanel;
        }*/

        /**
		 * Builds the Volvo zone - where all the cars appear. Besides setting the coordinates,
		 * it attaches the onclick events to each car in the gallery
		 */
		function buildDropSource(dropSource, contestId) {
            if (!objIsValid(dropSource)) {
                return;
            }
//			dropSource.hide();
            var dropSourceClose = document.createElement('div');
            dropSourceClose.id = 'dropSourceClose';
            dropSourceClose.onclick = hideVolvoRange;
            dropSource.appendChild(dropSourceClose);

            Event.observe(document, 'mousemove', function(event) {
                var x = Event.pointerX(event);
                var y = Event.pointerY(event);
                if($('rightPanel')) {
                    if(!Position.within($('rightPanel'), x, y)) {
                        dontShowVolvoRangeUntilMouseOut = false;
                    }
                }
            });

            for(var i = 0; i < window.drops.length; i++) {
		        var dropItem = document.createElement('img');
		        dropItem.className = 'dropItem';
		        dropItem.src = window.drops[i].icon.url;
		        dropItem.width = window.drops[i].icon.w;
		        dropItem.height = window.drops[i].icon.h;
		        dropItem.idx = i;

		        dropSource.appendChild(dropItem);

				Event.observe(dropItem, 'mouseover', function(/*event*/) {
                    var dropItemTitle = $('dropItemTitle');
                    var mainCoords = $('main').positionedOffset();
                    dropItemTitle.style.left = (mainCoords.left + 10) + "px";
                    dropItemTitle.style.top = (mainCoords.top + 10) + "px";
                    dropItemTitle.src = window.drops[this.idx].titleImg;
                });
				Event.observe(dropItem, 'mouseout', function(/*event*/) {
                    var dropItemTitle = $('dropItemTitle');
                    dropItemTitle.src = 'images/pixel.gif';
                });
				Event.observe(dropItem, 'click', function(/*event*/) {
					window.currentDropIdx = this.idx;
					if (!$('controls').visible()) {
						positionControls();
					}
					setTimeout('recomputeDropper()', 200);
				});
			}

	        var saveButton = document.createElement('button');
	        saveButton.innerHTML = 'Salvează';
	        saveButton.id = 'saveButton';
	        dropSource.appendChild(saveButton);
			Event.observe($('saveButton'), 'click', function(/*event*/) {
				saveOverlay(contestId);
			});
            var savingMessage = document.createElement('div');
            savingMessage.id = 'savingMessage';
            dropSource.appendChild(savingMessage);

//			dropSource.blindDown({duration:1.3});
		}

		/**
		 * Builds the Volvo zone banner
		 */
		function buildVolvoRangeBanner() {
			var so = new SWFObject("/images/new/galerie2/volvo/banner_start.swf", "volvoRangeIntro", "160", "480", "8", "#CCCCCC");
			so.addVariable("onRollOverGoto", "javascript:showVolvoRange()");
			so.write('volvoRangeBanner');
		}

		/**
		 * Correctly positions the controls on page
		 */
		function positionControls() {
			var mainCoords = $('main').positionedOffset();
			var controls = $('controls');
			controls.style.left = (mainCoords.left + 530) + "px";
			controls.style.top = (mainCoords.top + 420) + "px";
			/*new Effect.Opacity('controls', { from: 1.0, to: 0.3, duration: 0.01 });
			new Effect.Opacity('controlsLeft', { from: 1.0, to: 4.0, duration: 0.01 });
			new Effect.Opacity('controlsRight', { from: 1.0, to: 4.0, duration: 0.01 });*/
			controls.show();
		}

		/**
		 * Use this method to obtain the URL of an image
		 */
		function showMediaObject(idx, variant) {
            var mediaObject = window.currentGallery[idx];
            if (mediaObject.type == MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO) {
                if (variant == VARIANT_100X66) {
                     /*'<img width="100" height="66" ' + (variant == VARIANT_640X480 ? ' id="mainImg"' : '') + ' src="' + window.currentGallery[idx].urlForVariant['' + variant] + '" alt=""/>' +*/
                    return       '<div style="background:url(\'' + window.currentGallery[idx].urlForVariant['' + variant] +
                           '\') no-repeat; width:100px; height:66px;"><img src="/images/new/galerie2/play.gif" style="margin-top:13px; filter: alpha(opacity = 50);-moz-opacity: .65; opacity: .65;"/></div>';
                    //return '<img src="/images/new/galerie/video_icon.gif" alt=""/>';
                } else if (variant == VARIANT_640X480) {
                    return fixEmbeddedVideo(mediaObject.htmlEmbedVideo);
                } else {
                    return '';
                }
            } else {
                return '<img' + (variant == VARIANT_640X480 ? ' id="mainImg"' : '') + ' src="' + window.currentGallery[idx].urlForVariant['' + variant] + '" alt=""/>';
            }
        }

        /**
         * Fixes a problem with youtube embedded videos not showing dynamically (by setting innerHTML) on Internet Explorer 6
         */
        function loadEmbeddedVideo(id, embeddedCode) {
            document.getElementById(id).innerHTML = fixEmbeddedVideo(embeddedCode);
        }

        /**
         * Fixes a problem with youtube embedded videos not showing dynamically (by setting innerHTML) on Internet Explorer 6
         */
        function fixEmbeddedVideo(embedCode) {
            if (objIsValid(embedCode)) {
                if (embedCode.toLowerCase().indexOf('classid') < 0) {
                    var objPos = embedCode.toLowerCase().indexOf('<object ');
                    if (objPos >= 0) {
                        objPos += '<object '.length;
                        embedCode = embedCode.substr(0, objPos) +
                                    'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' +
                                    embedCode.substr(objPos);
                    }
                }
                if (embedCode.toLowerCase().indexOf('wmode') < 0) {
                    var firstParamPos = embedCode.toLowerCase().indexOf('<param');
                    if (firstParamPos >= 0) {
                        embedCode = embedCode.substr(0, firstParamPos) +
                                    '<param name="wmode" value="transparent"/>' +
                                    embedCode.substr(firstParamPos);
                    }
                    var embedPos = embedCode.toLowerCase().indexOf('<embed ');
                    if (embedPos >= 0) {
                        embedPos += '<embed '.length;
                        embedCode = embedCode.substr(0, embedPos) +
                                    'wmode="transparent" ' +
                                    embedCode.substr(embedPos);
                    }
                }
            }
            return embedCode;
        }

		/**
		 * Builds the big scrolling area (the 2 buttons on the left/right sides) which scroll through the images
		 */
		function initGalleryScrolling() {
			Event.observe($('bigScrollLeft'), 'click', function(/*e*/) {moveDelta(-1);});
			Event.observe($('bigScrollRight'), 'click', function(/*e*/) {moveDelta(1);});
		}

        function moveDelta(delta) {
            if(window.currentPicIdx >= 0 && window.currentPicIdx <= window.currentGallery.length - 1) {
                window.currentPicIdx += delta;
                if(window.currentPicIdx < 0) {
                    window.currentPicIdx = 0;
                }
                if(window.currentPicIdx > window.currentGallery.length - 1) {
                    window.currentPicIdx = window.currentGallery.length - 1;
                }
                if ($('controls')) {
                    $('controls').hide();
                }
                if ($('dropper')) {
                    $('dropper').hide();
                }
                window.currentDropIdx = -1;
                recomputeGallery(true, false);

                centerCurrentlySelectedThumb();
                var thumbId = window.currentGallery[currentPicIdx].userInputId;
                gotoThumbId(thumbId);
            }
        }

		/**
		 * Attaches the "on-drop" behaviour to the dropper
		 */
		function buildDropper() {
            new Draggable("dropper", {
                onEnd : function(){
                    var mainImgCoords = $('mainImg').positionedOffset();
                    var dropperCoords = $('dropper').positionedOffset();
                    window.currentDropLeft = dropperCoords.left - mainImgCoords.left;
                    window.currentDropTop = dropperCoords.top - mainImgCoords.top;
                    // Do not allow the dropper to be dropped outside mainImg
                    repositionDropperInsideImage(dropperCoords, mainImgCoords);
//                  restrictDropper();
                    window.setTimeout("preserveOverlay()", 100);
                }
            });
		}

		function repositionDropperInsideImage(dropperCoords, mainImgCoords) {
            // Do not allow the dropper to be dropped outside mainImg
            if (dropperCoords.left < mainImgCoords.left) {
                $('dropper').style.left = mainImgCoords.left + "px";
                window.currentDropLeft = 0;
            }
            if (dropperCoords.top < mainImgCoords.top) {
                $('dropper').style.top = mainImgCoords.top + "px";
                window.currentDropTop = 0;
            }
            var mainImgDims = $('mainImg').getDimensions();
            var dropperDims = $('dropper').getDimensions();
            var mainImgWidth = mainImgDims.width;
            var mainImgHeight = mainImgDims.height;
            var dropperWidth = dropperDims.width;
            var dropperHeight = dropperDims.height;
            if (dropperCoords.left + dropperWidth > mainImgCoords.left + mainImgWidth) {
                $('dropper').style.left = (mainImgCoords.left + mainImgWidth - dropperWidth) + "px";
                window.currentDropLeft = mainImgWidth - dropperWidth;
            }
            if (dropperCoords.top + dropperHeight > mainImgCoords.top + mainImgHeight) {
                $('dropper').style.top = (mainImgCoords.top + mainImgHeight - dropperHeight) + "px";
                window.currentDropTop = mainImgHeight - dropperHeight;
            }
        }

		function restrictDropper() {
			// Do not allow the dropper to be dropped outside mainImg
//            var mainImg = $('mainImg');
//            var mainImgDimensions = mainImg.getDimensions();
//            var mainImgWidth = mainImgDimensions.width;
//			var mainImgHeight = mainImgDimensions.height;
//            var mainImgCoords = mainImg.positionedOffset();
//            var top = mainImgCoords.top;
//            var right = mainImgCoords.left + mainImgWidth;
//            var bottom = mainImgCoords.top + mainImgHeight;
//            var left = mainImgCoords.left;
//            $('dropper').style.clip = 'rect(' + top + ',' + right + ',' + bottom + ',' + left + ')';
//			$('mainImgContainer').makeClipping().setStyle({width: mainImgWidth + 'px', height: mainImgHeight + 'px'})
		}

		/**
		 * Recalculates the dropper position. Called when a) changing images from galleries (their width/height can change - so
		 * to prevent the dropper getting out of the image area, its coordinates are recomputed); b) zooming, rotating the dropper
		 */
		function recomputeDropper() {
			var dropper = $('dropper');
			//if ((window.currentDropIdx == -1 && window.currentDropImage == null) || !objIsValid(window.currentGallery) || window.currentGallery.length == 0) {
			if (window.currentDropIdx == -1 || !objIsValid(window.currentGallery) || window.currentGallery.length == 0) {
				dropper.hide();
			} else {
				// recompute coordinates for dropper
//                if (window.currentDropImage != null) {
//					dropper.src = window.currentDropImage;
//                } else {
					dropper.src = window.drops[window.currentDropIdx].images[window.currentDropAngle];
//                }
				var mainImgCoords = $('mainImg').positionedOffset();

				var w = MAX_WIDTH - window.currentDropZoom * ZOOM_STEP;
				var h = MAX_HEIGHT - window.currentDropZoom * MAX_HEIGHT * ZOOM_STEP / MAX_WIDTH;
				if (window.currentDropLeft == -1) {
                    window.currentDropLeft = Math.floor(window.currentGallery[window.currentPicIdx].w - w);// - 120;
				}
				if (window.currentDropLeft < 0) {
                    window.currentDropLeft = 0;
				}
				if (window.currentDropTop == -1) {
					window.currentDropTop = Math.floor(window.currentGallery[window.currentPicIdx].h - h);// - 20;
				}
				if (window.currentDropTop < 0) {
					window.currentDropTop = 0;
				}

				dropper.style.left = (mainImgCoords.left + window.currentDropLeft) + "px";
				dropper.style.top = (mainImgCoords.top + window.currentDropTop) + "px";

                var mainImgDims = $('mainImg').getDimensions();
                var dropperDims = $('dropper').getDimensions();
                var maxIterations = 0;
                while(mainImgDims.width < dropperDims.width || mainImgDims.height < dropperDims.height) {
                    if(window.currentDropZoom < MAX_ZOOM - 1) {
						window.currentDropZoom ++;
					}

                    w = MAX_WIDTH - window.currentDropZoom * ZOOM_STEP;
                    h = MAX_HEIGHT - window.currentDropZoom * MAX_HEIGHT * ZOOM_STEP / MAX_WIDTH;
                    if(window.currentDropLeft == -1) {
                        window.currentDropLeft = Math.floor(window.currentGallery[window.currentPicIdx].w - w);// - 120;
                    }
                    if (window.currentDropLeft < 0) {
                        window.currentDropLeft = 0;
                    }
                    if(window.currentDropTop == -1) {
                        window.currentDropTop = Math.floor(window.currentGallery[window.currentPicIdx].h - h);// - 20;
				    }
                    if (window.currentDropTop < 0) {
                        window.currentDropTop = 0;
                    }
                    dropper.style.left = (mainImgCoords.left + 1) + "px";
                    dropper.style.top = (mainImgCoords.top + 1) + "px";

                    maxIterations ++;
                    if(maxIterations == 100) {
                        break;
                    }
                    dropper.width = w;
                    dropper.height = h;
                    dropperDims = $('dropper').getDimensions();
                }
                dropper.width = w;
                dropper.height = h;

                window.setTimeout("closePhotoDesc()", 10);
				dropper.show();
				preserveOverlay();
			}
		}

		/**
		 * Call this method to recalculate the whole contest area: current image, the dropper, etc
		 */
		function recomputeGallery(redrawMainImage, showDropper) {
			if (redrawMainImage && window.currentPicIdx < window.currentGallery.length) {
				// change the image
				var imgContainer = $('mainImgContainer');
//				imgContainer.hide();
                if (window.currentGallery[window.currentPicIdx].h > 0 && window.currentGallery[window.currentPicIdx].h < 480) {
                    imgContainer.style.marginTop = ((480 - window.currentGallery[window.currentPicIdx].h) / 2) + "px";
                } else {
                    imgContainer.style.marginTop = "0px";
                }
                imgContainer.style.width = window.currentGallery[window.currentPicIdx].w + "px";
                imgContainer.style.height = window.currentGallery[window.currentPicIdx].h + "px";
                imgContainer.innerHTML = '<img id="dropper" src="images/pixel.gif" alt="" style="display:none;"/>'
                        + showMediaObject(window.currentPicIdx, VARIANT_640X480);
//				imgContainer.appear({duration: 0.2});
//                window.setTimeout(function(){imgContainer.style.display = 'table-cell';}, 200);
                buildDropper();

                // show numVotes if any
                if($('nrVotes')) {
                    var nrv = window.currentGallery[window.currentPicIdx].v;
                    $('nrVotes').innerHTML = nrv;  
                    $('nrVotesStr').innerHTML = nrv == 1 ? "vot" : "voturi";
                }
                window.currentObjId = window.currentGallery[window.currentPicIdx].userInputId;

                // hide the voting div
                if(window.currentGallery[window.currentPicIdx].f != '1') {
                    if($('rating')) {$('rating').hide();}
                } else {
                    if($('rating')) {$('rating').show();}
                }

                // show photo description
                $('title').innerHTML = window.currentGallery[window.currentPicIdx].title;
                $('description').innerHTML = window.currentGallery[window.currentPicIdx].description;
                $('authorDetails').innerHTML = window.currentGallery[window.currentPicIdx].authorDetails;
                showPhotoDesc();

/*
                // select the image from the thumbs
                for(var i = 1; i <= NUM_THUMBS; i++) {
                    if($('thumb' + i).imgIdx == window.currentPicIdx) {
                        $('thumb' + i).addClassName("selected");
                    } else {
                        $('thumb' + i).removeClassName("selected");
                    }
                }
*/
            }

			if (showDropper) {
				window.setTimeout("recomputeDropper()", 100);
			} else {
                if ($('controls')) {
                    $('controls').hide();
                }
                if ($('dropper')) {
                    $('dropper').hide();
                }
            }
		}

		/**
		 * Builds the control panel with the rotate left-right/zoom in-out controls
		 */
		function buildControlsPanel() {
			$('controls').hide();

			// hides the control panel
//			Event.observe($('controlsClose'), 'click', onClickControlsClose);

			// rotate the car when pressing left or right
//			Event.observe($('controlsLeft'), 'click', onClickControlsLeft);
//			Event.observe($('controlsRight'), 'click', onClickControlsRight);

			// zooms in/out the car image
//			Event.observe($('controlsZoomOut'), 'click', onClickControlsZoomOut);
//			Event.observe($('controlsZoomIn'), 'click', onClickControlsZoomIn);

			// the controls are now merged into one
			Event.observe($('controls'), 'click', onClickControls);
		}

        function onClickControlsClose(/*event*/) {
				$('controls').hide();
				window.currentDropIdx = -1;
				recomputeGallery(false, true);
        }
        function onClickControlsLeft(/*event*/) {
				if (window.currentDropIdx != -1) {
					if(window.currentDropAngle < window.drops[window.currentDropIdx].images.length - 1) {
						window.currentDropAngle ++;
					}
					recomputeGallery(false, true);
				}
        }
        function onClickControlsRight(/*event*/) {
				if (window.currentDropIdx != -1) {
					if(window.currentDropAngle > 0) {
						window.currentDropAngle --;
					}
					recomputeGallery(false, true);
				}
        }
        function onClickControlsZoomOut(/*event*/) {
				if (window.currentDropIdx != -1) {
					if(window.currentDropZoom < MAX_ZOOM - 1) {
						window.currentDropZoom ++;
					}
					recomputeGallery(false, true);
				}
        }
        function onClickControlsZoomIn(/*event*/) {
				if (window.currentDropIdx != -1) {
					if(window.currentDropZoom > 0) {
						window.currentDropZoom --;
					}
					recomputeGallery(false, true);
				}
        }
        function onClickControls(event) {
			var mainCoords = $('main').viewportOffset();
            var x = event.clientX - (mainCoords.left + 530);
            var y = event.clientY +  - (mainCoords.top + 420);
            if (x >= 4 && x <= 24 && y >= 14 && y <= 42) {
                onClickControlsLeft(event);
            } else
            if (x >= 28 && x <= 48 && y >= 14 && y <= 42) {
                onClickControlsZoomOut(event);
            } else
            if (x >= 51 && x <= 71 && y >= 14 && y <= 42) {
                onClickControlsZoomIn(event);
            } else
            if (x >= 74 && x <= 94 && y >= 14 && y <= 42
                    && !(x >= 82 && x <= 97 && y >= 2 && y <= 17)) {
                onClickControlsRight(event);
            } else
            if (x >= 82 && x <= 97 && y >= 2 && y <= 17) {
                onClickControlsClose(event);
            }
        }

        /**
		 * Redraws the thumbnail browser
		 */
		function recomputeThumbnails() {
			for(var i = 1; i <= NUM_THUMBS; i++) {
				$('thumb' + i).hide();
                if (window.currentScrollIdx + i - 1 < window.currentGallery.length) {
                    $('thumb' + i).imgIdx = window.currentScrollIdx + i - 1;
                    $('thumb' + i).innerHTML = showMediaObject(window.currentScrollIdx + i - 1, VARIANT_100X66);
                    $('thumb' + i).appear({duration: 0.1});
                }

                // select the image from the thumbs list
                if($('thumb' + i).imgIdx == window.currentPicIdx) {
                    $('thumb' + i).addClassName("selected");
                } else {
                    $('thumb' + i).removeClassName("selected");
                }
			}
            $('currentThumbNumber').innerHTML = 1 + window.currentPicIdx;
            $('totalVisibleThumbs').innerHTML = window.currentGallery.length;
            $('firstThumbNumber').innerHTML = 1 + window.currentScrollIdx;
            $('lastThumbNumber').innerHTML = NUM_THUMBS + window.currentScrollIdx;
		}

		/**
		 * Initializes events for thumbnails area
		 */
		function initBottomScrolling() {
			// init scrolling
			Event.observe($('scrollLeft'), 'click', function(/*event*/) {
				moveDelta(-1);
			});

			Event.observe($('scrollRight'), 'click', function(/*event*/) {
				moveDelta(1);
			});

			for(var i = 1; i <= NUM_THUMBS; i++) {
				$('thumb' + i).imgIdx = i - 1;
				Event.observe($('thumb' + i), 'click', onClickThumbnail);
			}

            // catch enter on "search" input
            catchSearchEnter();
            // catch enter on "goto" input
            Event.observe($('gotoInput'), 'keypress', function(e) {
                if(e.keyCode == Event.KEY_RETURN) {
                    gotoThumb();
                }
            });
		}

        function onClickThumbnail(/*event*/) {
            if(typeof('findGalleryForThumbId') != 'undefined' && findGalleryForThumbId) {
                    window.currentGallery = window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE];
            }
            hideUserCoverageDescription();
            var userInputId = -1;
            if (window.currentGallery && window.currentGallery.length > this.imgIdx) {
                var item = window.currentGallery[this.imgIdx];
                if (objIsValid(item) && objIsValid(item.userInputId)) {
                    userInputId = item.userInputId;
                }
            }
            if (userInputId > 0) {
                // New navigation code
                gotoThumbId(userInputId);
            } else {
                // Old navigation code
                if ($('controls')) {
                    $('controls').hide();
                }
                if ($('dropper')) {
                    $('dropper').hide();
                }
                window.currentDropIdx = -1;
                window.currentDropImage = null;
                window.currentPicIdx = this.imgIdx;
                recomputeGallery(true, false);
            }
        }

        function preserveOverlay() {
            if (window.currentGallery.length == 0) {
//                alert("Galeria nu contine nicio imagine!");
                return;
            }
            if (window.currentDropIdx < 0) {
//                alert("Nu ati selectat nici o masina Volvo!");
                return;
            }
            //var mainImgCoords = $('mainImg').positionedOffset();
			//var dropperCoords = $('dropper').positionedOffset();
			var w = Math.floor(MAX_WIDTH - window.currentDropZoom * ZOOM_STEP);
			var h = Math.floor(MAX_HEIGHT - window.currentDropZoom * MAX_HEIGHT * ZOOM_STEP / MAX_WIDTH);
			var obj = {
                userInputId: window.currentGallery[window.currentPicIdx].userInputId,
                mediaId: window.currentGallery[window.currentPicIdx].id,
				overlayImageUrl: $('dropper').src,
				left: window.currentDropLeft, /*(dropperCoords.left - mainImgCoords.left),*/
				top: window.currentDropTop, /*(dropperCoords.top - mainImgCoords.top),*/
				width: w,
				height: h,
                zoom: window.currentDropZoom
            };
            userProxy.saveUserInputOverlayOnSession(obj, function(/*response*/) {});
        }

        function restoreOverlay() {
            userProxy.getUserInputOverlayFromSession(function(response) {
                if (response != null) {
                    window.currentDropImage = response.overlayImageUrl;
                    window.currentDropLeft = response.left;
                    window.currentDropTop = response.top;
                    window.currentDropZoom = response.zoom;
                    window.currentDropIdx = -1;
                    window.currentDropAngle = 0;
                    findDropImage();
                    if($('volvoRangeBanner')) {
                        showAllVolvo();
                    }
                    recomputeDropper();
                } else {
                    $('dropper').hide();
                }
            });
        }

        function findDropImage() {
            for (var i = 0; i < window.drops.length; i++) {
                for (var j = 0; j < window.drops[i].images.length; j++) {
                    if (window.drops[i].images[j] == window.currentDropImage) {
                        window.currentDropIdx = i;
                        window.currentDropAngle = j;
                        return;
                    }
                }
            }
        }

        /**
		 * Saves the overlay
		 */
		function saveOverlay(contestId) {
            if (window.currentGallery.length == 0) {
                alert("Galeria nu conţine nicio imagine!");
                return;
            }
            if (window.currentDropIdx < 0) {
                alert("Nu aţi selectat nicio maşină Volvo!");
                return;
            }
            //var mainImgCoords = $('mainImg').positionedOffset();
			//var dropperCoords = $('dropper').positionedOffset();
			var w = Math.floor(MAX_WIDTH - window.currentDropZoom * ZOOM_STEP);
			var h = Math.floor(MAX_HEIGHT - window.currentDropZoom * MAX_HEIGHT * ZOOM_STEP / MAX_WIDTH);
			var obj = {
                contestId: contestId,
                userInputId: window.currentGallery[window.currentPicIdx].userInputId,
                mediaId: window.currentGallery[window.currentPicIdx].id,
				overlayImageUrl: $('dropper').src,
				left: window.currentDropLeft, /*(dropperCoords.left - mainImgCoords.left),*/
				top: window.currentDropTop, /*(dropperCoords.top - mainImgCoords.top),*/
				width: w,
				height: h,
                zoom: window.currentDropZoom
			};

            if(!Prototype.Browser.IE6) {
                $('saveButton').hide();
                var savingMessage = $('savingMessage');
                savingMessage.hide();
                savingMessage.innerHTML = 'Vă rugăm să aşteptaţi,<br/>poza se salvează...';
                savingMessage.style.fontSize = '9px';
                savingMessage.show();
            } else {
                $('saveButton').disabled = true;
                $('saveButton').style.fontSize = "10px";
                $('saveButton').value = 'Poza se salvează...';
            }
            
            userProxy.saveUserInputOverlay(obj, function(response) {
                if(!Prototype.Browser.IE6) {
                    $('savingMessage').hide();
                    $('saveButton').show();
                } else {
                    $('saveButton').disabled = false;
                    $('saveButton').value = 'Salvează'; 
                    $('saveButton').style.fontSize = "12px";
                }
                if (response.status != 0) {
                    if (response.status == 2) {
                        //alert("Pentru a putea salva imaginea, intră în contul tău şi apoi apasă din nou pe butonul 'Salvează'");
                        $('loginTitle').innerHTML = "Pentru a putea salva imaginea, intra in contul tau si apoi apasa din nou pe butonul 'Salveaza'";
                        showLoginForm();
                    } else {
                        alert(response.obj);
                    }
                } else {
//                    var volvoId = parseInt(response.obj);
//                    if (isFinite(volvoId)) {
//                        $('gotoSavedImage').href = '#volvo_' + volvoId;
//                    } else {
//                        $('gotoSavedImage').href = '#volvo';
//                    }
                    showBgLayer();
                    centerPanel('imageSavedPopup');
                    $('imageSavedPopup').appear(0.5);
                }
            });
		}

        function handleWebResponseError(response) {
            var statusCodes = {
                "0" : "OK",
                "-1" : "Eroare",
                "1" : "Invalid",
                "2" : "Eroare de autentificare",
                "3" : "Nepermis"
            };
            alert(statusCodes[response.status] + ": " + response.obj);
        }

		function showBigScrollArrows() {
			$('bigScrollLeft').show();
			$('bigScrollRight').show();
		}
		function hideBigScrollArrows() {
			$('bigScrollLeft').hide();
			$('bigScrollRight').hide();
		}

		function gotoThumb() {
            var thumbNumber = $F('gotoInput');
            if (objIsValid(thumbNumber) && thumbNumber > 0 && thumbNumber <= window.currentGallery.length) {
                var thumbId = window.currentGallery[thumbNumber - 1].userInputId;
                gotoThumbId(thumbId);
            /*} else {
                $('gotoInput').value = '';
            }        */
            }
        }
        function gotoThumbId(userInputId) {
            if(typeof('findGalleryForThumbId') != 'undefined' && findGalleryForThumbId) {
                var gallery = findGalleryForThumbId(userInputId);
                if(gallery != null) {
                    window.currentGallery = gallery;
                }
            }
            hideUserCoverageDescription();
            var hash = window.location.hash;
            if (!hash.startsWith('#')) {
                hash = '#' + hash;
            }
            if (hash.startsWith('#fotoreportaj')) {
                if (hash.startsWith('#fotoreportaj_')) {
                    var photoCoverageId = -1;
                    var itemIdStr = hash.substring('#fotoreportaj_'.length);
                    var pos = itemIdStr.indexOf('_');
                    if (pos < 0) {
                        // The url contains only a photocoverage id
                        photoCoverageId = parseInt(itemIdStr);
                    } else {
                        // The url contains both a photocoverage id and a photo id
                        photoCoverageId = parseInt(itemIdStr.substring(0, pos));
                    }
                    if (isFinite(photoCoverageId)) {
                        jumpToGallery("#fotoreportaj_" + photoCoverageId + "_" + userInputId);
                    }
                }
            } else if (hash.startsWith('#foto')) {
                jumpToGallery("#foto_" + userInputId);
            } else if (hash.startsWith('#video')) {
                jumpToGallery("#video_" + userInputId);
            } else if (hash.startsWith('#volvo')) {
                jumpToGallery("#volvo_" + userInputId);
            } else {
                jumpToGallery("#foto_" + userInputId);
            }
        }

        function showCurrentGallery(interactive, itemId) {
            if (objIsValid(window.currentGallery)) {
                if(window.currentGallery.length == 0) {
                    $('galleryBottom').hide();
                    $('galleryBottomNavigation').hide();
                } else {
                    $('galleryBottom').show();
                    $('galleryBottomNavigation').show();
                }
                window.currentPicIdx = 0;
                if (itemId > 0) {
                    var notFound = true;
                    for (var i = 0; i < window.currentGallery.length; i++) {
                        var item = window.currentGallery[i];
                        if (objIsValid(item) && item.userInputId == itemId) {
                            notFound = false;
                            window.currentPicIdx = i;
                            // If the thumbnail is not already visible, then "scroll" to it
                            if (window.currentPicIdx < window.currentScrollIdx || window.currentPicIdx > window.currentScrollIdx + NUM_THUMBS - 1) {
                                window.currentScrollIdx = i;
                            }
                            if (window.currentScrollIdx > window.currentGallery.length - NUM_THUMBS && window.currentGallery.length >= NUM_THUMBS) {
                                window.currentScrollIdx = window.currentGallery.length - NUM_THUMBS;
                                window.currentScrollIdx = window.currentScrollIdx < 0 ? 0 : window.currentScrollIdx;
                            }
                            break;
                        }
                    }
                    if (notFound) {
                        window.currentScrollIdx = 0;
                    }
                } else {
                    window.currentScrollIdx = 0;
                }
                recomputeGallery(true, false);
                if(typeof('findGalleryForThumbId') != 'undefined' && findGalleryForThumbId) {
                    if(window.currentGallery == window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE]) {
                        recomputeThumbnails();
                    }
                } else {
                    recomputeThumbnails();
                }
                if (interactive) {
                    if($('volvoRangeBanner')) {
                        showVolvoRangeBanner();
                    }
				    //window.setTimeout("restoreOverlay()", 500);
                } else {
                    if($('volvoRangeBanner')) {
                        hideAllVolvo();
                    }
                }
            }
        }

		function showVolvoRangeBanner() {
            if($('dropSource')) {
                $('dropSource').hide();
            }
            if($('volvoRangeBanner')) {
                $('volvoRangeBanner').show();
            }
            if($('rightPanel')) {
                $('rightPanel').show();
            }
		}
		function showVolvoRange() {
            if(!dontShowVolvoRangeUntilMouseOut) {
                if($('volvoRangeBanner')) {
                    $('volvoRangeBanner').hide();
                }
                if($('dropSource')) {
                    $('dropSource').show();
                }
                if($('rightPanel')) {
                    $('rightPanel').show();
                }
            }
        }
		function hideVolvoRange() {
            dontShowVolvoRangeUntilMouseOut = true;
            if($('dropSource')) {
                $('dropSource').hide();
            }
            $('controls').hide();
            $('dropper').hide();
            if($('volvoRangeBanner')) {
                $('volvoRangeBanner').show();
            }
		}
		function showAllVolvo() {
            if($('volvoRangeBanner')) {
                $('volvoRangeBanner').hide();
            }
            if($('dropSource')) {
                $('dropSource').show();
            }
            if($('rightPanel')) {
                $('rightPanel').show();
            }
            positionControls();
		}
		function hideAllVolvo() {
            $('dropper').hide();
            $('controls').hide();
            if($('rightPanel')) {
                $('rightPanel').hide();
            }
            if($('dropSource')) {
                $('dropSource').hide();
            }
            if($('volvoRangeBanner')) {
                $('volvoRangeBanner').hide();
            }
		}

        var selectedMenu = null;
        var selectedSubmenu = null;

        function jumpToGallery(hash) {
            window.location.hash = hash;
            var obj = analyzeURL();
            showCurrentGallery(obj.interactive, obj.itemId);
            refreshMonitoringIframe(hash);
        }

        function jumpToGalleryWithReset(hash, doToggleDescription) {
            window.location.hash = hash;
            restoreGalleryFromUrl(doToggleDescription);
            refreshMonitoringIframe(hash);
        }

        function restoreGalleryFromUrl(doToggleDescription) {
            // Unselect the old selected menu, if any
            if (selectedMenu != null) {
                selectedMenu.removeClassName('selectedMenu');
                selectedMenu.removeClassName('selectedMenu2');
                selectedMenu = null;
            }
            // Unselect the old selected submenu, if any
            if (selectedSubmenu != null) {
                selectedSubmenu.removeClassName('selectedNavigationLink2');
                selectedSubmenu = null;
            }
            // Analyze the URL
            var obj = analyzeURL();
            if (obj.type == MEDIA_OBJECT_TYPE_PHOTO_COVERAGE) {
                // Show the photocoverages submenu
                Element.show('galTree4Children');
                selectedMenu = $('galTree4');
                selectedMenu.addClassName('selectedMenu');
                var photoCoverageIdx = findPhotoCoverageIdx(obj.photoCoverageId);
                var photoCoverage = null;
                if (photoCoverageIdx >= 0 && photoCoverageIdx < window.photoCoverages.length) {
                    photoCoverage = window.photoCoverages[photoCoverageIdx];
                    // Select the photocoverage in the submenu
                    selectedSubmenu = $('treeCoverage_' + obj.photoCoverageId);
                    selectedSubmenu.addClassName('selectedNavigationLink2');
                    // Scroll to the photocoverage in the submenu
                    //$('galTree4Children').top = "-" + (32*photoCoverageIdx) + "px";
                    moveGToElement('navigationPanel', 'treeCoverage_' + obj.photoCoverageId);
                }
                var coverageChanged = true;
                if (objIsValid(photoCoverage)) {
                    if(photoCoverage.id == window.currentCoverageId) {
                        coverageChanged = false;
                    }
                    if(coverageChanged) {
                        window.currentGallery = photoCoverage.photos;
                        showCurrentGallery(obj.interactive, obj.itemId);
                        window.currentCoverageId = photoCoverage.id;
                    }
                }
                if (photoCoverageIdx >= 0 && photoCoverageIdx < window.photoCoverages.length) {
                    photoCoverage = window.photoCoverages[photoCoverageIdx];

                    if(photoCoverage.description != null && photoCoverage.description != '') {
                        if(doToggleDescription && !coverageChanged) {
                            if($('userCoverageDescriptionAllPanel').visible()) {
                                hideUserCoverageDescription();
                            } else {
                                showUserCoverageDescription(photoCoverageIdx);
                            }                                
                        } else {
                            showUserCoverageDescription(photoCoverageIdx);
                        }
                    } else {
                        hideUserCoverageDescription();
                    }
                }
                

            } else if (objIsValid(window.galleryItemsByType) && objIsValid(window.galleryItemsByType[obj.type])) {
                switch (obj.type) {
                    case MEDIA_OBJECT_TYPE_IMAGE:
                        selectedMenu = $('galTree1'); break;
                    case MEDIA_OBJECT_TYPE_IMAGE_WITH_OVERLAY:
                        selectedMenu = $('galTree2'); break;
                    case MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO:
                        selectedSubmenu = $('mo_' + obj.itemId);
                        selectedSubmenu.addClassName('selectedNavigationLink2');
                        // Scroll to the photocoverage in the submenu
                        //$('galTree4Children').top = "-" + (32*photoCoverageIdx) + "px";
                        moveGToElement('navigationPanel', 'mo_' + obj.itemId);

                        selectedMenu = $('galTree3'); break;
                }
                if (selectedMenu != null) {
                    selectedMenu.addClassName('selectedMenu');
                }
                window.currentGallery = window.galleryItemsByType[obj.type];
                window.currentCoverageId = -5;
                showCurrentGallery(obj.interactive, obj.itemId);
            }
        }

        function analyzeURL() {
            var view = window.location.hash;
            var type = MEDIA_OBJECT_TYPE_IMAGE;
            var interactive = true;
            var itemId = -1;
            var photoCoverageId = -1;
            if (view.length > 0) {
                 if (view.startsWith('#')) {
                     view = view.substring(1);
                 }
                 if (view.startsWith('fotoreportaj')) {
                     type = MEDIA_OBJECT_TYPE_PHOTO_COVERAGE;
                     interactive = true;
                     if (view.startsWith('fotoreportaj_')) {
                         var itemIdStr = view.substring('fotoreportaj_'.length);
                         var pos = itemIdStr.indexOf('_');
                         if (pos < 0) {
                            // The url contains only a photocoverage id
                             photoCoverageId = parseInt(itemIdStr);
                         } else {
                             // The url contains both a photocoverage id and a photo id
                             photoCoverageId = parseInt(itemIdStr.substring(0, pos));
                             itemId = parseInt(itemIdStr.substring(pos + 1));
                         }
                     }
                 } else
                 if (view.startsWith('foto')) {
                     type = MEDIA_OBJECT_TYPE_IMAGE;
                     interactive = true;
                     if (view.startsWith('foto_')) {
                         itemId = parseInt(view.substring('foto_'.length));
                     }
                 } else
                 if (view.startsWith('video')) {
                     type = MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO;
                     interactive = false;
                     if (view.startsWith('video_')) {
                         itemId = parseInt(view.substring('video_'.length));
                     }
                 } else
                 if (view.startsWith('volvo')) {
                     type = MEDIA_OBJECT_TYPE_IMAGE_WITH_OVERLAY;
                     interactive = false;
                     if (view.startsWith('volvo_')) {
                         itemId = parseInt(view.substring('volvo_'.length));
                     }
                 }
            }
            if (!isFinite(itemId)) {
                itemId = -1;
            }
            if (!isFinite(photoCoverageId)) {
                photoCoverageId = -1;
            }
            return {interactive:interactive, itemId:itemId, type:type, photoCoverageId:photoCoverageId};
        }

		function addNewImage() {
            window.currentDropIdx = -1;
            window.currentDropImage = null;
            $('dropper').src = 'images/pixel.gif';
            userProxy.removeUserInputOverlayFromSession(function() {
                jumpToGallery('#foto');
            });
        }

function findPhotoCoverageIdx(photoCoverageId) {
    for (var i = 0; i < window.photoCoverages.length; i++) {
        if (window.photoCoverages[i].id == photoCoverageId) {
            return i;
        }
    }
    return -1;
}

function hideUserCoverageDescription() {
    if($('userCoverageDescriptionAllPanel')) {
        $('userCoverageDescriptionAllPanel').hide();//fade(0.02);
    }
}

function showUserCoverageDescription(photoCoverageIdx) {
    if($('userCoverageDescriptionPanel')) {
        photoCoverage = window.photoCoverages[photoCoverageIdx];
        $('userCoverageDescriptionPanel').innerHTML = photoCoverage.description + "<br/><br/>";

        var centerPanelCoords = $('centerPanel').cumulativeOffset();
        var centerPanelDims = $('centerPanel').getDimensions();
        var userCoverageDescriptionPanelDims = $('userCoverageDescriptionAllPanel').getDimensions();
        $('userCoverageDescriptionAllPanel').style.left = (centerPanelCoords.left/* + 0*/) + "px";
        $('userCoverageDescriptionAllPanel').style.top = (centerPanelCoords.top +
                               (centerPanelDims.height - userCoverageDescriptionPanelDims.height) / 2) +
                               "px";
        $('userCoverageDescriptionAllPanel').show();//.appear({duration:0.5});
    }
}

function positionGalleryLoginPanel() {
//    var galleryLoginMessage = $('galleryLoginMessage');
    var galleryLoginLink = $('galleryLoginLink');
    var galleryLogoutLink = $('galleryLogoutLink');
    //var galleryLoginPanel = $('galleryLoginPanel');
    var galleryContestLink = $('galleryContestLink');
    var leftPanel = $('leftPanel');
//    leftPanel.insert(galleryLoginPanel);
//    leftPanel.insert(galleryLoginMessage);
    leftPanel.insert(galleryLoginLink);
    leftPanel.insert(galleryLogoutLink);
    leftPanel.insert(galleryContestLink);
//    Element.show(galleryLoginPanel);
    if (objIsValid(welcomeUsername) && welcomeUsername.length > 0) {
        Element.show(galleryLogoutLink);
        if($('galleryUploadLink')) {
            $('galleryUploadLink').show();
        }
    } else {
        Element.show(galleryLoginLink);
        if($('galleryUploadLink')) {
            $('galleryUploadLink').hide();
        }
    }
    Element.show(galleryContestLink);
}

function toggleGalleryLoginForm() {
//    Element.hide('galleryLoginLink');
    Element.toggle('loginFormGallery');
    Element.update('galleryLoginMessage');
}
        
function doLoginGallery() {
    Element.update('galleryLoginMessage', '<img src="/images/new/ajax_loading_anim_3.gif" height="16" alt=""/> Se conecteaza...');
    var opt = {
        method: 'post',
        postBody: Form.serialize('loginFormGallery') + '&ajax=true',
        onSuccess: function(response) {
            Element.update('galleryLoginMessage', '');
            var msg = response.responseText;
            if (msg.startsWith("error:")) {
                Element.update('galleryLoginMessage', '<font color="red" align="center">Login invalid</font>');
            } else if (msg.startsWith("url:")) {
                location.href = msg.substring("url:".length);
                hideLoginForm();
            } else if (msg.startsWith("success:")) {
                var nickname = msg.substring("success:".length);
                welcomeUsername = nickname;
                Element.hide('loginPopup');
                Element.hide('galleryLoginLink');
                Element.update('userNickname', nickname.escapeHTML());
                Element.show('galleryLogoutLink');
                if($('galleryUploadLink')) {
                    $('galleryUploadLink').show();                
                }
                hideLoginForm();
            }
        }
    };
    new Ajax.Request('/web_login_check', opt);
}

function doLogoutGallery() {
    var logoutUrl = '/logout?a='+(new Date()).getTime();
    var opt = {
        method: 'post',
        postBody: '',
        onSuccess: function(/*response*/) {
            Element.hide('galleryLogoutLink');
            Element.update('userNickname', '');
            Element.show('galleryLoginLink');
        }
    };
    new Ajax.Request(logoutUrl, opt);
    if($('galleryUploadLink')) {
        $('galleryUploadLink').hide();
    }
};

var closePhotoDesc = function closePhotoDesc() {
    $('photoDescContainer').fade({duration:0.4});
    $('ym').fade({duration:0.4});
};

var showPhotoDesc = function() {
    if(window.currentGallery && window.currentGallery.length > 0) {
        initPhotoDetails();
        $('photoDescContainer').appear({duration:0.4});
        $('ym').appear({duration:0.4});
    }
};

var sendByYm = function(url) {
    window.location.href = "ymsgr:im?+&msg=" + url;
};

var initPhotoDetails = function() {
    var photoDescDim = $('photoDescText').getDimensions();
    var centerPanelCoords = $('centerPanel').cumulativeOffset();
    var centerPanelDims = $('centerPanel').getDimensions();
    var closeHeight = 19;
    var arrowHeight = 83;
    var arrowMargin = 3;
    
    var photoDescHeight = (photoDescDim.height + closeHeight) < (arrowHeight + arrowMargin * 2 + closeHeight) ?
                          (arrowHeight + arrowMargin * 2 + closeHeight) : (photoDescDim.height + closeHeight);
    
    $('photoDescContainer').style.left = centerPanelCoords.left + "px";
    $('photoDescContainer').style.top = (centerPanelCoords.top + centerPanelDims.height - photoDescHeight +
                                        (Prototype.Browser.IE6 ? -2 : 0)) + "px";
    $('photoDescContainer').style.height = photoDescHeight + "px";

    var arrowMarginTop = parseInt((photoDescHeight - closeHeight - arrowHeight) / 2);
    $('bigScrollRight').style.marginTop = arrowMarginTop +15+ "px";
    $('bigScrollLeft').style.marginTop = arrowMarginTop +15+ "px";
    $('photoDesc').style.height = (photoDescHeight - closeHeight) + "px";

//    var photoDescTextDims = $('photoDescText').getDimensions();
//    var photoDescTextTop = parseInt((photoDescHeight - closeHeight - photoDescTextDims.height) / 2);
//    $('photoDescText').style.paddingTop = "3px";

    //$('photoDescContainer').show();

    $('ym').style.top = (centerPanelCoords.top + 20) + "px";
    $('ym').style.left = (centerPanelCoords.left + centerPanelDims.width - 40) + "px";
//    $('ym').show();

//        $('photoDescContainer').appear({duration:0.4});
//        $('ym').appear({duration:0.4});
};

var galleryResize = function() {
    initPhotoDetails();
//    $('bgLayer').style.width = document.viewport.getWidth();
    $('bgLayer').style.height = document.viewport.getHeight();
    centerPanel('imageSavedPopup');
    centerPanel('loginPopup');
    //restrictDropper();
};

var centerCurrentlySelectedThumb = function() {
    window.currentScrollIdx = window.currentPicIdx - 2;
    if(window.currentScrollIdx < 0) {
        window.currentScrollIdx = 0;
    }
};

var showFinale = function(items, menuEntry) {
    // Unselect the old selected menu, if any
    if (selectedMenu != null) {
        selectedMenu.removeClassName('selectedMenu');
        selectedMenu.removeClassName('selectedMenu2');
        selectedMenu = null;
    }
    // Unselect the old selected submenu, if any
    if (selectedSubmenu != null) {
        selectedSubmenu.removeClassName('selectedNavigationLink2');
        selectedSubmenu = null;
    }

    selectedMenu = $(menuEntry);
    if (selectedMenu != null) {
        selectedMenu.addClassName('selectedMenu2');
    }

    // search the current gallery
    currentGallery = [];
    try {
        for(var i = 0; i < items.length; i++) {
            var obj = items[i];
            if(obj.f == '1') {
                currentGallery[currentGallery.length] = obj;
            }
        }
    } catch(e) {}

    if (currentGallery.length > 0) {
        gotoThumbId(currentGallery[0].userInputId);
    } else {
        window.currentPicIdx = 0;
        window.currentScrollIdx = 0;
        recomputeThumbnails();
        recomputeGallery(true, false);
    }
};

var searchGallery = function() {
    var searchStr = $F('searchInput');
    if(!searchStr || searchStr == "") {
        alert("Introduceţi o valoare în câmpul de căutare");
        return;
    }

    // if in search mode, restore the old gallery
    if(inSearchMode) {
    } else {
        inSearchMode = true;

        // remember the old gallery
        oldGallery = [];
        if(window.currentGallery && window.currentGallery.length > 0) {
            for(var i = 0; i < currentGallery.length; i++) {
                oldGallery[oldGallery.length] = currentGallery[i];
            }
        }
    }

    // search the current gallery
    currentGallery = [];
    try {
        for(var i = 0; i < window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE].length; i++) {
            var obj = window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE][i];
            if((obj.title && obj.title.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.description && obj.description.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.authorDetails && obj.authorDetails.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0)) {
                currentGallery[currentGallery.length] = obj;
            }
        }
        for(var i = 0; i < window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE_WITH_OVERLAY].length; i++) {
            var obj = window.galleryItemsByType[MEDIA_OBJECT_TYPE_IMAGE_WITH_OVERLAY][i];
            if((obj.title && obj.title.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.description && obj.description.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.authorDetails && obj.authorDetails.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0)) {
                currentGallery[currentGallery.length] = obj;
            }
        }
        for(var i = 0; i < window.galleryItemsByType[MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO].length; i++) {
            var obj = window.galleryItemsByType[MEDIA_OBJECT_TYPE_HTML_EMBED_VIDEO][i];
            if((obj.title && obj.title.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.description && obj.description.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                (obj.authorDetails && obj.authorDetails.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0)) {
                currentGallery[currentGallery.length] = obj;
            }
        }
        for(var i = 0; i < window.photoCoverages.length; i++) {
            for(var j = 0; j < window.photoCoverages[i].photos.length; j++) {
                var obj = window.photoCoverages[i].photos[j];
                if((obj.title && obj.title.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                    (obj.description && obj.description.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0) ||
                    (obj.authorDetails && obj.authorDetails.toLowerCase().indexOf(searchStr.toLowerCase()) >= 0)) {
                    currentGallery[currentGallery.length] = obj;
                }
            }
        }
    } catch(e) {}

    if (currentGallery.length > 0) {
        gotoThumbId(currentGallery[0].userInputId);
    } else {
        window.currentPicIdx = 0;
        window.currentScrollIdx = 0;
        recomputeThumbnails();
        recomputeGallery(true, false);
    }

    searchOldHTML = $('search').innerHTML;
    $('search').innerHTML = "<div style='float:left;text-align:left;'><div style='float:left;'>" + currentGallery.length +
                            " poze&nbsp;</div><div style='float:left;'>\"" + searchStr +
                            "\"</div><div >&nbsp;<a href='javascript:resetSearch()'><img src='/images/new/galerie2/go-back.gif'/></a></div>" +
                            "<div><a href='javascript:resetSearch()' style='color:white;'>Înapoi la toate pozele</a></div></div>";

    inSearchMode = false;
};

var resetSearch = function() {
    // restore html
    $('search').innerHTML = searchOldHTML;
    catchSearchEnter();

    // reset gallery
    currentGallery = [];
    for(var i = 0; i < oldGallery.length; i++) {
        currentGallery[currentGallery.length] = oldGallery[i];
    }

    inSearchMode = false;

    if (currentGallery.length > 0) {
        gotoThumbId(currentGallery[0].userInputId);
    } else {
        window.currentPicIdx = 0;
        window.currentScrollIdx = 0;
        recomputeThumbnails();
        recomputeGallery(true, false);
    }
};

var catchSearchEnter = function() {
    // catch enter on search input
    Event.observe($('searchInput'), 'keypress', function(e) {
        if(e.keyCode == Event.KEY_RETURN) {
            searchGallery();
        }
    });
    Event.observe(window, 'keypress', function(e) {
        if(e.keyCode == Event.KEY_ESC) {
            if($('userCoverageDescriptionAllPanel').visible()) {
                hideUserCoverageDescription();
            }
        }
    });
};

var refreshMonitoringIframe = function(hash) {
    if($('monitoring')) {
        var src = $('monitoring').src;
        var diezPos = src.indexOf("#");
        if(diezPos > 0) {
            src = src.substring(0, diezPos);
        }
        var questionMarkPos = src.indexOf("?");
        if(questionMarkPos > 0) {
            src = src.substring(0, questionMarkPos);
        }
        var newSrc = src;
        if(typeof(hash) != "undefined" && hash != "") {
            var underscorePos = hash.indexOf("_");
            if(underscorePos > 0) {
                hash = hash.substring(0, underscorePos);
            }
            if(hash.charAt(0) == "#") {
                hash = "?" + hash.substring(1);
            }
            newSrc += hash;
        }
        $('monitoring').src = newSrc;
    }
};

var hideLoginForm = function() {
    $('bgLayer').hide();
    $('loginPopup').fade(0.02);
};


var loginFormMoved = false;
var showLoginForm = function() {
    if(!loginFormMoved) {
        var removed = $('galleryLoginPanel').remove();
        $('loginPopupContainer').appendChild(removed);
        centerPanel('loginPopup');
        $('galleryLoginPanel').show();
        loginFormMoved = true;
    }

    showBgLayer();
    $('loginPopup').appear(0.05);

    window.setTimeout("$F('j_username2').focus()", 500);
};

var centerPanel = function(id) {
    var w = document.viewport.getWidth();
    var h = document.viewport.getHeight();
    var dims = $(id).getDimensions();
    $(id).style.left = ((w - dims.width) / 2) + "px";
    $(id).style.top = ((h - dims.height) / 2) + "px";
};

var showBgLayer = function() {
    $('bgLayer').style.left = "0px";
    $('bgLayer').style.top = "0px";
    $('bgLayer').style.height = document.viewport.getHeight() + "px";
    $('bgLayer').show();
};

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
    initialize: function(element) {
        this.element = $(element);
        var options = Object.extend({
                x:    0,
                y:    0,
                mode: 'absolute'
            } , arguments[1] || {}  );
        this.start(options);
    },
    setup: function() {
        if (this.options.continuous && !this.element._ext ) {
            this.element.cleanWhitespace();
            this.element._ext=true;
            this.element.appendChild(this.element.firstChild);
        }

        this.originalLeft=this.element.scrollLeft;
        this.originalTop=this.element.scrollTop;

        if(this.options.mode == 'absolute') {
            this.options.x -= this.originalLeft;
            this.options.y -= this.originalTop;
        } else {

        }
    },
    update: function(position) {
        this.element.scrollLeft = this.options.x * position + this.originalLeft;
        this.element.scrollTop  = this.options.y * position + this.originalTop;
    }
});

function moveGTo(container, delta){
    currentScrollY += delta;
    var container_y = Position.cumulativeOffset($(container))[1];
    var maxY = Position.cumulativeOffset($('endMarker'))[1] - 300;
    currentScrollY = currentScrollY > maxY ? maxY : currentScrollY;
    currentScrollY = currentScrollY < container_y ? container_y : currentScrollY;
    new Effect.Scroll(container, {x:0, y:currentScrollY - container_y, duration:0.4});//(element_y-container_y)});
}

function moveGToElement(container, elemId){
    Position.prepare();
    currentScrollY = Position.cumulativeOffset($(elemId))[1];
    var container_y = Position.cumulativeOffset($(container))[1];
    currentScrollY = currentScrollY < container_y ? container_y : currentScrollY;
    new Effect.Scroll(container, {x:0, y:currentScrollY - container_y, duration:0.5});
}

function gvo(votePro) {
    // detect whether it's a coverage or a regular photo
    var isCoverage = false;
    var coverageId = -1;
    for(var i = 0; i < window.photoCoverages.length; i++) {
        for(var j = 0; j < window.photoCoverages[i].photos.length; j++) {
            if(window.currentObjId == window.photoCoverages[i].photos[j].userInputId) {
                isCoverage = true;
                coverageId = window.photoCoverages[i].id;
                break;
            }
        }
        if(isCoverage) {
            break;
        }
    }
    var typeCoverage = 42;
    var typeUserInput = 27;
    votingProxy.voteForObject(isCoverage ? typeCoverage : typeUserInput, isCoverage ? coverageId : window.currentObjId, votePro ? 1 : 0, function(response) {
        if (response.status == 0) {
            var nrVotesSpan = $('nrVotes');
            if (nrVotesSpan) {
                var nrVotes = nrVotesSpan.innerHTML;
                nrVotes = parseInt(nrVotes);
                if(isNaN(nrVotes)) {
                    nrVotes = 0;
                }
                if (votePro) {
                    nrVotes ++;
                } else {
                    nrVotes --;
                }
                nrVotesSpan.innerHTML = nrVotes;
                $('nrVotesStr').innerHTML = nrVotes == 1 ? "vot" : "voturi";
            }
        } else {
            alert(response.obj);
            if (response.status != 5) {
                $('loginTitle').innerHTML = "Pentru a putea vota imaginea sau fotoreportajul, intra in contul tau si apoi voteaza din nou";
                showLoginForm();
            }
        }
    });
}

