var igalleryClass = new Class
({
	Implements: Options,

    options: {},

    initialize: function(options)
    {
        this.setOptions(options);
        this.imageIndex = 0;
		this.currentHash = '';
        this.zIndex = 0;

        if(this.options.main == 1)
        {
        	this.urlImageId = this.getUrlParamater('image');

        	if(this.urlImageId != 'unset')
        	{
        		this.imageIndex = this.urlImageId - 1;


        		this.thumbId = 'main-' + this.options.catid + '-' + this.urlImageId;

        		if( $chk( document.id(this.thumbId) ) )
        		{
        		    this.igThumbScroller = new Fx.Scroll(this.options.thumbContainer,{duration: 50});
        		    this.igThumbScroller.toElement( document.id(this.thumbId) );
        		}
        	}
			
			if(this.options.main == 1)
    		{
	        	if(this.options.refreshMode == 'hash')
	    		{
	        		this.checkHash(false);
	        		this.checkHashPeriodical = this.checkHash.periodical(400, this, true);
	    		}
    		}

        	if(this.options.showLargeImage == 1)
        	{
	           this.swapImage(this.options.jsonImagesImageType[this.imageIndex], 50, this.imageIndex, false);
        	}
        	else
        	{
        		if(this.options.allowComments == 1)
        		{
        			this.swapComments();
        		}
        	}
        }

        if(this.options.showThumbs == 1)
		{
    		this.thumbScroller = new Scroller(this.options.thumbContainer, {area: this.options.scrollBoundary, velocity: this.options.scrollSpeed});
    		document.id(this.options.thumbContainer).addEvent('mouseenter', this.thumbScroller.start.bind(this.thumbScroller));
    		document.id(this.options.thumbContainer).addEvent('mouseleave', this.thumbScroller.stop.bind(this.thumbScroller));

    		this.addThumbBehaviors();
		}

		if(this.options.showUpDown == 1 && this.options.showThumbs)
		{
			this.addArrowBehaviors(this.options.upArrow, -200, 'vertical');
			this.addArrowBehaviors(this.options.downArrow, 200, 'vertical');
		}
		if(this.options.showLeftRight == 1 && this.options.showThumbs)
		{
			this.addArrowBehaviors(this.options.rightArrow, 200, 'horizontal');
			this.addArrowBehaviors(this.options.leftArrow, -200, 'horizontal');
		}

		if(this.options.preload == 1 && this.options.main == 1 && this.options.showLargeImage == 1)
		{
			this.preloadCounter = 0;
			this.preloaderVar = this.preloadImages.periodical(750, this);
		}

        if( (this.options.showSlideshowControls == 1 || this.options.slideshowAutostart == 1)  && this.options.main == 1 && this.options.showLargeImage == 1)
        {
        	this.clearSlideShow();

        	if(this.options.showSlideshowControls == 1)
			{
                document.id(this.options.slideshowForward).addEvent('click', function(e)
				{
					this.clearSlideShow();
					this.slideShowSwap(true);
				}.bind(this));

				document.id(this.options.slideshowRewind).addEvent('click', function(e)
				{
					this.clearSlideShow();
					this.slideShowSwap(false);
				}.bind(this));
			}

        	if(this.options.slideshowAutostart == 1 && this.options.showLargeImage == 1)
        	{
        		this.slideShowStart(false);
        	}
			
			if(this.options.main == 1)
			{
				var pagWrapper = document.id(this.options.mainWrapper).getElement('span[class=pagination]');
				
				if($chk(pagWrapper))
				{
					var pagChildren = pagWrapper.getChildren();
					
					pagChildren.each(function(el,index)
					{
						if(index < 3 || index > (pagChildren.length - 4) )
						{
							el.setStyle('display', 'none');
						}
					});
				}
			}
        }
    },
	
	checkHash: function(refresh)
    {
    	var hashVar = window.location.hash;
    	
    	if(hashVar != this.currentHash)
    	{
	    	var dashPos = hashVar.indexOf('-');
	    	if(dashPos > 0)
	    	{
	    		var catid = hashVar.substr(1, dashPos - 1);
	    		var fileNameClean = hashVar.substr(dashPos + 1);
	    		
	    		if(catid == this.options.catid)
	    		{
		    		this.options.jsonImages.main.each(function(el,index)
		    		{
		    			if( el.filename.indexOf('/' + fileNameClean + '-') > 0 )
		    			{
		    				this.imageIndex = index;
		    			}
		    		}.bind(this));
	    		}
	    	}
	    	
	    	if(refresh == true)
	    	{
	    		this.swapImage(this.options.jsonImagesImageType[this.imageIndex], this.options.fadeDuration, this.imageIndex, true);
	    	}
	    	
	    	this.currentHash = hashVar;
    	}
    },
    
    addHash : function(imageObject)
	{
		var slashPos = imageObject.filename.indexOf('/');
		var fileNameOnly  = imageObject.filename.substr(slashPos + 1);
		
		var dashPos = fileNameOnly.indexOf('-');
		var fileNameClean  = fileNameOnly.substr(0, dashPos);
		var hashToAdd = this.options.catid + '-' + fileNameClean;
		
		window.location.hash = hashToAdd;
		
		this.currentHash = '#' + hashToAdd;
		
	},

    addThumbBehaviors: function(options)
    {
        this.linksArray = document.id(this.options.thumbTable).getElements('a');

		this.linksArray.each(function(el,index)
		{
			el.addEvent('click', function(e)
			{
				e = new Event(e).stop();
				this.clearSlideShow();

				if(this.options.showLargeImage == 0 && this.options.main == 1)
				{
					this.thumbLinksArray = document.id(this.options.thumbContainer).getElements('a');
					this.thumbLinkClass = el.getProperty('class');
					this.thumbLinkTarget = el.getProperty('target');

					if(this.thumbLinkClass == 'picture_link')
					{
						el.setStyle('cursor', 'pointer');

						if (this.thumbLinkTarget == '_blank')
						{
							window.open(this.thumbLinksArray[index]);
						}
						else
						{
							window.location = this.thumbLinksArray[index];
						}
					}
					else
					{
						this.showLightBox(index);
					}
				}
				else
				{
				    this.swapImage(this.options.jsonImagesImageType[index], this.options.fadeDuration, index, true);
				}
			}.bind(this));

		}.bind(this));
	},

    swapImage : function(imageObject, fadeDuration, index, addHash)
	{
	    this.imageIndex = index;
		this.insertImage(imageObject, fadeDuration, this.imageIndex);
		
		if(this.options.showThumbs == 1)
		{
            this.thumbCells = document.id(this.options.thumbTable).getElements('td');
            this.thumbCells.each(function(el,index)
            {
                  el.setProperty('class','inactive_thumb');
            }.bind(this));
            this.thumbCells[index].setProperty('class','active_thumb');
		}

		if(this.options.main == 1 && this.options.showLargeImage == 1 && this.options.showThumbs == 1)
		{
			this.addMainImageClick(this.imageIndex);
		}

		if(this.options.showThumbs == 0 && this.options.lightboxOn == 1)
		{
		    document.id(this.options.largeImage).removeEvents('click');

			document.id(this.options.largeImage).setStyle('cursor', 'pointer');

			document.id(this.options.largeImage).addEvent('click', function(e)
			{
				this.showLightBox(index);
			}.bind(this));
		}

		if(this.options.downloadType != 'none')
		{
		    if(this.options.main == 0 || this.options.showLargeImage == 1)
		    {
			    if(this.options.main == 1)
			    {
			        this.linkType = 'main';
			    }
			    else
			    {
			        this.linkType = 'lbox';
			    }

                var url = this.options.host + 'index.php?option=com_igallery&task=download&type=' + this.linkType + '&id=' + this.options.idArray[index];

			    this.downloadLink = document.id(this.options.downloadId);
                this.downloadLink.setProperty('href',url);

    			}
		}

		if(this.options.allowRating == 1)
		{
			this.swapRating();
		}
		
		if(this.options.allowRating == 2)
		{
			var alcontainer = document.id(this.options.alRatingsContainer);
			var imgUrlVar = index + 1;
			
			alcontainer.getElement('.alratings_okeyid').setProperty('value', this.options.idArray[index]);
			alcontainer.getElement('.alratings_otitle').setProperty('value', imageObject.filename);
			alcontainer.getElement('.alratings_olink').setProperty('value', 'index.php?option=com_igallery&view=showcategory&id=' + this.options.catid + '&image=' + imgUrlVar);
			
			alRatings.refreshRating('com_igallery', this.options.idArray[index]);
		}

		if(this.options.allowComments == 1)
		{
			this.swapComments();
		}
		
		if(this.options.allowComments == 2)
		{
			jcomments.showPage(this.options.idArray[index],'com_igallery',0);
			
			var objectIdInput = document.id('comments-form').getElement('input[name=object_id]');
			objectIdInput.setProperty('value', this.options.idArray[index]);
			
			var jcforms = document.id('jc').getElements('form[id=comments-form]');
			jcforms.each(function(el,index)
			{
				if(index != 0)
				{
					el.dispose();
				}
			});
			
		}
		
		if(this.options.allowComments == 3)
		{
			var joomUrl = this.options.host + 'index.php?option=com_igallery&controller=igcategory&task=joomcomment&format=raw&id=' + this.options.idArray[index];
			var joomAjax = new Request({url:joomUrl, method: 'get', 
			onComplete: function(response)
			{
				document.id(this.options.joomCommentContainer).empty();
				document.id(this.options.joomCommentContainer).set('html',response);
			}.bind(this)
			});
			
			joomAjax.send();
		}

		if(this.options.showDescriptions == 1)
		{
			this.swapDescription(index);
		}
		
		if(this.options.showTags == 1)
		{
			this.swapTags(index);
		}
		
		if(this.options.facebookShare == 1)
		{
			var currentUrl = window.location.href;
			if(currentUrl.indexOf("#") > -1)
			{
				currentUrl = currentUrl.substr(0, currentUrl.indexOf("#"));
			}
			
			var urlSymbool = currentUrl.indexOf("?") > -1 ? '&' : '?'; 
			var urlToShare = currentUrl + urlSymbool + 'image=' + (index + 1);
			var facebookUrl = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(urlToShare);
			
			this.facebookLink =  document.id(this.options.facebookContainer).getElement('a');
			this.facebookLink.setProperty('href', facebookUrl);
		}
		
		if(this.options.reportImage == 1)
		{
			this.reportForm = document.id(this.options.reportContainer).getElement('form');
			this.reportForm.setStyle('display', 'none');
		    this.reportUrl = this.options.host + 'index.php?option=com_igallery&controller=igphoto&task=reportImage&id=' + this.options.idArray[index] + '&catid=' + this.options.catid;
		    this.reportForm.setProperty('action', this.reportUrl);
			
		    this.reportLink = document.id(this.options.reportContainer).getElement('a');
		    this.reportLink.addEvent('click', function(e)
			{
				new Event(e).stop();
				this.reportForm.setStyle('display', 'block');
			}.bind(this));
		}
		
		if(this.options.main == 1)
		{
			if(this.options.refreshMode == 'hash' && addHash == true)
			{
				this.addHash(imageObject);
			}
		}
		
		this.addHit();
	},
	
	removeImage : function(fadeDuration, currentImgId)
	{
		var insertedImages = document.id(this.options.largeImage).getElements('img[class=large_img]');
	    
		for(var i=0; i<insertedImages.length; i++)
	    {
			var opacity = insertedImages[i].getStyle('opacity');
			
			if(opacity != 0)
			{
				if(insertedImages[i].getProperty('id') != currentImgId)
				{
					this.imageFadeAway = new Fx.Tween(insertedImages[i], {property:'opacity',duration:fadeDuration});
		    		this.imageFadeAway.start(opacity,0);
				}
			}
	    }

		if(this.options.main == 1 && this.options.lightboxOn == 1)
		{
			if (this.options.magnify == 1 && document.id('magnifygif') != null)
			{
				document.id('magnifygif').dispose();
			}
		}
	},

	insertImage : function(imageObject, fadeDuration, index)
	{
		if(typeof(this.lastImageDisplayed) != 'undefined')
	    {
			if(this.lastImageDisplayedIndex == index)
			{
				return;
			}
	    }
		
		if(this.options.main != 1)
		{
			if(this.options.lboxScalable == 1)
			{
				if(this.shrinkRatio < 1)
				{
					imageObject.width = Math.round(imageObject.width * this.shrinkRatio);
					imageObject.height = Math.round(imageObject.height * this.shrinkRatio);
				}
			}
		}
		
		if(typeof(this.lastImageDisplayed) != 'undefined')
	    {
			this.imageToRemove = this.lastImageDisplayed;
			var imageToRemoveWidth = parseInt(this.imageToRemove.getStyle('width'));
			var imageToRemoveHeight = parseInt(this.imageToRemove.getStyle('height'));
	    }
		else
		{
			var imageToRemoveWidth = 0;
			var imageToRemoveHeight = 0;
		}
		
	    this.insertedImages = document.id(this.options.largeImage).getElements('img[class=large_img]');
	    this.insertedMatch = false;

		for(var i=0; i<this.insertedImages.length; i++)
	    {
			this.insertedImageId = this.insertedImages[i].getProperty('id');
			this.idSplitted = this.insertedImageId.split('-');
			this.insertedImageCounter = this.idSplitted[2];
			if(this.insertedImageCounter == index)
			{
			    this.insertedMatch = true;
			    break;
			}
		}

	    if(this.insertedMatch == true)
		{
			var imageToInsertWidth = document.id(this.insertedImageId).getStyle('width').toInt();
			var imageToInsertHeight = document.id(this.insertedImageId).getStyle('height').toInt();
			
			var widthDiff = imageToInsertWidth - imageToRemoveWidth;
			var heightDiff = imageToInsertHeight - imageToRemoveHeight;
			
			if( widthDiff < 5 && widthDiff > -5 && heightDiff < 5 && heightDiff > -5)
			{
				this.wait = true;
			}
			else
			{
				this.wait = false;
				this.removeImage(fadeDuration, this.insertedImageId);
			}
			
			document.id(this.insertedImageId).setStyle('z-index',this.zIndex);
			this.zIndex++;
			
			this.imageFadeIn = new Fx.Tween(this.insertedImageId, {property:'opacity',duration:this.options.fadeDuration}).start(0,1).chain(function()
			{
		    	if(this.wait == true)
		    	{
		    		this.removeImage(50, this.insertedImageId);
		    	}
		    	this.lastImageDisplayed = document.id(this.insertedImageId);
		    	this.lastImageDisplayedIndex = index;
		    }.bind(this));
			
		    this.largeImgDivSizeArray = document.id(this.options.largeImage).getSize();
			this.imageToInjectLeftMargin = Math.round( (this.largeImgDivSizeArray.x - imageObject.width) /2 );
			this.imageToInjectTopMargin  = Math.round( (this.largeImgDivSizeArray.y - imageObject.height) /2 );

			if(this.options.style == 'grey-border-shadow')
			{
			    this.imageToInjectLeftMargin = this.imageToInjectLeftMargin - 7;
			    this.imageToInjectTopMargin = this.imageToInjectTopMargin - 7;
			}

			if(this.options.main == true && this.options.magnify == 1 && this.options.lightboxOn == 1)
			{
				this.insertMagnify(this.insertedImageCounter, this.imageToInjectLeftMargin, this.imageToInjectTopMargin);
			}
		}
	    else
	    {
			if( (Math.abs(parseInt(imageObject.width - imageToRemoveWidth)) < 5) && (Math.abs(parseInt(imageObject.height - imageToRemoveHeight)) < 5) )
	    	{
	    		this.wait = true;
	    	}
			else
			{
				this.wait = false;
	    		this.removeImage(fadeDuration, 'ig' + this.options.main + '-' + this.options.catid + '-' + index);
			}
			
    		this.ImageAsset = new Asset.images([this.options.resizePath + imageObject.filename ],
    		{
    			onComplete: function()
    			{
    				this.largeImgDivSizeArray = document.id(this.options.largeImage).getSize();
    				this.imageToInjectLeftMargin = Math.round( (this.largeImgDivSizeArray.x - imageObject.width) /2 );
    				this.imageToInjectTopMargin  = Math.round( (this.largeImgDivSizeArray.y - imageObject.height) /2 );

    				if(this.options.style == 'grey-border-shadow')
    				{
    				    this.imageToInjectLeftMargin = this.imageToInjectLeftMargin - 7;
    				    this.imageToInjectTopMargin = this.imageToInjectTopMargin - 7;
    				}

    				this.ImageAsset.setStyles
    				({
    					position: 'absolute',
    					left: this.imageToInjectLeftMargin,
    					top: this.imageToInjectTopMargin,
    					width: imageObject.width,
    					height: imageObject.height,
    					opacity: 0,
						'z-index': this.zIndex
    				});
					
					this.zIndex++;
    				this.ImageAsset.setProperty('class', 'large_img');
    				this.ImageAsset.setProperty('alt', imageObject.alt);
    				this.imageAssetId = 'ig' + this.options.main + '-' + this.options.catid + '-' + index;
                    this.ImageAsset.setProperty('id', this.imageAssetId);
                    
    				this.ImageAsset.injectTop( document.id(this.options.largeImage) );
    				this.ImageAssetInjected = document.id(this.options.largeImage).getElement('img');
    				this.imageFadeIn = new Fx.Tween(this.ImageAssetInjected, {property:'opacity',duration:fadeDuration}).start(0,1).chain(function()
					{
    			    	if(this.wait == true)
    			    	{
    			    		this.removeImage(5, this.imageAssetId);
    			    	}
    			    	this.lastImageDisplayed = document.id(this.imageAssetId);
    			    	this.lastImageDisplayedIndex = index;
    			    }.bind(this));
    				
                    if(this.options.main == true && this.options.magnify == 1 && this.options.lightboxOn == 1)
    				{
    					this.insertMagnify(index, this.imageToInjectLeftMargin, this.imageToInjectTopMargin);
    				}

    			}.bind(this)
    		});
	    }
	},

	addMainImageClick : function(index)
	{
			this.linksArray = document.id(this.options.thumbContainer).getElements('a');
			this.linkClass = this.linksArray[index].getProperty('class');
			this.linkTarget = this.linksArray[index].getProperty('target');

			if(this.linkClass == 'picture_link')
			{
				document.id(this.options.largeImage).setStyle('cursor', 'pointer');
				document.id(this.options.largeImage).removeEvents('click');

				document.id(this.options.largeImage).addEvent('click', function(e)
				{
					if (this.linkTarget == '_blank')
					{
						window.open(this.linksArray[index]);
					}
					else
					{
						window.location = this.linksArray[index];
					}

				}.bind(this));
			}

			if(this.options.lightboxOn == 1 && this.linkClass == 'no_link' )
			{
				document.id(this.options.largeImage).removeEvents('click');

				document.id(this.options.largeImage).setStyle('cursor', 'pointer');

				document.id(this.options.largeImage).addEvent('click', function(e)
				{
					this.showLightBox(index);
				}.bind(this));
			}
	},
	
	addHit : function()
	{
		this.hitUrl = 'index.php?option=com_igallery&controller=igphoto&task=addHit&format=raw&id=' + this.options.idArray[this.imageIndex];
		this.hitAjax = new Request({url: this.hitUrl, method: 'get', 
		onComplete: function(response){}.bind(this)});
		
		this.hitAjax.send();
	},

	addArrowBehaviors: function(arrow, pixels, mode)
	{
   		this.arrowScroller = new Fx.Scroll(this.options.thumbContainer);

		document.id(arrow).addEvent('click', function(e)
		{
			this.containerSizeArray = document.id(this.options.thumbContainer).getScroll();
			this.currentScrollX = this.containerSizeArray.x;
			this.currentScrollY = this.containerSizeArray.y;

			if (mode == 'horizontal')
			{
				this.arrowScroller.start(this.currentScrollX + pixels, this.currentScrollY);
			}

			if (mode == 'vertical')
			{
				this.arrowScroller.start(this.currentScrollX, this.currentScrollY + pixels);
			}

	    }.bind(this));
    },

    lboxPreloadStarter : function()
	{
		this.preloadCounter = 0;
		this.preloaderVar = this.preloadImages.periodical(750, this);
	},

    preloadImages : function()
	{
    	new Asset.images([this.options.resizePath + this.options.jsonImagesImageType[this.preloadCounter].filename ],
		{
		    onComplete: function(){}
		});

		this.preloadCounter++;

		if(this.preloadCounter == this.options.numPics)
		{
			$clear(this.preloaderVar);
		}
	},

	swapDescription : function(index)
	{
		this.descriptionDivs = document.id(this.options.desContainer).getElements('div[class=des_div]');
		this.descriptionDivs.each(function(el,index)
		{
			el.setStyle('display', 'none');
		});

		document.id(this.options.desContainer).scrollTo(0,0);
		this.descriptionDivs[index].setStyle('display', 'block');
	},
	
	swapTags : function(index)
	{
		this.tagsDivs = document.id(this.options.tagsContainer).getElements('div[class=tags_div]');
		
		this.tagsDivs.each(function(el,index)
		{
			el.setStyle('display', 'none');
		});
		this.taglinks = this.tagsDivs[index].getElements('a');
		
		this.tagsDivs[index].setStyle('display', 'block');
		if(this.taglinks.length == 0)
		{
			this.tagsDivs[index].setStyle('visibility', 'hidden');
		}
	},

	slideShowStart : function(instant)
	{
		if(instant == true)
		{
			this.slideShowSwap(true);
		}

  		this.slideShowObject = this.slideShowSwap.periodical(this.options.slideshowPause, this, true);

  		if(this.options.showSlideshowControls == 1)
		{
			document.id(this.options.slideshowPlay).setProperty('src', this.options.imageAssetPath + 'pause.jpg');
			document.id(this.options.slideshowPlay).removeEvents();
			document.id(this.options.slideshowPlay).addEvent('click', function(e)
			{
				this.clearSlideShow();
			}.bind(this));
		}
	},

    slideShowSwap : function(forward)
	{
		if(forward == true)
		{
			if(this.imageIndex == this.options.numPics - 1)
			{
				this.imageIndex = 0;
			}
			else
			{
				this.imageIndex++
			}
		}
    	else
    	{
    		if(this.imageIndex == 0)
			{
				this.imageIndex = this.options.numPics - 1;
			}
			else
			{
				this.imageIndex--
			}
    	}

		this.swapImage(this.options.jsonImagesImageType[this.imageIndex], this.options.fadeDuration, this.imageIndex );
	},

	clearSlideShow : function()
	{
		$clear(this.slideShowObject);

		if(this.options.showSlideshowControls == 1 && $chk( $(this.options.slideshowPlay) ) )
		{
			document.id(this.options.slideshowPlay).setProperty('src', this.options.imageAssetPath + 'play.jpg');
			document.id(this.options.slideshowPlay).removeEvents();
			document.id(this.options.slideshowPlay).addEvent('click', function(e)
			{
				this.slideShowStart(true);
			}.bind(this));
		}
	},

	swapRating: function()
	{
		this.caculateDisplayRating();

		this.showRatingMessage();

		if(this.options.guest == 0)
		{
			this.ratingStars.each(function(el,index)
			{
				el.removeEvents();

				if(this.options.ratedArray[this.imageIndex] == 0)
				{
					this.addStarsMouseover(el,index);
					this.addStarsClick(el,index);
				}
			}.bind(this));
		}
	},

	caculateDisplayRating: function()
	{
		this.imgRating = this.options.ratingsArray[this.imageIndex];

		document.id(this.options.numRatings).set('html', this.options.ratingsCounterArray[this.imageIndex]);

		this.ratingStars = document.id(this.options.ratingsForm).getElements('img');

		for(this.k = 0; this.k<5; this.k++)
		{
			this.ratingStars[this.k].setProperty('src', this.options.imageAssetPath + 'star-white.gif');
		}

		for(this.m = 0; this.m<Math.floor(this.imgRating); this.m++)
		{
			this.ratingStars[this.m].setProperty('src', this.options.imageAssetPath + 'star-blue.gif');
		}

		if(this.imgRating - Math.floor(this.imgRating) > 0)
		{
			this.ratingStars[Math.floor(this.imgRating)].setProperty('src', this.options.imageAssetPath + 'star-half.gif');
		}
	},

	showRatingMessage: function()
	{
    	this.ratingMessages = document.id(this.options.ratingsMessageContainer).getElements('span');
    	this.ratingMessages.each(function(el,index){el.setStyle('display','none')});

    	if(this.options.guest == 1)
		{
    		this.ratingMessages[0].setStyle('display','inline');
		}

		if(this.options.guest == 0 && this.options.ratedArray[this.imageIndex] == 0)
		{
    		this.ratingMessages[1].setStyle('display','inline');
		}

		if(this.options.guest == 0 && this.options.ratedArray[this.imageIndex] == 1)
		{
    		this.ratingMessages[2].setStyle('display','inline');
		}
	},

	addStarsMouseover: function(el,index)
	{
		el.addEvent('mouseenter', function()
	    {
	    	for(this.i = 0; this.i<5; this.i++)
			{
				if(this.i <= index)
				{
					this.ratingStars[this.i].setProperty('src', this.options.imageAssetPath + 'star-blue.gif');
				}
				else
				{
					this.ratingStars[this.i].setProperty('src', this.options.imageAssetPath + 'star-white.gif');
				}
			}
	    }.bind(this));

	    el.addEvent('mouseleave', function()
	    {
	    	for(this.i = 0; this.i<5; this.i++)
			{
				if(this.i < Math.floor(this.imgRating))
				{
					this.ratingStars[this.i].setProperty('src', this.options.imageAssetPath + 'star-blue.gif');
				}
				else
				{
					this.ratingStars[this.i].setProperty('src', this.options.imageAssetPath + 'star-white.gif');
				}

				if(this.imgRating - Math.floor(this.imgRating) > 0)
				{
					this.ratingStars[Math.floor(this.imgRating)].setProperty('src', this.options.imageAssetPath + 'star-half.gif');
				}
			}
	    }.bind(this));
	},

	addStarsClick: function(el,index)
	{
	    el.addEvent('click', function()
	    {
	    	this.ratingMessages.each(function(el,index){el.setStyle('display','none')});
	    	this.ratingMessages[3].setStyle('display','inline');
	    	document.id(this.options.ratingsImgId).setProperty('value', this.options.idArray[this.imageIndex]);
	    	document.id(this.options.ratingsImgRating).setProperty('value', index + 1);

	    	document.id(this.options.ratingsForm).set('send',
			{
				onComplete: function(response)
				{
					this.ratingMessages.each(function(el,index){el.setStyle('display','none')});

					if(response == 'ig-login')
	    			{
						this.ratingMessages[5].setStyle('display','inline');
	    			}

	    			else if(response == 'ig-already')
	    			{
						this.ratingMessages[2].setStyle('display','inline');
	    			}
					
	    			else if(response == 'ig-restricted')
	    			{
						alert('restricted access');
						return;
	    			}

	    			else
	    			{
	    			    this.options.ratingsArray[this.imageIndex] = response;
	    			    this.options.ratedArray[this.imageIndex] = 1;
	    			    this.options.ratingsCounterArray[this.imageIndex] = this.options.ratingsCounterArray[this.imageIndex] + 1;
	    			    this.caculateDisplayRating();
	    			    this.ratingMessages.each(function(el,index){el.setStyle('display','none')});
						this.ratingMessages[4].setStyle('display','inline');
	    			}
				}.bind(this)
			});
			document.id(this.options.ratingsForm).send();
	    }.bind(this));
	},

	swapComments: function()
	{
		this.showCorrectComments();

		if(this.options.guest == 0)
		{
			this.addCommentSubmit();
		}
    },

    showCorrectComments: function()
	{
		this.commentsContainerChildDivs = document.id(this.options.commentsContainer).getElements('div');
        this.commentsCounter = 0;

    	this.commentsContainerChildDivs.each(function(el,index)
		{
			this.commentDivId = el.getProperty('class');
			this.commentDivIdArray = this.commentDivId.split("_");
			this.commentDivId = this.commentDivIdArray.pop();

			if(this.commentDivId == this.options.idArray[this.imageIndex])
			{
				el.setStyle('display','block');
				this.commentsCounter++
			}
			else
			{
				el.setStyle('display', 'none');
			}

		}.bind(this));

		document.id(this.options.commentsAmount).set('html', this.commentsCounter);

		if(this.options.main == 0)
		{
			this.totalScrollHeight = Window.getScrollHeight();
			document.id(this.options.lboxDark).setStyle('height',this.totalScrollHeight);
		}
	},

	addCommentSubmit: function()
	{
		document.id(this.options.commentsForm).removeEvents();
		document.id(this.options.commentsImgId).setProperty('value', this.options.idArray[this.imageIndex]);
		this.commentsMessages = document.id(this.options.commentsMessageContainer).getElements('span');
		this.commentsMessages.each(function(el,index){el.setStyle('display','none')});

		document.id(this.options.commentsForm).addEvent('submit', function(e)
		{
			new Event(e).stop();
			this.commentToSend = document.id(this.options.commentsTextarea).get('value');

			if(this.commentToSend.length < 1)
			{
				this.commentsMessages[0].setStyle('display','inline');
				return;
			}

			document.id(this.options.commentsLoadingGif).set('html','<img src="' + this.options.imageAssetPath + 'loader.gif' + '" />');

			document.id(this.options.commentsForm).set('send',
			{
				onComplete: function(response)
				{
					if(response == 0)
					{
						this.commentsMessages[1].setStyle('display','inline');
						return;
					}
					
					else if(response == 'ig-moderate')
	    			{
						this.commentsMessages[3].setStyle('display','block');
						document.id(this.options.commentsLoadingGif).set('html','');
						document.id(this.options.commentsTextarea).value = '';
						return;
	    			}

					this.newCommentDiv = new Element('div',
					{
						'class': 'comments_div_' + this.options.idArray[this.imageIndex]
					});

					this.newCommentDiv.set('html',response);
					this.newCommentDiv.injectInside(this.options.commentsContainer);

					if(this.options.main == 1 && this.options.lightboxOn == 1 && this.lboxGalleryObject.options.allowComments == 1)
					{
						this.newCommentDiv.clone().injectInside(this.lboxGalleryObject.options.commentsContainer);
					}
					if(this.options.main != 1 && this.mainGalleryObject.options.allowComments == 1)
					{
						this.newCommentDiv.clone().injectInside(this.mainGalleryObject.options.commentsContainer);
					}

					document.id(this.options.commentsLoadingGif).set('html','');
					this.commentsMessages[2].setStyle('display','inline');
					document.id(this.options.commentsTextarea).value = '';
					document.id(this.options.commentsAmount).set('html',this.commentsCounter + 1);
					this.showCorrectComments();

				}.bind(this)
			});
			document.id(this.options.commentsForm).send();
		}.bind(this));
	},

	showLightBox : function(index)
	{
		if(this.lboxGalleryObject.options.preload == 1)
		{
			this.lboxGalleryObject.lboxPreloadStarter();
		}

		this.bodyTag = document.getElementsByTagName("body").item(0);
		this.scrolledDown = Window.getScrollTop();
		this.totalScrollHeight = Window.getScrollHeight();
		this.totalWidth = Window.getWidth();
		this.totalHeight = Window.getHeight();

		this.lboxPaddingLeft = document.id(this.options.lboxWhite).getStyle('padding-left').toInt();
		this.lboxPaddingRight = document.id(this.options.lboxWhite).getStyle('padding-right').toInt();
		this.lboxPadding = (this.lboxPaddingLeft + this.lboxPaddingRight) / 2;
		
		if(this.lboxGalleryObject.options.lboxScalable == 1)
		{
			this.lboxTotalWidth = this.options.lightboxWidth + this.lboxPaddingLeft + this.lboxPaddingRight;
			this.widthRatio = (this.totalWidth/this.lboxTotalWidth) * 0.9;
			
			this.lboxTotalHeight = document.id(this.lboxGalleryObject.options.largeImage).getStyle('height').toInt();;
			this.heightRatio = (this.totalHeight/this.lboxTotalHeight) * 0.9;
			
			this.shrinkRatio = 1;
			this.lboxGalleryObject.shrinkRatio = 1;
			
			if(this.widthRatio < 1 || this.heightRatio < 1)
			{
				if(this.widthRatio < this.heightRatio)
				{
					this.shrinkRatio = this.widthRatio;
					this.lboxGalleryObject.shrinkRatio = this.widthRatio;
				}
				else
				{
					this.shrinkRatio = this.heightRatio;
					this.lboxGalleryObject.shrinkRatio = this.heightRatio;
				}
			}
			
			if(this.shrinkRatio < 1)
			{
				this.options.lightboxWidth = Math.round(this.options.lightboxWidth *  this.shrinkRatio);
				this.lboxTotalWidth = Math.round(this.lboxTotalWidth *  this.shrinkRatio);
				document.id(this.options.lboxWhite).setStyle('width', this.lboxTotalWidth);
				document.id(this.lboxGalleryObject.options.largeImage).setStyle('width', this.options.lightboxWidth);
				
				this.lboxTotalHeight = Math.round(this.lboxTotalHeight *  this.shrinkRatio);
				document.id(this.lboxGalleryObject.options.largeImage).setStyle('height', this.lboxTotalHeight);
				
				if(this.lboxGalleryObject.options.showThumbs == 1)
				{
					document.id(this.lboxGalleryObject.options.thumbContainer).setStyle('width', this.lboxTotalWidth);
				}
				if(this.lboxGalleryObject.options.showDescriptions == 1)
				{
					document.id(this.lboxGalleryObject.options.desContainer).setStyle('width', this.lboxTotalWidth);
				}
			}
		}
		
		this.whiteDivLeftMargin = (this.totalWidth/2) - ( (this.options.lightboxWidth)/2) - this.lboxPadding;
		document.id(this.options.lboxWhite).injectTop(this.bodyTag);
		document.id(this.options.lboxWhite).setStyles
		({
			'top': this.scrolledDown + 30,
	        'left': this.whiteDivLeftMargin,
	        'opacity': '0',
			'display': 'block',
			'float': 'left'
		});

		this.totalScrollHeight = Window.getScrollHeight();

		document.id(this.options.lboxDark).injectTop(this.bodyTag);
		document.id(this.options.lboxDark).setStyles
		({
			'width': '100%',
	        'height': this.totalScrollHeight,
	        'top': '0px',
	        'left': '0px',
	        'opacity': '0',
			'display': 'block'
		});

		this.darkDivFade = new Fx.Tween(document.id(this.options.lboxDark), {property:'opacity',duration:this.options.fadeDuration});
		this.darkDivFade.start(0,.7);

		this.whiteDivFadeIn = new Fx.Tween(document.id(this.options.lboxWhite), {property:'opacity',duration:this.options.fadeDuration});
		this.whiteDivFadeIn.start(0,1);
		
		if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
		{
			var jcommentsClone = document.id('jc').clone();
			document.id('jc').dispose();
			
			jcommentsClone.injectInside(this.options.jCommentsLbox);
			this.totalScrollHeight = Window.getScrollHeight();
			document.id(this.options.lboxDark).setStyle('height', this.totalScrollHeight);
			
		}

		this.lboxGalleryObject.swapImage(this.options.jsonImages.lbox[index], 0, index, true);
		
		if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
		{
			var jcforms = document.id('jc').getElements('form[id=comments-form]');
			jcforms.each(function(el,index)
			{
				if(index != 0)
				{
					el.dispose();
				}
			});
		}

		if(this.lboxGalleryObject.options.showSlideshowControls == 1 || this.lboxGalleryObject.options.slideshowAutostart == 1)
    	{
        	this.lboxGalleryObject.clearSlideShow();

        	if(this.lboxGalleryObject.options.showSlideshowControls == 1)
			{
			    document.id(this.lboxGalleryObject.options.slideshowForward).removeEvents();
			    document.id(this.lboxGalleryObject.options.slideshowRewind).removeEvents();

	        	document.id(this.lboxGalleryObject.options.slideshowForward).addEvent('click', function(e)
				{
					this.lboxGalleryObject.clearSlideShow();
					this.lboxGalleryObject.slideShowSwap(true);
				}.bind(this));

				document.id(this.lboxGalleryObject.options.slideshowRewind).addEvent('click', function(e)
				{
					this.lboxGalleryObject.clearSlideShow();
					this.lboxGalleryObject.slideShowSwap(false);
				}.bind(this));

			}

        	if(this.lboxGalleryObject.options.slideshowAutostart == 1)
        	{
        		this.lboxGalleryObject.slideShowStart(false);
        	}
    	}

    	this.lboxThumbId = 'lbox-' + this.options.catid + '-' + index;
    	if( $chk( document.id(this.lboxThumbId) ) )
		{
        	this.igLboxThumbScroller = new Fx.Scroll(this.lboxGalleryObject.options.thumbContainer,{duration: 50});
            this.igLboxThumbScroller.toElement( document.id(this.lboxThumbId) );
		}

		if(this.lboxGalleryObject.options.downloadType != 'none')
		{
		    var url = this.options.host + 'index.php?option=com_igallery&task=download&type=lbox&id=' + this.options.idArray[index];
            this.downloadLink = document.id(this.lboxGalleryObject.options.downloadId);
            this.downloadLink.setProperty('href',url);
		}

		document.id(this.options.closeImage).addEvent('click', function(e)
		{
			this.lboxGalleryObject.clearSlideShow();
			this.lboxGalleryObject.lastImageDisplayedIndex = -1;
			
			if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
			{
				var jcommentsClone = document.id('jc').clone();
				document.id('jc').dispose();
				jcommentsClone.injectInside(this.options.jCommentsMain);
				
				jcomments.showPage(this.options.idArray[this.imageIndex],'com_igallery',0);
				document.id('comments-form').object_id.setProperty('value', this.options.idArray[this.imageIndex]);
				
				var jcforms = document.id('jc').getElements('form[id=comments-form]');
				jcforms.each(function(el,index)
				{
					if(index != 0)
					{
						el.dispose();
					}
				});
			}

			this.darkDivFade.start(0.7,0).chain(function()
			{
				document.id(this.options.lboxDark).setStyle('display','none');
			}.bind(this));

			this.whiteDivFadeIn.start(1,0).chain(function()
			{
				document.id(this.lboxGalleryObject.options.largeImage).set('html','');
				document.id(this.options.lboxWhite).setStyle('display','none');
			}.bind(this));

			if(this.options.allowRating == 1)
			{
				this.caculateDisplayRating();
			}

		}.bind(this));
	},

	insertMagnify : function(index, mainImageLeftMargin, mainImageTopMargin)
    {
  		this.currentLargeImage = document.id(this.options.largeImage).getElement('img[class=large_img]');

  		this.largeImageLeftPadding = this.currentLargeImage.getStyle('padding-left').toInt();
    	this.largeImageTopPadding = this.currentLargeImage.getStyle('padding-top').toInt();
    	this.largeImageLeftMargin = this.currentLargeImage.getStyle('margin-left').toInt();
    	this.largeImageTopMargin = this.currentLargeImage.getStyle('margin-top').toInt();

		this.magnifyMarginLeft = mainImageLeftMargin + this.options.jsonImages.main[index].width - 27 + this.largeImageLeftPadding + this.largeImageLeftMargin;
		this.magnifyMarginTop = mainImageTopMargin + this.options.jsonImages.main[index].height - 20 + this.largeImageTopPadding + this.largeImageTopMargin;


		this.magnifyImage = new Asset.images([this.options.imageAssetPath + 'magnify.gif' ],
		{
			onComplete: function()
			{
				this.magnifyImage[0].injectInside(this.options.largeImage).setStyles
				({
					position: 'absolute',
					left: this.magnifyMarginLeft,
					top: this.magnifyMarginTop,
					'z-index': 10,
					opacity: 0.7
				});

				this.magnifyImage[0].setProperty('id', 'magnifygif');

			}.bind(this)
		});
	},

	getUrlParamater : function (strParamName)
	{
		this.strReturn = 'unset';
		this.strHref = window.location.href;

		if(this.strHref.indexOf("?") > -1)
		{
			this.strQueryString = this.strHref.substr(this.strHref.indexOf("?")).toLowerCase();
			this.aQueryString = this.strQueryString.split("&");

			for( this.i = 0; this.i < this.aQueryString.length; this.i++ )
			{
				if( this.aQueryString[this.i].indexOf(strParamName.toLowerCase() + "=") > -1 )
				{
					this.aParam = this.aQueryString[this.i].split("=");
					this.strReturn = this.aParam[1];
					break;
				}
			}
		}
		return unescape(this.strReturn);
	}

 });
