/** HealManager
 *	@author : Partikule studio 2009
 *	
 *	Options :
 *
 *		baseUrl:		URL to the website
 *		parent:			type of the parent. 'article', 'page', etc. Used to update the database table.                 
 *		idParent:		ID of the parent element      
 *		pContainer:		The picture container DOM element 
 *		mContainer:		The MP3 list container DOM element
 *		vContainer:		The video list container DOM element
 *		button:			DOM opener button name
 *		wait:			DOM wait spinner elmement
 *		mode:			'tinyBrowser' : Using the tinyBrowser plugin to browse files
 *						'mcFileManager' : Using MoxeCode MceImageManager / MceFileManager to browse files
 */

var HealManager = new Class({
	
	Implements: Options,

	options: {
		baseUrl:			'',
		togglers:			'.toggler',			// Menu togglers
		elements:			'.element',			// Menu element content
		container:			'content',			// Container name
		bgContainer :		'bg',				// Background container
		loader:				{'animate': ['loader-#.png', 12]},
		loaderContainer:	'menu',
		loaderUrl:			'static/frontend/healfashionlab/images/spinner/black/',
		debug:				'',					// Debug Div. Debug not printed if '';
		rel:				'',					// Related link. 0 : Home. Used to decide if bg picture is showed or not at class startup
		saveEvent:			false
	},

	initialize: function(options){
	
		// class attributes
		this.imgRatio = 1;
		this.imgHeight = 0;
		this.imgWidth = 0;

		// Options
		this.setOptions(options);

		this.container =		$(this.options.container);
		this.loaderContainer =	$(this.options.loaderContainer);
		this.bgContainer = 		$(this.options.bgContainer);
		
		// Togglers
		this.togglers = 		$$(this.options.togglers);
		this.elements = 		$$(this.options.elements);
		
		// Links collections
		this.togglersLinks = 	$$(this.options.togglers + ' a');
		this.elementsLinks = 	$$(this.options.elements + ' a');

		// Menu & Logo
		this.menu = $('menu');
		this.menulang = $('menuLang');
		this.menulangA = $$('#menuLang ul li a');
		
		this.logoWhite = $('logo-white');
		this.logoBlack = $('logo-black');
		
		this.links = $('links');
		this.linksA = $$('#links li a');

		$('footer').fade('hide');
		this.links.fade('hide');
		this.menulang.fade('hide');
		
		// Menu
		this.initMenu();

		// Background image : Home
		this.initBackground();

		// Loader
		if (this.options.loader)
 			this._loader();
 			
		this.showSlider = true;
		if (Browser.Engine.webkit && Browser.Engine.version < 500)
		{
			this.showSlider = false;
		}

 		// Slider
		if (this.showSlider)
		{
			this.setSlider();
		}
		
	
	},


	initMenu: function()
	{
		// Show Menu
		this.menu.fade('hide');
		this.menu.setStyle('display','block');

		this.logoBlack.fade('hide');
		this.logoBlack.setStyle('display', 'block');
	
		this.logoWhite.fade('hide');
		this.logoWhite.setStyle('display', 'block');
	
		this.links.fade('hide');
		this.links.setStyle('display', 'block');
	
		this.menulang.fade('hide');
		this.menulang.setStyle('display', 'block');
		
		// Accordion init
		this.accordion = new Accordion($$(this.options.togglers), $$(this.options.elements));
		
		// Current menu item
		this.currentMenuItem = $$('.current-menu-item').getProperty('rel');
		
		// Display current accordion
		this.accordion.display(this.currentMenuItem);

		// The menu elements to white
		if (this.currentMenuItem == 0)
		{
			this.togglersLinks.addClass('white');
			this.elementsLinks.addClass('white');
			this.menulangA.addClass('white');
			
/*
			this.menuFadeIn.delay(2000, this);
			this.menulangFadeIn.delay(2000, this);
			this.logoWhiteFadeIn.delay(2000, this);
*/
			this.menu.fade('in');
			this.menulang.fade('in');
			this.logoWhite.fade('in');

		}
		else
		{
			this.menu.fade('show');
			this.logoBlack.fade('show');
			this.links.fade('show');
			this.menulang.fade('show');
		}
		
		// Events on main togglers
		this.togglersLinks.addEvent('click', function(evt)
		{
			
			var el =	evt.target;
			
			if (el.hasClass('external'))
			{

			}
			else
			{
				evt.stop();
	
				var href =	el.getProperty('href');
				var rel =	el.getProperty('rel');		// Get the accordion element id
				var page = (href.substring(href.lastIndexOf('/')+1)).replace('.html', '');
	
				var url = this.options.baseUrl + 'page/single/' + page;

				// Accordion event
				this.accordion.display(rel);
	
				// Hide active class on items
				this.togglersLinks.removeClass('active');
				this.elementsLinks.removeClass('active');
				
				// Home page : Show the bg picture, don't show the active style
				this.currentMenuItem = rel;
				if (rel == 0)
				{
					this.showBackground();
					$('footer').fade('hide');
	
					this.togglersLinks.addClass('white');
					this.elementsLinks.addClass('white');
					this.menulangA.addClass('white');
	
					this.links.fade('hide');
					this.logoWhite.fade('in');
					this.logoBlack.fade('out');
				}
				// Hide the bg picture
				else
				{
					this.hideBackground();
					$('footer').setStyle('display','block');
					$('footer').fade('in');
					
					this.togglersLinks.removeClass('white');
					this.elementsLinks.removeClass('white');
					this.menulangA.removeClass('white');
					
					this.logoBlack.fade('in');
					this.links.fade('in');
					this.logoWhite.fade('out');
				}
	
				// Show active menu / active submenu
				el.addClass('active');
				
				// Activate the first submenu
				this.activateFirstSubmenu(this.currentMenuItem);
	
				// Show spinner
				if (Browser.Engine.trident != true) {
					this.loaderContainer.retrieve('loader').fireEvent('show');
				}
				
				// Content fade out
				this.container.fade('out');
	
				// Request
				var myRequest = new Request.HTML({
									url:url,
									onSuccess: this.showContent.bind(this),
									evalScripts: false
									//evalResponse: true
								}).send();
			}
			
		}.bind(this));
		 
		
		// Events on sub-menu elements
		this.elementsLinks.addEvent('click', function(evt)
		{
			evt.stop();
			evt.stopPropagation();
			
			this.elementsLinks.removeClass('active');
			
			// Show active submenu
			evt.target.addClass('active');

			// Show active menu : get parent
			$('toggler'+this.currentMenuItem).addClass('active');

		}.bind(this));
		 
	},


	/** Menu intro fade in 
	 */
	menuFadeIn: function()
	{
		this.menu.fade('in');
	},


	/** Logo intro fade in 
	 */
	logoWhiteFadeIn: function()
	{
		this.logoWhite.fade('in');
	},


	/** Links intro fade in 
	 */
	linksFadeIn: function()
	{
		this.links.fade('in');
	},


	menulangFadeIn: function()
	{
		this.menulang.fade('in');
	},


	/** Show contents in container
	 */
	showContent: function(responseText, responseXML, responseHTML, responseJS) 
	{
		// Hide loader
		if (Browser.Engine.trident != true) {
			this.loaderContainer.retrieve('loader').fireEvent('hide');
		}

		// Content fade in
		this.container.fade('hide');
		
		// Inject HTML
		this.container.set('html', responseHTML);

		// Content fade in
		this.container.fade('in');
		
		// Try to get the slider
		if (this.showSlider)
		{
			this.setSlider();
		}
		
		// Javascript content execution
		$exec(responseJS);

		// After that, modify all the links to call the correct URL
		this.setContentLinks();
	},



	setSlider: function()
	{
		try {
			slider = this.container.getElement('#slider');

			if (slider)
			{
				var rel = slider.getAttribute('rel');
	
				var s = new Slider({container:'slider',nbcol:12,nbrow:1,current_id:rel});
			}
		}
		catch(err)
		{
			if (Browser.Engine.trident)
			{
				if ($('slider'))
				{
					var rel = $('slider').getAttribute('rel');
					var s = new Slider({container:'slider',nbcol:12,nbrow:1,current_id:rel});
				}
			}
		}
	},

	setSwitcher: function(c, t, lc)
	{
		if ($(c))
		{
		
			var sw = new Switcher({
							baseUrl:this.options.baseUrl,
							container:c,
							thumbContainer:t,
							loaderContainer:lc
						});
		}
	},


	setDisplayer: function(c, t, lc)
	{
		if ($(c))
		{
		
			var sw = new Displayer({
							baseUrl:this.options.baseUrl,
							container:c,
							thumbContainer:t,
							loaderContainer:lc
						});
		}
	},
	
	refreshDisplayer: function(e)
	{
		var e = new Event(e);
		e.stop();
		e.stopPropagation();
		
	},


	/** Set the content links
	 *  On A HREF : 	Link to a single page
	 *	On MAP HREF : 	Link to a single article
	 */
	setContentLinks: function()
	{
		// A HREF
		// this._hackLinks($$('#' + this.options.container + ' a'), this.options.baseUrl + 'page/getSingle/');
		
		// collection thumbs & bottom collection link to other article from the same page
		this._hackLinks($$('#' + this.options.container + ' .article-link'), this.options.baseUrl + 'article/getSingle/');
		
		// Product link : e-Shop
		this._hackLinks($$('#' + this.options.container + ' .product-link'), this.options.baseUrl + 'shop/getSingle/product/');
		
	},


	/** Catch the click event on each link from the content div.
	 */
	_hackLinks: function(links, baseurl)
	{
		links.removeEvents();
		
		links.each(function(item, index)
		{
			href =	item.getProperty('href'),
			rel =	item.getProperty('rel');

			var localhost = 'http://localhost/ionize/'; 		// dev

			if (href)
			{
				if (href.indexOf('/') == 0 || href.indexOf(this.options.baseUrl) > -1 || href.indexOf(localhost) > -1 )
				{
					// Get the URL
					var page = 	(href.substring(href.lastIndexOf('/')+1)).replace('.html', '');
					var url = 	baseurl + page;
	
					// Highlight menu item
					var segments = href.replace('.html', '').split('/');
					var id = this.findMenuItemId(segments);
	
	//	this.log('item' + item);
	
					// Click Event on element
					item.addEvent('click', function(evt)
					{
						evt.stop();
						
						// Content fade out
						this.container.fade('out');
	
						// Show spinner
						if (Browser.Engine.trident != true) 
						{
							this.loaderContainer.retrieve('loader').fireEvent('show');
						}
						
						if (id)	
						{
							this.activate(segments);		// Set menu / submenu active
							this.accordion.display(id);		// Toggle the menu item
						}
	
						// Request
						var myRequest = new Request.HTML({
											url:url,
											evalScripts: false,
											onSuccess: this.showContent.bind(this)
										}).send();
					}.bind(this));
	
				}
			}

		}.bind(this));
	},


	/** Find the toggler ID into a URL segment table
	 */
	findMenuItemId: function(segments)
	{
		var menuId = '';
	
		this.togglersLinks.each(function(element, index){
		
			var href = element.getProperty('href');
			var el = (href.substring(href.lastIndexOf('/')+1)).replace('.html', '');

			segments.each(function(segment, index){
				if (segment == el)
				{
					menuId = element.getProperty('rel');
				}
			});
		}.bind(this));

		return menuId;
		
	},


	/** Toggles one accordion menu item
	 */
	menuToggle: function(id)
	{
		this.accordion.display(id);		
	},


	/** Set the class of the current menu / submenu item to "active"
	 */
	activate: function(segments)
	{
		this.togglersLinks.removeClass('active');
		this.elementsLinks.removeClass('active');
	
		// Togglers / Elements check
		var arr = this._getElementsToActivate(segments, this.togglersLinks);
		$$(arr).addClass('active');
		
		arr = (this._getElementsToActivate(segments, this.elementsLinks));
		$$(arr).addClass('active');
	},

	/** Activates the first submenu when the user click on a toogler
	 */
	activateFirstSubmenu: function(id)
	{
		for(var i=0; i < this.elementsLinks.length; i++)
		{
			var rel = this.elementsLinks[i].getProperty('rel');
			if (rel == id)
			{
				this.elementsLinks[i].addClass('active');
				break;
			}	
		}
	},

	/** Activates one menu element.
	 * 	Called by the content page
	 */
	activateElement: function(segment)
	{
		segments = segment.split(',');
		
		arr = (this._getElementsToActivate(segments, this.elementsLinks));
		$$(arr).addClass('active');
	},

	/** Get the element to activate
	 *  used by this.activate()
	 */
	_getElementsToActivate: function(segments, elements)
	{
		var arr = new Array();
		
		elements.each(function(element, index){
		
			var href = element.getProperty('href');
			
			if (href !='')
			{
				var el = (href.substring(href.lastIndexOf('/')+1)).replace('.html', '');
				
				segments.each(function(segment, index){
					if (segment == el)
					{
						arr.push(element);
					}
				});
			}
		}.bind(this));
		return arr;
		
	},


	/** Initialize the home background
	 */
	initBackground: function()
	{
		// Show the picture
		if (this.currentMenuItem == 0)
		{
			// Opera : to get the image size, the image must be showed
			$(this.options.bgContainer).setStyle('display','block');

			this.bgImg =		$(this.options.bgContainer + '-img');
	
			this.imgHeight =	this.bgImg.height;
			this.imgWidth =		this.bgImg.width;
			this.imgRatio =		this.imgWidth / this.imgHeight;

			this.bgContainer.fade('hide');

			// First resize
			this.resizeBackground();
			
			// Window Resize event
			$(window).addEvent('resize', function(evt)
			{
				this.resizeBackground();
			}.bind(this));

			this.showBackground();
		}
	},


	/** Hides the home background picture
	 */ 
	hideBackground: function()
	{
		if ($(this.options.bgContainer).getStyle('display') == 'block')
		{
			$(this.options.bgContainer).fade('out');
		}
	},

	
	/** Shows the home background picture
	 */
	showBackground: function()
	{
		if (!this.bgImg)
		{
			this.initBackground();
		}
		else
		{
			$(this.options.bgContainer).setStyle('display', 'block');

			$(this.options.bgContainer).fade('in');
		}
	},

	/** Resize the background picture
	*/
	resizeBackground:function()
	{
	
		// Get the sizes
		var winSize = $(document.body).getSize();
		var winRatio = winSize.x / winSize.y;
		
		// Set the reference
		var h = this.imgHeight;
		var w = this.imgWidth;
		// var marge = 1 * this.imgRatio;
		var marge = 0;
		var ref = '';
		
		// reference = height
		if (this.imgRatio <= winRatio)
		{	
			ref = ('height');
			var ratio = h / w;
			this.bgImg.width = 	winSize.x + marge;
			this.bgImg.height = this.bgImg.width * ratio + marge;
			
		}
		else
		{
			ref = ('width');
			var ratio = w/h;
			this.bgImg.height = winSize.y + marge;
			this.bgImg.width = 	this.bgImg.height * ratio + marge;
		}
/*
		this.bgContainer.setStyle('height', winSize.y);
		this.bgContainer.setStyle('width', winSize.x);
*/

		this.bgContainer.setStyle('height', this.bgImg.height);
		this.bgContainer.setStyle('width', this.bgImg.width);
		
		// x position : callage droite
		var decalage = this.bgImg.width - winSize.x;
		this.bgContainer.setStyle('left', -decalage); 

	},


	/** Creates the home spinner
	 */
	_loader: function(){
	
	
 		if (this.options.loader === true) 
 			this.options.loader = {};
		var loader = new Element('div', {
			'class': 'loader',				
			'morph': $merge(this.options.loader, {'link': 'cancel'})
		}).store('hidden', false).store('i', 1).inject(this.loaderContainer);
		
		if (this.options.loader.animate){
			for (var i = 0; i < this.options.loader.animate[1]; i++)
				img = new Asset.image(this.options.baseUrl + this.options.loaderUrl + this.options.loader.animate[0].replace(/#/, i));
			if (Browser.Engine.trident && this.options.loader.animate[0].contains('png'))
				loader.setStyle('background-image', 'none');					
		}
		loader.set('events', {
			'animate': function(){  
				var loader = this.loaderContainer.retrieve('loader');				
				var i = (loader.retrieve('i').toInt() + 1) % this.options.loader.animate[1];
				loader.store('i', i);
				var img = this.options.baseUrl + this.options.loaderUrl + this.options.loader.animate[0].replace(/#/, i);
				if (Browser.Engine.trident && this.options.loader.animate[0].contains('png'))
					loader.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img + '", sizingMethod="scale")';
				else 
					loader.setStyle('background-image', 'url(' + img + ')');
			}.bind(this),
			'hide': function(){  
				var loader = this.loaderContainer.retrieve('loader');
				if (!loader.retrieve('hidden')){
					// loader.store('hidden', true).morph('loader-hidden');
					loader.store('hidden', true).fade('out');
					if (this.options.loader.animate)
						$clear(loader.retrieve('timer'));					
				}
			}.bind(this),
			'show': function(){  
				var loader = this.loaderContainer.retrieve('loader');
				if (loader.retrieve('hidden')){
					// loader.store('hidden', false).morph('loader-visible');
					loader.store('hidden', false).fade('in');
					if (this.options.loader.animate)
						loader.store('timer', function(){this.fireEvent('animate');}.periodical(50, loader));
				}
			}.bind(this)
		});
		this.loaderContainer.retrieve('loader', loader).fireEvent('hide');
		
	},



	log: function(key, value, clean, el)
	{
		var el = (el) ? $(el) : $('debug');
		
		if (el) {
		
			if (clean== true)
				el.set('html', key + ':' + '<b>' + value + '</b><br/>');
			else
				el.set('html', el.get('html') + key + ':' + '<b>' + value + '</b><br/>');
		}
	}


});

