/*
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://www.vig27.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.
*/

/* 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: $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({
	photoGalleryInitialized: false,
	ajaxMenuInitialized: false,
	frozen: false,
	ajaxArray: [],
	initialize: function(page){
		/* Depending on the page, switch and initialize what is appropriate. */
		
		
		/* If this is not the menu or gallery page, initialize the photoGallery */
		if(true){
					
			/** Initialize the slideshow if this is the gallery page. **/
			
			var data = [
				'pics/slideshow/img1.jpg' ,  
				'pics/slideshow/img2.jpg' ,
				'pics/slideshow/img3.jpg' ,
				'pics/slideshow/img4.jpg' ,
				'pics/slideshow/img5.jpg' ,
				'pics/slideshow/img6.jpg' ,
				'pics/slideshow/img7.jpg' ,
				'pics/slideshow/img8.jpg' ,
				'pics/slideshow/img9.jpg' 
				];
					
		}
		
		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;
		}
		
	},
	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);
			
			/* Finally, get rid of the reference itself. */
			this.photoGallery = $empty;
		}
		
		if(this.ajaxMenuInitialized){
			this.flushMenu.bind(this)();
			this.vigScroller.destroy();
			this.vigScroller = $empty;
			
			this.ajaxMenuInitialized = false;
		}
		
		this.lightBox = $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){

	},
	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 profileTips() { 
	if($('menu')){
		
	}
	else{
		if ($$('.profileElement').length > 0) {
			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){
	
	profileTips();
		
	myVigFX = new vigFX(page);
			
}

/*
	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:				'',
		player:				'iframe',
		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/>');
	
}

/* 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
	});
	
	initVig(page);
	
}











