ItGallery = Class.create();

ItGallery.prototype = {

	initialize:function( objDefSettings )
	{
		this.sLoadingImage 	= (objDefSettings.loadingImage!='undefined')?objDefSettings.loadingImage:false;
		this.iOpacity		= (objDefSettings.opacity!='undefined')?objDefSettings.opacity:1;
		this.sRelName		= (objDefSettings.rel!='undefined')?objDefSettings.rel:'gallery';
		this.ImageBoxSizeX	= 900;
		this.ImageBoxSizeY	= 675;
		this.serverURI		= (objDefSettings.uri)?objDefSettings.uri:'';
		this.buttonCloseImage	= objDefSettings.buttonClose;
		this.imagesNavLogo	= objDefSettings.imagesNavLogo;

		this.iImageCount		= 0;
		this.showImageBox 		= false;	//check show or not Div with full Image
		this.aImagesMap			= Array();
		this.objImageContainer	= document.getElementsByTagName("body")[0];
		this.currentImageIndex  = -1;

	},

	createImageMap:function()
	{
		var aImageThumbs = $(this.objImageContainer).getElementsBySelector('a[rel="'+this.sRelName+'"]');
		for(var i=0; i<aImageThumbs.length; i++)
		{
			aImageThumbs[i].onclick = function()
			{
				return false;
			}
			Event.observe(aImageThumbs[i],'click', this.bShowImage.bindAsEventListener(this,i) );
			var img = aImageThumbs[i].down('img');
			var sImageDescription = '';
			if( img )
			{
				sImageDescription = img.alt;
			}
			sImageTitle = (aImageThumbs[i].title)?aImageThumbs[i].title:'Image '+(i+1);
			this.bAddNewImage(aImageThumbs[i].href,sImageTitle, sImageDescription);
		}
	},

	bAddNewImage:function(sImageUrl,sTitle, sDescription)
	{
		this.aImagesMap[this.iImageCount] = {src:sImageUrl,
											 title:sTitle,
											 description:sDescription};
		this.iImageCount++;
	},

	bShowImage:function(objEvent, iImageId)
	{
		this.currentImageIndex = iImageId;
		if(!this.showImageBox )
		{
			this.bCreateImageLayers();
		}
		Element.clearChildren(this.imageBox);
		var objPreloaderDiv	= this.imageBox.append('div',{className:'preLoader',id:'preloader',width:this.ImageBoxSizeX+'px'})
		if( this.sLoadingImage )
		{
			objPreloaderDiv.style.backgroundImage = 'url("'+this.sLoadingImage+'")';
		}

		this.objCurrentImage = new Image();
		this.objCurrentImage.title = this.aImagesMap[iImageId].title;
		this.objCurrentImage.alt = this.aImagesMap[iImageId].description;
		Event.observe(this.objCurrentImage,'load',this.bInsertImageInBoxLA.bindAsEventListener(this,iImageId))

		this.objCurrentImage.src = this.aImagesMap[iImageId].src;
	},

	bCreateImageLayers:function()
	{
		var overlayDiv = this.objImageContainer.append('div',{id:'overlay-it-gallery'},{} );
			overlayDiv.setOpacity(this.iOpacity);

		this.imageBoxCont = this.objImageContainer.append('table',{className:'popup-arrow'},{width:'920px',height:'740px'} );
		var sTr = '<tr style="height:9px"><td width="9" height="9"><img src="'+this.serverURI+'images/sh-tab01.png" width="9" height="9" class="png" alt="" title="" /></td>';
            sTr+= '<td height="9" class="sh-top"><!-- top shadow --></td>';
            sTr+= '<td width="9" height="9"><img src="'+this.serverURI+'images/sh-tab02.png" width="9" height="9" class="png" alt="" title="" /></td>';
            sTr+= '</tr>';
            sTr+= '<tr style="vertical-align:top"><td width="9" class="sh-left"><!-- left shadow --></td><td id="imageTDContainer" align="center" valign="middle" width="900" height="700" style="text-align:center;vertical-align:top;background-color:white">';
            sTr+= '</td><td width="9" class="sh-right"><!-- shadow right --></td>';
            sTr+= '</tr><tr><td width="9" height="9"><img src="'+this.serverURI+'images/sh-tab03.png" width="9" height="9" class="png" alt="" title="" /></td>';
            sTr+= '<td class="sh-bt"><!-- shadow bottom --></td><td width="9" height="9">';
            sTr+= '<img src="'+this.serverURI+'images/sh-tab04.png" width="9" height="9" class="png" alt="" title="" /></td></tr></table>';
		
		this.imageBoxCont.update(sTr);
		this.imageBox = $('imageTDContainer').append('div',{className:'popup-photo'});

		this.imageBox.hide();
		this.bResizeOverlayWindow( overlayDiv );
		this.imageBox.show();

		Event.observe(window,'resize',this.bResizeOverlayWindowLA.bindAsEventListener(this,overlayDiv ));
		this.showImageBox	= true;
 	},

	bInsertImageInBox:function(iImageIndex )
	{
		this.bCorrectImageSizes();
		Element.remove($('preloader'));

		this.imageBox.appendChild( this.objCurrentImage );
		this.imageBox.style.verticalAlign = "middle";
		this.imageBox.update(this.sGetTemplateNavigationPopup() + this.imageBox.innerHTML );
		var objDescriptionDiv = this.imageBox.append('div',{className:'popup-description'});
		objDescriptionDiv.style.width = this.objCurrentImage.width + "px";
		if( this.descriptionMarginLeft > 0)
		{
			if(!Prototype.Browser.IE)
			{
				objDescriptionDiv.style.paddingLeft = this.descriptionMarginLeft + "px";
			}
		}
		var sDesString = this.objCurrentImage.title;
		if( this.objCurrentImage.alt )
		{
			sDesString+= '<br />' +this.objCurrentImage.alt;
		}
		objDescriptionDiv.update(sDesString);
		this.setImageBoxCathers();
	},

	bInsertImageInBoxLA:function(objEvent,iImageIndex )
	{
		this.descriptionMarginLeft = Math.ceil( (this.ImageBoxSizeX - this.objCurrentImage.width)/2);
		this.bInsertImageInBox(iImageIndex);
	},

	setImageBoxCathers:function()
	{
		var aCloseButtons = $(this.imageBox).getElementsBySelector('a[rel="buttonClose"]');
		for(var i=0;i<aCloseButtons.length;i++)
		{
			aCloseButtons[i].onclick = function()
			{
				return false;
			}
			Event.observe(aCloseButtons[i],'click',this.bCloseImageBoxLA.bindAsEventListener(this) );
		}
		if( this.currentImageIndex > 0 )
		{
			this.bSetPrevCatchers();
		}
		if( this.currentImageIndex < this.aImagesMap.length -1 )
		{
			this.bSetNextCatchers();
		}
		if(this.iImageCount > 1)
		{
			this.bSetNavNumCatchers();
		}
	},

	bSetPrevCatchers:function()
	{
		var aFirstButton = $(this.imageBox).getElementsBySelector('a[rel="buttonNavFirst"]');
		for(var i=0;i<aFirstButton.length;i++)
		{
			aFirstButton[i].onclick = function()
			{
				return false;
			}
			Event.observe(aFirstButton[i],'click',this.bShowImage.bindAsEventListener(this,0) );
		}
		var aPrevButton = $(this.imageBox).getElementsBySelector('a[rel="buttonNavPrev"]');
		for(var i=0;i<aPrevButton.length;i++)
		{
			aPrevButton[i].onclick = function()
			{
				return false;
			}
			Event.observe(aPrevButton[i],'click',this.bShowImage.bindAsEventListener(this,this.currentImageIndex -1) );
		}
	},

	bSetNextCatchers:function()
	{
		var aLastButton = $(this.imageBox).getElementsBySelector('a[rel="buttonNavLast"]');
		for(var i=0;i<aLastButton.length;i++)
		{
			aLastButton[i].onclick = function()
			{
				return false;
			}
			Event.observe(aLastButton[i],'click',this.bShowImage.bindAsEventListener(this,this.iImageCount-1) );
		}
		var aNextButton = $(this.imageBox).getElementsBySelector('a[rel="buttonNavNext"]');
		for(var i=0;i<aNextButton.length;i++)
		{
			aNextButton[i].onclick = function()
			{
				return false;
			}
			Event.observe(aNextButton[i],'click',this.bShowImage.bindAsEventListener(this,Number(this.currentImageIndex) + 1) );
		}
	},

	bSetNavNumCatchers:function()
	{
		var aNavButton = $(this.imageBox).getElementsBySelector('a[rel="buttonNavNum"]');
		for(var i=0;i<aNavButton.length;i++)
		{
			aNavButton[i].onclick = function()
			{
				return false;
			}
			sId = aNavButton[i].id;
			sId = sId.replace("navnum","");
			Event.observe(aNavButton[i],'click',this.bShowImage.bindAsEventListener(this,sId) );
		}

	},

	bCorrectImageSizes:	function()
	{
		/*
		if(!this.ImageBoxSizeX || !this.ImageBoxSizeX )
		{
			return;
		}
		var perfectImageX = this.ImageBoxSizeX;
		var perfectImageY = this.ImageBoxSizeY;

		if( Number(this.objCurrentImage.width) >  Number(perfectImageX) )
		{
			k = ( this.objCurrentImage.width / perfectImageX );
			this.objCurrentImage.width  = perfectImageX;
			this.objCurrentImage.height = Math.floor( this.objCurrentImage.height/k );
		}
		if( Number(this.objCurrentImage.height) > Number(perfectImageY) )
		{
			k = this.objCurrentImage.height / perfectImageY ;
			this.objCurrentImage.height = perfectImageY;
			this.objCurrentImage.width  = Math.floor( this.objCurrentImage.width / k);
		}
		*/
		this.objCurrentImage.style.marginTop = parseInt(Math.floor( (this.ImageBoxSizeY - this.objCurrentImage.height)/2) ) + "px";
	},


	bResizeOverlayWindow:function(objDiv)
	{
		var arrayPageSize 	= Element.getPageSize();
		var W = arrayPageSize[0];
		var H = arrayPageSize[1];

		objDiv.style.width 	= W + "px";
		objDiv.style.height = H + "px";

		iImageBoxTop = Math.floor((arrayPageSize[3] - this.ImageBoxSizeY)/2) + Math.max(document.body.scrollTop,document.documentElement.scrollTop);
		this.imageBoxCont.style.top = iImageBoxTop + "px";

		if( arrayPageSize[2] > this.ImageBoxSizeX )
		{
			iImageBoxLeft = Math.floor((arrayPageSize[2] - this.ImageBoxSizeX)/2) + Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
		}
		else
		{
			iImageBoxLeft = 10;
		}
		this.imageBoxCont.style.left = iImageBoxLeft + "px";
	},

	bResizeOverlayWindowLA:function(objEvent,objDiv)
	{
		this.bResizeOverlayWindow(objDiv);
	},

	bCloseImageBox: function()
	{
		Event.stopObserving(window,'resize',this.bResizeOverlayWindowLA );
		Element.remove(this.imageBox);
		Element.remove(this.imageBoxCont);
		Element.remove($('overlay-it-gallery'));
		this.showImageBox = false;
	},

	bCloseImageBoxLA:function(objEvent)
	{
		this.bCloseImageBox();
	},

	sGetTemplateNavigationPopup:function()
	{
		var aDimes = this.imageBoxCont.getDimensions();
		var Navigation = new Template('<span><a href="#" title="" rel="buttonNavNum" id="navnum#{ImageId}"> #{imageIndex} </a></span>');

		var sTemplate  = '';
			sTemplate += '<table cellpadding="0" cellspacing="0" class="PictureGalleryNavigation"><tr>';
			sTemplate += '<td class="PictureTitle">#{imageTitle}</td>';
			sTemplate += '<td class="NavPages"><div class="NavPages-bg"><div class="NavPages-innerbg">';
			sTemplate += '<table cellpadding="0" cellspacing="0">';
			sTemplate += '<tr><td><img src="'+this.serverURI+'images/'+this.imagesNavLogo +'" title="" alt="Pictures" />';
			
			
			if( this.currentImageIndex != 0)
			{
				sTemplate += '<a href="#" title="" rel="buttonNavFirst" class="NavIconBegin"><img src="'+this.serverURI+'images/empty.gif" title="" alt="" width="13" height="13" /></a>';
                sTemplate += '<a href="#" title="" rel="buttonNavPrev" class="NavIconPrev"><img src="'+this.serverURI+'images/empty.gif" title="" alt="" width="13" height="13" /></a>';
			}
			else
			{
				sTemplate += '<span class="NavIconBegin-Inact"><img src="'+this.serverURI+'images/empty.gif" title="" alt="" width="13" height="13" /></span>';
                sTemplate += '<span class="NavIconPrev-Inact"><img src="'+this.serverURI+'images/empty.gif" title="" alt="" width="13" height="13" /></span>';
			}
			
			sTemplate += '<span class="PagesLink">';
			 
			for(i=0;i<this.aImagesMap.length; i++ )
			{
				var imageIndex = i+1;
				if(i!= this.currentImageIndex )
				{
					sTemplate += Navigation.evaluate({imageIndex:imageIndex,
													  ImageId:i});
				}
				else
				{
					sTemplate += '<span class="OpenPicture"> '+imageIndex+' </span>';
				}
			}
			sTemplate += '</span>';

			
			if( this.currentImageIndex != this.iImageCount -1)
			{
				sTemplate += '<a href="#" title="" rel="buttonNavNext" class="NavIconEnd"><img src="'+this.serverURI+'images/popup-nav-next.gif" title="" alt="" /></a>';
                sTemplate += '<a href="#" title="" rel="buttonNavLast" class="NavIconNext"><img src="'+this.serverURI+'images/popup-nav-end.gif" title="" alt="" /></a>';
			}
			
			else
			{
				sTemplate += '<span class="NavIconEnd-Inact"><img src="'+this.serverURI+'images/popup-nav-next.gif" title="" alt="" /></span>';
                sTemplate += '<span class="NavIconNext-Inact"><img src="'+this.serverURI+'images/popup-nav-end.gif" title="" alt="" /></span>';
			}

		sTemplate += '</td></tr></table></div></div>';
		sTemplate += '</td><td class="ButtonClose"><a href="#" title="" rel="buttonClose">';
		sTemplate += '<img src="'+this.serverURI+ 'images/'+this.buttonCloseImage+'" title="" alt="" class="button-close" /></a></td></tr></table>';		
		
		var popupWindow = new Template(sTemplate);
		var show = {imageTitle:this.aImagesMap[this.currentImageIndex].title};
		return popupWindow.evaluate(show);
	}
};

var $CE = function(tagName, attributes, styles){ //short for create element
      var el = document.createElement(tagName);
      if (attributes)
            $H(attributes).each(function(pair){
                  eval("el." + pair.key + "='" + pair.value + "'");
            });
      if (styles)
            $H(styles).each(function(pair)
            {
                el.style[pair.key] = pair.value;
            });

      return $(el);
};

Element.addMethods({
	clearChildren: function(element) {
		element = $(element);
		$A(element.childNodes).each(function(e){
			  e.parentNode.removeChild(e);
		});
		return element;
	},

	append: function(element, tagName, attributes, styles) {
		element = $(element);
		var newEl = $CE(tagName, attributes, styles);
		element.appendChild(newEl);
		return newEl;//<-- this one returns the new element
	},

	appendText: function(element, text){
		element = $(element);
		var t = document.createTextNode(text);
		element.appendChild(t);
		return element;
	  },

	getPageSize:function ()
	{
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	//console.log("xScroll " + xScroll)
	//console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
	//console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}
});