// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var Photo = {
	
	upload: function() {
		$('uploading_status').show();
		$('upload_form').submit();
	},
	
	finish_upload: function () {
		var now = new Date();
		var src;
		if (document.images) {
			src = $('preview_image').getAttribute('src');
			$('preview_image').setAttribute('src', src+ now.getTime());
		}
		$('upload_container').hide();
		$('set_image_details').show();
	}
}

/* ========================================================= */
/* = this object handles toggle controls on the accordians = */
/* ========================================================= */
var Controls = {
	
	slide_toggle_vis: function (controlId, itemId) {
		
		var text1 = '[show]';
		var text2 = '[hide]';
		
		//toggle the content pane
		new Effect.toggle(itemId, 'blind');
		
		//switch the control text
		if ($(controlId).innerHTML != text1) {
			$(controlId).update(text1);
		}
		else {
			$(controlId).update(text2);
		}
	},	
	
		
	show_progress_inf: function (id) {
		//show the progress indicator with ID given
		$(id).show();
		
		//IE stops an visualBehavioursd GIF as soon as it submits the form, so set a timemout to refresh the SRC and start animation again.
		//This assumes that the image GIF has an id of <id of container>_gif
		gif = $(id + "_gif");
		setTimeout('gif.src = "/images/ajax-loader.gif"', 100);
	}
		
}



/* ======================================================================================== */
/* = this object overlays some animations and extra behaviours ontop of the standard HTML = */
/* ======================================================================================== */
var visualBehaviours = {
	
	//global constants for fade in/out timings using for image rollovers and subpages 
	contentFadeOut: 0.2,   //in seconds
	contentFadeIn: 1,      //in seconds
	contentPause: 300,     //in millisconds


	//Initialiser function coordinates all behaviours required on the page.
	// 1) calculates which subpage should be displayed
	// 2) hides spacers
	// 3) hide all subPages except the one we want
	// 4) 
	init: function () {
		//flash the cart if it's on the page
		if ($('cart')) {
			this.flashCart();
		}
		
		
		//If the page is a custom page then we need to hide the content apart from the subPage referenced in the anchor link (if any).
		//This section also needs to setup observers on the sidebar items
		if ($('subpage_content')) {
			//Find out which section we need to load by looking at the URL and looking for an anchor passed in.
			//Default to first section if no anchor supplied or anchor is invalid.
			fullURL =  window.location.href;
			anchorToLoad = this.parseURLForAnchor (fullURL, true);


			$$('#subpage_content .spacers').each (function(e) {e.remove(); });  //remove the spacers from the page as we don't want them in this enhanced view
			sections = $$('#subpage_content .subpage');            //find all of the subsections for this page
			
			//remove the subsection we intend to display from the array so it isn't hidden			
			if ($(anchorToLoad)) {
				this.sidebarUpdate ($( 'menu_' + anchorToLoad));  //highlight the required item in the sidebar 
				sections = sections.reject (function (section) { return section.readAttribute('id') == anchorToLoad});
			}
			else { sections.shift(); }  //remove 1st element of array as we want to default to keeping the first subpage
			
			//hide all subpages initially
			sections.each( function(e) { e.hide(); })
			
			//add sidebar item observers to swap content when items clicked
			$$('#subpage_menu h3').each (function (e) {e.observe ('click', visualBehaviours.sidebarItemClicked  )});
			
			//add a VIEW ALL SECTIONS menu option
			if (!$('hideViewAll')) {
				$('subpage_menu').insert('<h3 id="view_all"><a href="#">View All</a></h3>');
				$('view_all').observe ('click', visualBehaviours.sidebarViewAllClicked);
			}
			
			//add menu item observers for drop down menus
			$$('.navTopMenuItem').each (function (e) {e.observe ('click', visualBehaviours.menuItemClicked  )});
		}
		
		
		//animate the page section headings on page load
		sectionElements = $$('#subpage_menu h3');
		sectionElements.each (function (e) {e.hide(); });                   //hide all sidebar items...
		sectionElements.each (function (e, i) { setTimeout( function() {    //loop through all and schedule an animation to make sidebar item appear
			visualBehaviours.listItemAppearAnimation(e)
			}, i*100); }); 
		
		
		//animate the gallery headings on page load
		galleryElements = $$('#gallery_list .sum');
		galleryElements.each (function (e) {e.hide(); });                   //hide all sidebar items...
		galleryElements.each (function (e, i) { setTimeout( function() {    //loop through all and schedule an animation to make sidebar item appear
			visualBehaviours.listItemAppearAnimation(e)
			}, i*100); });
			
		//because we're using anchors, the page might have ended up displaying the wrong section, so change posisiton on page...
		scrollTo(0,0);
	},
	
	flashCart: function () {
		$('cart').highlight();
		
	},
	
	
	//Callback function for when the VIEW ALL link is clicked.
	//Displays all content/subpages for the page.
	sidebarViewAllClicked: function (event) {
		$$('#subpage_content .subpage').each (function (e) {e.fade({duration: 0.2});});
		setTimeout ( function() {
			$$('#subpage_content .subpage').each (function (e) { e.appear({duration: 0.2}); });
			}, 250);
		visualBehaviours.sidebarUpdate(this);
	},
	
	
	//callback function for when a link is clicked in a drop down menu
	//Because the browser doesn't reload anchor'd urls on the same page, the menus don't work. So this funciton neds to capture the click,
	//and then check if the destination page is the same as the curent page. If it is then invoke the subpage swap function.
	menuItemClicked: function (event) {
		//this funciton needs to act if the item clicked on dropdown menu is on the same page we're on
		linkURL = visualBehaviours.parseURLForAnchor (this.readAttribute('href'), false);
		fullURL = visualBehaviours.parseURLForAnchor (window.location.href, false);
		
		if (fullURL.endsWith (linkURL)) { 
			newSubpage = visualBehaviours.parseURLForAnchor (this.readAttribute('href'), true);
			visualBehaviours.swapSubpage (newSubpage);
			fadeAllMenus();
		}
	},
	
	
	//Callback function for when a link is clcked in the sidebar.
	//Parses the href of the link looking for the anchor, and uses this to work out which DIV to display.
	sidebarItemClicked: function (event) {
		linkTag = this.select('a')[0]; //under the heading there should be a single <a> tag, so take first element in the selected array
		divToShow = visualBehaviours.parseURLForAnchor (linkTag.readAttribute('href'), true);
		visualBehaviours.swapSubpage (divToShow);
	},
	
	
	//utility method to swap/load a particular content div into the man page
	swapSubpage: function (divToShow) {
		$$('#subpage_content .subpage').each (function (e) {
			e.fade({duration: visualBehaviours.contentFadeOut});
			});
			
		setTimeout (function () {  //show the correct DIV - use TImeout to allow time for previous fade to complete
			$(divToShow).appear({duration: visualBehaviours.contentFadeIn});
			}, visualBehaviours.contentPause);
		
		visualBehaviours.sidebarUpdate ($( 'menu_' + divToShow));  //animate the sidebar to provide user with some feedback
	},
	
	
	//Utility method used to animate the clicked sidebar item and highlight it by applying a CSS class.
	sidebarUpdate: function (element) {
		$$('#subpage_menu h3').each (function (e) {e.removeClassName('showing');});
		element.addClassName('showing');
		element.shake({distance: 3, duration: 1});		
	},
	
	
	//utility method to parse a url for an anchor. 2nd parameter is option: true returns the anchor and false returns the URL
	parseURLForAnchor: function (url, returnAnchor) {
		anchor = '';
		basicUrl = url;
		if (url.include('#')) {	
			anchor = url.gsub(/.*#/, ''); 
			basicUrl = url.gsub(/#.*/, '');
		}  
		return (returnAnchor ? anchor : basicUrl);  
	},

	
	//Utility method used to apply some kind of animation to a list item. Called from the init function.
	listItemAppearAnimation: function (element) {
		element.appear({duration: 0.4});
	},
	
	
	//Callback function for when a user rollsover gallery lsit items.
	//Swaps the image displayed on page for another one relavant to the list tiem hovered over. Uses animation.
	swapGalleryPreviewImage: function (newSrc) {
		var g = $('gallery_image');
		if (g.getAttribute('src') != newSrc) {
			g.fade({duration: visualBehaviours.contentFadeOut/5});
			setTimeout ( function () {
				g.writeAttribute('src', newSrc);
				g.appear({duration: visualBehaviours.contentFadeIn/3});
				}, visualBehaviours.contentPause/5);   // CHANGED: speeded up the transition of gallery rollovers
		}
	}
}





/* =================================================================================== */
/* = Slideshow object to get images via AJAX and turn a static image intoa slideshow = */
/* =================================================================================== */
var slideshow = {
	
	//TODO
	//need a pause button
	//add a replay button when the slideshow has finished
	
	totalImages: 0,     //total images downloaded from the website.
 	currentImage: {title: "", filename: "", width: 0, height: 0},
 	currentGallery: {name: "", permalink: "", images_count: 0},
	timerHandle: null,  //use this to keep track of the setTimeout
	currentArrayIndex: 0, //use this to keep track of where we are in the current array strcuture
	
	timeVisible: 3500,
	timeHidden: 1500,
	
	images: null,   //holder for the image array
	
	initialise: function (){
		if ($('slideshow_area'))
		{
			new Ajax.Request('site/slideshow_images', {
				method: 'get',
				onLoading: slideshow.showLoadingMessage(),
				onFailure: function () { alert('failure! Need to hide the loader or update the message!');},  /* TODO */
				onSuccess: function (request) { slideshow.startSlideshow(request); }
			});
		}
	},
	
	showLoadingMessage: function () {
		$('slideshow_image_area').hide(); //TODO we need to show this again if we don't have any pictures!
 		$('slideshow_message_area').update('<img src="images/ajax-loader.gif"/>Loading Images for slideshow...');
		$('slideshow_message_area').show();
	},
	
	startSlideshow: function (r) {
		$('slideshow_message_area').hide();
                $('loading_message').remove();
		this.images = r.responseJSON.collect ( function (obj) {return obj.image});   //rails 2.3.4 has changes JSON handling so we need to strip out the extra image objects
		this.totalImages = this.images.length;
		
		//check we actually have some images to play in a slideshow before we do anything!
		if(this.totalImages > 0)
		{
			//TODO elsewhere. need to handle inthe model what happens if no galleries are published. We can't rturn nil to json metho
			//preload the images if browser supports it
			if(document.images) {
				imageObj = new Array();
				for (var i = 0; i < this.images.length; i++) {
					imageObj[i] = new Image();
					imageObj[i].src = 'images/'+this.images[i].medium_filename;
				}
			}
			slideshow.setCurrentImage();		
		}
		else {
			//there are no images so show the original picture again
			$('slideshow_image_area').show();
		}
	},

	setCurrentImage: function () {
		//the assigment code in this function is a little redundant but serves to decouple to format of the JSON object form the JS used in processing slideshow
		this.currentImage.width = this.images[this.currentArrayIndex].medium_width;
		this.currentImage.height = this.images[this.currentArrayIndex].medium_height;
		this.currentImage.filename = this.images[this.currentArrayIndex].medium_filename;
		this.currentImage.title = this.images[this.currentArrayIndex].title;
		this.currentGallery.name = this.images[this.currentArrayIndex].gallery.name;
		this.currentGallery.permalink = this.images[this.currentArrayIndex].gallery.permalink;
		this.currentGallery.images_count = this.images[this.currentArrayIndex].gallery.images_count;
		this.currentArrayIndex++;
		slideshow.displayCurrentImage();
		//increment the array counter for the next iteration
		if (this.currentArrayIndex < this.totalImages) {
			this.timerHandle = setTimeout ("slideshow.hideCurrentImage()", this.timeVisible);
		}
	},

	displayCurrentImage: function () {
		$('slideshow_image').writeAttribute({src: '/images/'+this.currentImage.filename, width: this.currentImage.width, height: this.currentImage.height, alt: this.currentImage.title});
		$('slideshow_link').writeAttribute ({href: '/print-galleries/' + this.currentGallery.permalink + '/1'});
		$('image_title').update('"' + this.currentImage.title + '"');
		// $('image_title').update('"' + this.currentImage.title + '" (image ' + this.currentArrayIndex + ' of ' + this.totalImages + ')');
		$('gallery_desc').update('Taken from gallery "' + this.currentGallery.name + '"&nbsp;&nbsp;&nbsp;(' + this.currentGallery.images_count + ' images)');

		$('slideshow_text').hide();
		$('slideshow_image_area').show();
		$('slideshow_text').slideDown({queue: 'end'});

		
	},
	
	hideCurrentImage: function () {
		$('slideshow_image_area').fade();
		if (this.currentArrayIndex < this.totalImages) {
			this.timerHandle = setTimeout ("slideshow.setCurrentImage()", this.timeHidden);
		}
	}
};


/* ====================================== */
/* = Javascript initiators on page load = */
/* ====================================== */
document.observe('dom:loaded', function () { slideshow.initialise(); });
document.observe('dom:loaded', function () { visualBehaviours.init(); });