/*
    This file is part of JonDesign's SmoothGallery v2.0.

    JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    JonDesign's SmoothGallery is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JonDesign's SmoothGallery; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
*/
	
var gallerySet = gallery.extend({
	initialize: function(element, options) {
		this.setOptions({
			manualSetData: [],
			gallerySelector: "div.galleryElement",
			galleryTitleSelector: "h2",
			galleryDescSelector: "span.galleryDescription",
			textGallerySelector: "{0}",
			textShowGallerySelector: '{0}',
			textGalleryInfo: '{0} pictures',
			startWithSelector: true,
			showCarouselOpen: true,
			/* Changing default options */
			carouselPreloader: true
		}, options);
		
		this.options.textGallerySelector = document.getElementById("SSsectionName").firstChild.nodeValue;
		this.options.textShowGallerySelector = "See more " + document.getElementById("SSsectionName").firstChild.nodeValue;
		this.gallerySet = this.options.manualSetData;
		this.addEvent('onPopulated', this.createGallerySelectorTab.bind(this));
		
/* SELECT STONE GALLERY FILES PANEL + GALLERY ARROWS PANEL */
		this.addEvent('onPopulated', this.createGallerySelector.bind(this));
		this.startWithSelectorFn = this.toggleGallerySelector.pass(true, this);
		if (this.options.startWithSelector){
			this.addEvent('onGallerySelectorCreated', this.startWithSelectorFn);
			this.addEvent('onPopulated', this.createGalleryFilesPanel.bind(this));
		}
		this.parent(element, this.options);
	},
	populateData: function() {
		options = this.options;
		var data = this.gallerySet;
		this.populateFrom.getElements(options.gallerySelector).each(function (galEl) {
			currentGalArrayPlace = 0;
			galleryDict = {
				cutsheet: galEl.getElement('span').getAttributeNode('rel').value,
				tileimage: galEl.getElement('span').getAttributeNode('name').value,
				astmspec: galEl.getElement('span').getAttributeNode('rev').value,
				title: galEl.getElement(options.galleryTitleSelector).innerHTML,
				gallerydesc: galEl.getElement(options.galleryDescSelector).innerHTML,
				elements: []
			};
			galleryDict.elements.extend(this.populateGallery(galEl, 0));
			data.extend([galleryDict]);
			if (this.options.destroyAfterPopulate){galEl.remove();}
		}, this);
		this.gallerySet = data;
		this.galleryData = data[0].elements;
		this.currentGallery = 0;
		this.fireEvent('onPopulated');
	},
	
/* --> SELECT STONE GALLERY FILES PANEL FUNCTION */
		createGalleryFilesPanel: function() {
			this.galleryFilesPanel = new Element('span').setProperties({
				id: "galleryFilesPanel"
			})
			.setStyles({
				'visibility': 'hidden',
				'position': 'absolute',
				'top': '-36px',
				'left': '475px'
			}).injectInside(document.getElementById("SS_mainBody"));
			
/* --> SELECT STONE: After the Gallery Files Panel is created, put link elements inside of it and point them to the first item in the 'gallerySet' array */
			this.galleryFilesPanel.appendChild(new Element ('a').setProperties({href: "/download/" + this.gallerySet[0].astmspec, id: "SSastmSpec", title: "Download this stone's ASTM specifications", target: "_blank"}).setHTML('ASTM Spec'));
			this.galleryFilesPanel.appendChild(new Element ('a').setProperties({href: "/download/" + this.gallerySet[0].tileimage, id: "SStileImage", title: "Download this stone's CAD tile", target: "_blank"}).setHTML('Tile Image'));
			this.galleryFilesPanel.appendChild(new Element ('a').setProperties({href: "/download/" + this.gallerySet[0].cutsheet, id: "SScutSheet", title: "Download this stone's cutsheet", target: "_blank"}).setHTML('Cut Sheet'));
			this.galleryFilesPanel.appendChild(new Element ('a').setProperties({href: "/download/" + this.gallerySet[0].cutsheet, id: "SSdownloadFile", title: "Download the current image in high-resolution", target: "_blank"}).setHTML('Full-Size Photo')); 
			
			if( !this.gallerySet[0].cutsheet ){ document.getElementById('SScutSheet').setStyle('visibility', 'hidden'); }
			if( !this.gallerySet[0].tileimage ){ document.getElementById('SStileImage').setStyle('visibility', 'hidden'); }
			if( !this.gallerySet[0].astmspec ){ document.getElementById('SSastmSpec').setStyle('visibility', 'hidden'); }
			
			this.addEvent('onGalleryButtonClicked', function(){this.galleryFilesPanel.setStyle('visibility', 'visible'); if (this.options.showCarouselOpen == true) {
				this.toggleCarousel()
			}}.bind(this));
			this.addEvent('onBackToGalleries', function(){this.galleryFilesPanel.setStyle('visibility', 'hidden'); }.bind(this));
			var SSgalleryFilesPanel = this.galleryFilesPanel;
		},
	changeGallery: function(number)
	{
		if (number!=this.currentGallery || this.galleryChanged == undefined )
		{
			this.changeData(this.gallerySet[number].elements);
			this.maxIter = this.gallerySet[number].elements.length;
/* --> SELECT STONE: Find the link elements in the Gallery Files Panel by their ID, and update their links to match the numbers in the 'gallerySet' array */
			if (this.gallerySet[number].cutsheet > 0) {
				document.getElementById('SScutSheet').getAttributeNode('href').value = '/download/' + this.gallerySet[number].cutsheet;
				document.getElementById('SScutSheet').setStyle('visibility', 'inherit');
			} else { document.getElementById('SScutSheet').setStyle('visibility', 'hidden');}
			if (this.gallerySet[number].tileimage > 0) {
				document.getElementById('SStileImage').getAttributeNode('href').value = '/download/' + this.gallerySet[number].tileimage;
				document.getElementById('SStileImage').setStyle('visibility', 'inherit');
			} else { document.getElementById('SStileImage').setStyle('visibility', 'hidden'); }
			if (this.gallerySet[number].astmspec > 0) {
				document.getElementById('SSastmSpec').getAttributeNode('href').value = '/download/' + this.gallerySet[number].astmspec;
				document.getElementById('SSastmSpec').setStyle('visibility', 'inherit');
			} else { document.getElementById('SSastmSpec').setStyle('visibility', 'hidden'); }
			this.currentGallery = number;
			/* this.gallerySelectorBtn.setHTML(this.gallerySet[number].title); */
			this.fireEvent('onGalleryChanged');
			this.galleryChanged = 'defined';
		}
		this.toggleGallerySelector(false);
	},
	createGallerySelectorTab: function() {
		this.gallerySelectorBtn = new Element('a').addClass('gallerySelectorBtn').setProperties({
			title: this.options.textShowGallerySelector
		})
		.setHTML(this.options.textShowGallerySelector).addEvent(
			'click', 
			function(){ this.toggleGallerySelector(true); this.fireEvent('onBackToGalleries'); }.bind(this)
		).injectInside(this.galleryElement);
		this.addEvent('onShowCarousel', function(){this.gallerySelectorBtn.setStyle('zIndex', 10);}.bind(this));
		this.addEvent('onCarouselHidden', function(){this.gallerySelectorBtn.setStyle('zIndex', 15);}.bind(this));
	},
	createGallerySelector: function() {
		this.gallerySelector = new Fx.Styles(
			new Element('div').addClass('gallerySelector').injectInside(this.galleryElement).setStyles({'display': 'none','opacity': '0'}));
		this.gallerySelectorTitle = 
			new Element('h2').setHTML(this.options.textGallerySelector).injectInside(this.gallerySelector.element);
		var gallerySelectorHeight = this.galleryElement.offsetHeight - 50 - 10 - 2;
		this.gallerySelectorWrapper = new Fx.Style(
			new Element('div').addClass('gallerySelectorWrapper').setStyle('height',gallerySelectorHeight + "px").injectInside(this.gallerySelector.element)
		);
		this.gallerySelectorInner =	new Element('div').addClass('gallerySelectorInner').injectInside(this.gallerySelectorWrapper.element);
		this.gallerySelectorWrapper.scroller = new Scroller(this.gallerySelectorWrapper.element, {
			area: 100,
			velocity: 0.3
		}).start();
		this.createGalleryButtons();
		this.fireEvent('onGallerySelectorCreated');
	},
	createGalleryButtons: function () {
		var galleryButtonWidth =
			((this.galleryElement.offsetWidth - 30) / 2) - 14;
		this.gallerySet.each(function(galleryItem, index){
			var button = new Element('div').addClass('galleryButton').injectInside(this.gallerySelectorInner).addEvents({
				'mouseover': function(myself){
					myself.button.addClass('hover');
				}.pass(galleryItem, this),
				'mouseout': function(myself){
					myself.button.removeClass('hover');
				}.pass(galleryItem, this),
				'click': function(myself, number){
					this.fireEvent('onGalleryButtonClicked');
					this.changeGallery.pass(number,this)();
				}.pass([galleryItem, index], this)
			}).setStyle('width', galleryButtonWidth);
			galleryItem.button = button;
			var thumbnail = "";
			if (this.options.showCarousel) {
				thumbnail = galleryItem.elements[0].thumbnail;
			}
			else {
				thumbnail = galleryItem.elements[0].image;
			}
			new Element('div').addClass('preview').setStyle(
				'backgroundImage',
				"url('" + thumbnail + "')"
			).injectInside(button);
			new Element('h3').setHTML(galleryItem.title).injectInside(button);
			new Element('h5').setHTML(galleryItem.gallerydesc).injectInside(button);
			new Element('p').addClass('info').setHTML(formatString(this.options.textGalleryInfo, galleryItem.elements.length)).injectInside(button);
		}, this);
		new Element('br').injectInside(this.gallerySelectorInner).setStyle('clear','both');
	},
	toggleGallerySelector: function(state) {
		if (state)
			this.gallerySelector.start({'opacity' : 1}).element.setStyle('display','block');
		else
			this.gallerySelector.start({'opacity' : 0});
	},
	initHistory: function() {
		this.fireEvent('onHistoryInit');
		this.historyKey = this.galleryElement.id + '-gallery';
		if (this.options.customHistoryKey)
			this.historyKey = this.options.customHistoryKey();
		this.history = HistoryManager.register(
			this.historyKey,
			[0,0],
			function(values) {
				this.changeGallery.pass(parseInt(values[0]) - 1, this).delay(10);
				if(values[0] != 0 && values[1] != 0){
					this.toggleGallerySelector.pass(false, this).delay(1000);
					this.galleryFilesPanel.setStyle('visibility', 'visible');
					if(this.options.showCarouselOpen == true && this.carouselActive == false)this.toggleCarousel();}
				this.goTo.pass(parseInt(values[1]) - 1, this).delay(100);
				if(parseInt(values[0]) > 0 && parseInt(values[1]) < 1){
					this.galleryFilesPanel.setStyle('visibility', 'hidden'),
					this.toggleCarousel(),
					this.toggleGallerySelector(true).delay(200);}
				/*alert('Values array has ' + values.length + " values\n" + values[0] + "\n" + values[1]);*/
			}.bind(this),
			function(values) {
				return [this.historyKey, '(', values[0], ')', '-picture','(', values[1], ')'].join('');
			}.bind(this),
			this.historyKey + '\\((\\d+)\\)-picture\\((\\d+)\\)');
		updateHistory = function(){
			this.history.setValue(0, this.currentGallery + 1);
			this.history.setValue(1, this.currentIter + 1);
		}.bind(this);
		this.addEvent('onChanged', updateHistory);
		this.addEvent('onGalleryChanged', updateHistory);
		this.fireEvent('onHistoryInited');
	}
});