/*
Vig27 Javascript Effects Handler Object

This needs to be encapsulated in an object in the future for the final release.

For testing purposes however we will simply include the functions as-is.

*/


/* Base URL of website */

var baseUrl = 'http://vig27-dev.amediacreative.com/';

/*This variable is here to slice the "/vig27/" off of the URL for the menus. Turns out that I can't get rid of the first slash
  very effeciently so this seems a lot faster.
*/

var sliceOffset = 10;

/* Vig27 FX handler. */

var myVigFX;
var shadowBoxInit = false;

/*

class::vigScroller

Scroller class. This handles the scrolling of menus in the Vig site.

Functions:

initialize(), takes no options (now), creates a scroller to use.
destroy(), takes no options, destroys the current scroller

Variables:
mySlide, a pointer to the current scroller object.
myScroll, a pointer to the item to be scrolled.
menuItems, the menuItems element.

*/


var vigScroller = new Class({
    /* Initialize menuItems to be an empty object */
    scrollKnobHeight: 40,
    initialize: function(){
    
        this.menuItems = $('menuItems');
	    this.myScroll = new Fx.Scroll(this.menuItems,{
									  duration:500,
									  transition:Fx.Transitions.linear
									  });
	    /*
	    Reset the scroll handler to the default position on page reload.
	    */
	    this.myScroll.scrollTo(120,0);
	    
	    /* Create the scrollKnob.  */
	    this.scrollKnob = $('scrollKnob'); 
	    
	    /* Create the Knob Scroll scroller effect. */
	    this.knobScroll = new Fx.Style(this.scrollKnob,"top",{
						duration: 500,
						transition:Fx.Transitions.linear
					});
	    
	    /* We could (optionally) and a knob transition here for refresh, but I don't think its warranted/needed. */
	    
	    this.scrollPos = 0;
	    this.knobPos = 0;
        this.scrollInfo = this.menuItems.getSize();
        this.scrollHeight = this.scrollInfo.scrollSize.y;
	    this.scrollBoxHeight = this.scrollInfo.size.y;
	    
	     /*
	    This makes sure that the scrollbar scrolls to the end of the menu and no further,
	    ie, every scroll that the user makes has some visible effect. Give them a little
	    room to breathe. Also make sure that the knob doesn't scroll off the page.
	    */
	    
	    this.relativeEffectHeight = Math.floor(this.scrollHeight - this.scrollBoxHeight + 20);
	    this.scrollBoxHeight = Math.floor(this.scrollBoxHeight - this.scrollKnobHeight); 
	    
	    /* Small hack, here. I'm getting rid of the onTick function, and I'm simply going to use
	       the onComplete function. */
	    this.mySlide = new Slider($('scrollBar'), this.scrollKnob , {
			    mode: 'vertical',
			    steps: 100,
			    wait: true,
			    onComplete: this.slide.bind(this),
			    onTick: Class.empty
			   
		});
    },
    destroy: function(){
        /* Destroy all local variables set in the initialize function */
        delete this.menuItems;
        delete this.myScroll;
        delete this.mySlide.onComplete;
        delete this.mySlide;
        delete this.scrollPos;
        delete this.scrollInfo;
        delete this.scrollBoxHeight;
        delete this.scrollHeight;
        delete this.relativeEffectHeight;
        /* Funny, this works in FX but not IE - delete this; */
    },
    slide: function(pos){
        try{
            this.scrollPos = Math.floor(this.relativeEffectHeight * (pos/100));
            this.knobPos = Math.floor(this.scrollBoxHeight * (pos/100));
            
	        this.myScroll.scrollTo(120,this.scrollPos);
	       
			this.knobScroll.start(this.knobPos);
	        
	    }
	    catch(e){
	        //Try to delete this function reference.
			delete this.mySlide;
	        //delete this;
	    }	
    } 
});

/* This class is meant to manage all of the effects on the Vig. Created for AJAX purposes.*/

var vigFX = new Class({
	photoGallery : Class.empty(),
	lightBox: Class.empty(),
	vigScroller: Class.empty(),
	photoGalleryInitialized: false,
	ajaxMenuInitialized: false,
	frozen: false,
	ajaxArray: [],
	initialize: function(page){
		/* Depending on the page, switch and initialize what is appropriate. */
		//console.trace();
		
		
		/* If this is not the menu or gallery page, initialize the photoGallery */
		if(true){
			
			this.photoGallery = new gallery($('vigGallery'), {
				timed: true,
				showArrows: true,
				showCarousel: false,
				showInfopane: false,
				embedLinks: false,
				delay: 5000
			});
			
			this.photoGalleryInitialized = true;
			
		}
		else{
		    this.photoGalleryInitialized = false;
		}
				
		
		/* Init the scroller on any pages using the AJAX scroller. */
		if(page == 'events'){
			this.vigScroller = new vigScroller();
			this.vigScroller.initialize;
		}
		
		/* If this is the press or gallery page, initialize Lightbox.*/
		//if(page == 'press' || page == 'gallery'){
		
			this.lightBox = new Lightbox();
		//}
		
		/* After everything is done, init the internal AJAX controllers.
		if(page == 'events'){
			this.initMenu(page);
			this.ajaxMenuInitialized = true;
		}
		*/
		/* Create/initialize the "catch" event that delays AJAX loading when OnStart is fired. */
		
		//this.addEvent('onStartChanging',this.freezeAjax);
		
		//this.addEvent('onChanged',this.resumeAjax);
		/* Initialize the top menu. */
		
		this.wakeLinkListeners(page);
	},
	flush: function(){
		/* Destroy all events/handlers. */
		if(this.photoGalleryInitialized){
			
			/* This is redundant but it doesn't seem to be working. */
			this.photoGallery.clearTimer;
			this.photoGallery.timer = $clear(this.photoGallery.timer);
			
			/* Get rid of that function too.. */
			
			//this.photoGallery.nextItem.destroy():
			//this.photoGallery.nextItem = Class.empty();
			
			/* Finally, get rid of the reference itself. */
			//this.photoGallery.destroy();
			this.photoGallery = Class.empty();
		}
		
		if(this.ajaxMenuInitialized){
			this.flushMenu.bind(this)();
			this.vigScroller.destroy();
			this.vigScroller = Class.empty();
			
			this.ajaxMenuInitialized = false;
		}
		
		this.sleepListeners.bind(this)();
		
		//this.removeEvent('onStartChanging', this.freezeAjax);
		//this.removeEvent('onChanged', this.resumeAjax);
		
		this.lightBox = Class.empty();
		
	},
	/** 
		These functions will freeze all the AJAX calls and delay them when onStart is fired.
		
	**/
	freezeAjax: function(){
		this.frozen = true;
	},
	resumeAjax: function(){
		this.frozen = false;
	},
	/**
		function::wakeLinkListener()
		
		This function initializes the AJAX objects for the Vig that pertain to the top menubar.
		
		TEST::Right now this is only going to work for the menu object.
	*/
	wakeLinkListeners: function(page){
		/* This part will grab all menu items, but for now only grabs "Menu". */
		
		
		/* This part will expect a function of the type {NAME}/ajax_{NAME}, where {NAME} is the string predating _link, so in this case it is "menu",
		and it "ajax_menu" to be available as a function in the "menu" controller.
		
		This is only if you use an AJAX function to refresh a Menu Div. */
	
		this.menuListeners = $$('a.ajaxLink');
		
		/* Remove the listener for the currently visited page. This is to prevent unnecessary refreshing. */
		
		this.menuListeners.remove($(page+'_link'));
		//var vigFX = this;
		//var ajaxArray = this.ajaxArray;
		
		this.menuListeners.each(this.setupListeners.bind(this));
	},
	setupListeners: function(menuListener){
	    var id = menuListener.getProperty('id');
		var subPos = id.indexOf('_');
		var thisName = id.slice(0,subPos);
		var myVigFX = this;
		 
		var functionStub = this.getContent.bind(menuListener).pass(myVigFX);
		 //functionStub.ajaxArray = this.ajaxArray;
		 
		 menuListener.addEvent('click',function(event){
		 	/* This should stop the event from firing beyond this item. */
		 	event = new Event(event);
		 	event.stop();
		 	
		 	haltVig(thisName);
		 	functionStub();
		 });
	},
	getContent: function(myVigFX){
	
		var id = this.getProperty('id');
		var subPos = id.indexOf('_');
		var thisName = id.slice(0,subPos);
		
		initVig(thisName);
	},
	/*
		function::sleepListeners()
		
		This function removes all of the event listeners on the page as part of the flush command
		so that the object can be reinstantiated after the AJAX load.
		
		
	*/
	sleepListeners: function(){
		
		this.menuListeners.each(function(menuListener){
			menuListener.removeEvents();
			});
	},
	/*
		function::initMenu()
		
		This function initializes all the links on the menu page and associates them with 
		Ajax objects.

	*/
	initMenu: function(page) {
		
		/* These elements were made stateful so we could get rid of the event listeners  */
		this.largeLinks = $$('p.largeLink');
		this.page = page;
		this.largeLinks.each(this.setupMenu.bind(this));
	},
	/*  function::setupMenu()
	
		 Helper function, this takes each individual
		largeLink and adds an event to it after creating an AJAX class and storing it in the class's array.*/
	setupMenu: function(largeLink){
	
		var myVigFX = this;
		var functionStub = this.callMenu.bind(largeLink).pass(myVigFX);
		
		
		var id = largeLink.getProperty('id');
		var thisName = id+'_menu';
		var url = baseUrl+'application/views/'+this.page+'/'+id+'.menu.html';
		
		this.ajaxArray[thisName] = new Ajax(url, {
			method:'get',
			update:$('menuItems'),
			onComplete: myVigFX.refreshvigScroller.bind(myVigFX),
			evalScripts: false
			});
			
		largeLink.addEvent('click',function(event){
			event = new Event(event);
			event.stop();
			
			functionStub();
			});
		
	},
	/*
		function::callMenu()
		
		This function is used to call/update the menu list.
		
	*/
	callMenu: function(myVigFX){
		
		//var url = location.pathname;
		//var page = url.slice(10);
		
		var id = this.getProperty('id');
		var thisName = id+"_menu";
		
		/* Wax the Vig Scroller, create a new one.  */
		myVigFX.vigScroller.destroy();
		delete myVigFX.vigScroller;
		
		/* If the page doesn't have a menu that can be scrolled, remove the scrollbar. */
		var scrollBar = $('scrollBar');
		
		if( id == "beer" || id == "champagne" || id == "chef" || id == "start"){
			scrollBar.setStyle('display','none');
			scrollBar.setStyle('margin-left','0px');
		}
		else{
			scrollBar.setStyle('display','block');
			scrollBar.setStyle('margin-left','10px');
		}
		
		/* If there is a contact link listener, remove it if the link is not start. */
		
		if(myVigFX.menuListeners.contains($('contact_link_inner')) && id != "start"){
			var removeIndex = myVigFX.menuListeners.indexOf($('contact_link_inner'));
			myVigFX.menuListeners[removeIndex].removeEvents();
			myVigFX.menuListeners.remove($('contact_link_inner'));
		}
		
		/* Update the VigFX Ajax Menu ID*/
		myVigFX.eventMenuID = id;
		
		/* Make the AJAX request. */
		if(myVigFX.frozen == false){
			myVigFX.ajaxArray[thisName].request();
		}
		else{
			myVigFX.ajaxArray[thisName].request.delay(1000);
		}
	},
	/* This helper function flushes out the large links if they are defined.  */
	flushMenu: function(){
		this.largeLinks.each(function(largeLink){
			largeLink.removeEvents();
			});
		
	},
	refreshvigScroller: function(){
	
		/* If the menu is NOT the start menu, remove the event for the contact link and then remove the listener.
			If it is, add the listener for the contact link and add an event. */
			
		if( this.eventMenuID == "start"){
			/* Check to make sure the start menu is not already selected. */
			if(!myVigFX.menuListeners.contains($('contact_link_inner'))){
			
				var menuListener = $('contact_link_inner');
				myVigFX.menuListeners.include(menuListener);
				
				var functionStub = myVigFX.getContent.bind(menuListener).pass(myVigFX);
				
				menuListener.addEvent('click',function(event){
				/* This should stop the event from firing beyond this item. */
					event = new Event(event);
					event.stop();
					
					haltVig(thisName);
					functionStub();
				});
			}
		}
		
		this.vigScroller = new vigScroller();
		this.vigScroller.initialize;
	}
});

/* Implement Events handlers */
		
vigFX.implement(new Events);

/**
function startScroller() {
	var menuItems = $('menuItems');
	var scrollInfo = menuItems.getSize();
	var scrollHandler = new Fx.Scroll(menuItems,{
									  duration:500,
									  transition:Fx.Transitions.linear
									  });
	
	var scrollHeight = scrollInfo.scrollSize.y;
	var scrollBoxHeight = scrollInfo.size.y;

	This makes sure that the scrollbar scrolls to the end of the menu and no further,
	ie, every scroll that the user makes has some visible effect. Give them a little
	room to breathe.

	var relativeEffectHeight = Math.floor(scrollHeight - scrollBoxHeight + 20);
	
	var scrollPos = 0;
	
	Reset the scroll handler to the default position on page reload.
	
	scrollHandler.scrollTo(120,0);
	mySlide = new Slider($('scrollBar'), $('scrollKnob'), {
			mode: 'vertical',
			steps: 100,
			wait: false,
			onComplete: function(pos){
			scrollPos = Math.floor(relativeEffectHeight * (pos/100));
			$('error').setHTML("Pos=" + pos + ", scrollPos = " + scrollPos);
			scrollHandler.scrollTo(120,scrollPos);	
							
			}
		});
}
**/

/*
function::startGallery()

This function starts the rotating image gallery found on the atmosphere page.


function startGallery() {
	var myGallery = new gallery($('vigGallery'), {
		timed: true,
		showArrows: true,
		showCarousel: false,
		embedLinks: false,
		delay: 5000
	});
}
*/


/*
function::profileTips()

This function initializes the profileTips for Vig.

*/
function profileTips() { 
		theseTips =	new Tips($$('.profileElement'),{
			maxTitleChars: 50,
			maxOpacity: .9,
			initialize:function(){
				this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
			},
			onShow: function(toolTip) {
				this.fx.start(1);
			},
			onHide: function(toolTip) {
				this.fx.start(0);
			}
		});
}

/*
function::initVig()

This function initializes all of the JS on the Vig site.
*/
	
function initVig(page){
	
	//startGallery();
	
	profileTips();
	
	/** This part is commented out until I figure out how exactly Joey wants this stuff to display -Stew
	
	var content_id = page+'_stock';
	var content = $(content_id);
	
	content.addClass("center_deck");
	content.removeClass("center_out");
	
	var fadeIn = new Fx.Style(content,'opacity',{
			duration:900,
			wait:false,
			transition: Fx.Transitions.Quad.easeOut
			});
	
	/* If the page has a gallery, get it. 
	
	if(page != 'menu' && page != 'gallery'){
		vigGallery = $E(".vigGallery",content_id);
		vigGallery.setProperty('id','vigGallery');
	}
		*/
		
	myVigFX = new vigFX(page);
			
	//fadeIn.start(0,1);
	
}

/*
	function::haltVig()
	
	This function halts all of the JS on the Vig site. Used for AJAX.
*/

function haltVig(page){

	/* Fade out the old div. */
	myVigFX.flush();
	
	/* If there is a vigGallery, find it and remove. */
	
	vigGallery = $('vigGallery');
	
	if(vigGallery){
		vigGallery.removeProperty('id');
		
		/* Remove the loading elements and the left/right click elements. */
		
		var loadingElement = $E(".loadingElement",vigGallery);
		var slideInfoZone = $E(".slideInfoZone",vigGallery);
		var aLeft = $E(".left",vigGallery);
		var aRight = $E(".right",vigGallery);
		
		loadingElement.remove();
		slideInfoZone.remove();
		aLeft.remove();
		aRight.remove();
		
		/* Reset all the children of vigGallery to be of class imageElement and 
		remove their style properties.*/
		var oldSlideInfo = $ES(".imageInfo",vigGallery);
		var oldSlideElements = $ES(".slideElement",vigGallery);
		oldSlideElements.each(function(slideElement,index){
			
			/* Strip the old properties */
			slideElement.removeClass("slideElement");
			
			/* Set up the variables for recreating the DOM "as was left". */
			
			var url = oldSlideInfo[index].getText();
			var header = new Element('h3');
			var img = new Element('img',{
								  'class':'full',
								  'width':900,
								  'height':500,
								  'src':url
								  });
			var arbitraryP = new Element('p');
			
			var numberPos = url.indexOf("img");
			var jpegPos = url.indexOf(".jpg");
			
			var number = url.slice(numberPos+3,jpegPos);
			
			/* Reconstruct the DOM. */
			
			header.setHTML('Image'+number);
			
			header.injectInside(slideElement);
			arbitraryP.injectInside(slideElement);
			img.injectInside(slideElement);
			
			
			slideElement.addClass("imageElement");
			slideElement.removeProperty("style");
		});
		
		
	}
	
	/* If there is a lightbox Gallery, find it and remove. */
	
	var lightboxOverlay = $('lbOverlay');
	
	if(lightboxOverlay){
		var removeLightboxes = $$('#lbOverlay','#lbCenter','#lbBottomContainer');
		removeLightboxes.each(function(removeLightbox){
			removeLightbox.remove();
		});
	}

	var content = $E(".center_deck","center");
	
	var fadeOut = new Fx.Style(content,'opacity',{
		duration:900,
		wait:false,
		transition: Fx.Transitions.Quad.easeOut
	});
			
	fadeOut.start(1,0);
	
	content.addClass("center_out");
	content.removeClass("center_deck");
		
	content.removeProperty("style");
		
}

function initializeOnce(){
	
	/* Initialize shadowbox.*/

	var shadowOptions = {
		assetUrl:			baseUrl,
		resizeLgImages:		false,
		handleUnsupported:  'remove',
		type:				'html',
		keysClose:			['c',27]
	}
	
	Shadowbox.init(shadowOptions);

}

/* Hides everything except for the grey center box and the loading image while the preloader is doing its thing. */
	
function hideBody(){
	var main = $$('#top','#top_bg');
	var body = $E('body');
	body.setStyle('background','#010101');
	
	main.setStyle('overflow','hidden');
	main.setStyle('opacity','0');
	
	var loadingBox = new Element('div',{id: 'loadingBox'});
	
	loadingBox.injectInside($('center'));
	loadingBox.setHTML('<img src="'+baseUrl+'images/main/loading.gif" alt="Please wait- Vig27 is loading.."><br/>');
	/*
	This doesn't work because lightbox is gay
	Lightbox.show( baseUrl + 'images/main/logo.png','Please stand by - Vig27 is now loading.');
	*/
}

/* Shows the body and activates the images, Ajax, and profile tips after
	the page is done loading */
function showBody(page){
	
	var main = $$('#top','#top_bg');
	main.setStyle('overflow','visible');
	main.setStyle('visibility','visible');
	
	var body = $E('body');
	body.setStyle('background','');
	var loadingBox = $('loadingBox');
	
	var flowImgOut = new Fx.Style(loadingBox, 'opacity', {duration:500});
	flowImgOut.start(1,0);
	
	loadingBox.remove();
	
	var flowMainOn = new Fx.Elements(main,{
		duration: 500
	});
	
	var flowOnOptions = {
		'opacity':[0,1]
	};
	
	flowMainOn.start({
		'0': flowOnOptions,
		'1': flowOnOptions
	});

	/*
	This doesn't work because lightbox is gay
	Lightbox.close();
	*/
	
	initVig(page);
	
}








/*
|--------------------------------------------------------------------------
| AMEDIA CREATIVE FRONTEND FRAMEWORK > LIGHTBOX
|--------------------------------------------------------------------------
|
*/

	/**
	* Function to call the lightbox.
	* Usually you might want to embed this directly in the href of an a tag.
	*
	* @name 	Call Lightbox
	* @access 	public
	* @param 	var-type none
	* @return 	none
	* @author 	Joey Avino
	* @email	javino@gabriels.net
	*/
	function call_lightbox() {

		/**
		* How to use the variables.
		*
		* function			init_tabs(_event, _tabs, _pages, _default);
		*
		* _obj 				This is the ID of your lightbox that will be displayed.
		* _overlay 			This is the the ID of your overlay.
		* _duration 		How long would you like it to fade in? 0 for instant.
		* _opacity 			Will make the overlay transparent on a scale from 0 to 1.
		*
		* NOTE:				You can use one overlay for multiple lightboxes.
		*/
		var _obj = '#menu_lightbox';
		var _overlay  = '#lightbox_overlay';
		var _duration = 200;
		var _opacity = .8; 

		display_lightbox(_obj, _overlay, _duration, _opacity);

	}

	/**
	* Function to hide the lightbox.
	* Usually you might want to embed this directly in the href of an a tag.
	*
	* @name 	Hide Lightbox
	* @access 	public
	* @param 	var-type none
	* @return 	none
	* @author 	Joey Avino
	* @email	javino@gabriels.net
	*/
	function lightbox_hidden() {

		var _obj = '#menu_lightbox';
		var _overlay  = '#lightbox_overlay';
		var _duration = 200;

		close_lightbox(_obj, _overlay, _duration);

	}
