WR.util.namespace('WR.bogushtime.trainings');

/**
 * Trainings idea: before and after image series
 * 
 * @author kott
 */
WR.bogushtime.trainings.ideas = {
	init: function() {
		this.initScroller();
	},
	
	/**
	 * The list of ideas IDs. Will be filled from the 'training_idea.html' template
	 */
	IDs: [],
	
	/**
	 * Current idea ID
	 */
	curID: null,
	
	/**
	 * Initialize before-and-after scroller.
	 * 
	 * It already works in Web-1.0 (for SEO). But we will make it also as Web-2.0
	 */
	initScroller: function() {
		var cnt = $('#trainings-ideas-scroller'),
			dgrm = $('#trainings-diagrams'),
			prevBtn = $('img.prevItem', cnt),
			nextBtn = $('img.nextItem', cnt);
		
		// Wrap navigation buttons 'next' and 'prev' if needed
		if (!prevBtn.parent().is('a')) {
			prevBtn.wrap('<a href="../../bogushtime/js"></a>');
		}

		if (!nextBtn.parent().is('a')) {
			nextBtn.wrap('<a href="../../bogushtime/js"></a>');
		}
		
		var self = this;
		$('a', cnt).click(function(e) {
			// Prevent default browser link clicking
			e.preventDefault();
			
			var linkedID = $(this).attr('linked_id'),
				prevID = self.curID;
			
			// Do something with click only when there is target ID
			if (!linkedID)
				return;
			
			self.curID = linkedID;
			
			// Re-set navigation 'prev' and 'next' buttons
			var minus1ID, plus1ID;
			for (var i = 0, l = self.IDs.length; i < l; i++) {
				if (self.IDs[i] == linkedID) {
					minus1ID = self.IDs[i - 1];
					plus1ID = self.IDs[i + 1];
					break;
				}
			}
			
			if (minus1ID)
				prevBtn.removeClass('disabledItem').parent().attr('linked_id', minus1ID);
			else
				prevBtn.addClass('disabledItem').parent().removeAttr('linked_id');
			
			if (plus1ID)
				nextBtn.removeClass('disabledItem').parent().attr('linked_id', plus1ID);
			else
				nextBtn.addClass('disabledItem').parent().removeAttr('linked_id');
			
			// Remove current selected item and create new one
			$('img.scrollItem', cnt).removeClass('selectedItem');
			
			$('#scroll-point-for-idea-' + linkedID, cnt).addClass('selectedItem');
			
			// Hide old and show new diagrams/ideas
			showDiagrams: {
				// Stop current animation and hide images
                var t = dgrm.find('img.diagramImage');
                t.filter(':animated').stop(true, true);

                function _showNew() {
                    dgrm.find('#diagram-before-' + linkedID + ', #diagram-after-' + linkedID).fadeIn();
                }

                t = t.filter(':visible');
                if (t.length)
                    t.fadeOut(_showNew);
                else
                    _showNew();
			}
		});
	}
}

// Will be inited in the 'idea.html'

