/**
 *	Lightbox Classes
 *	For the Creation Flow for SympathyTree
 **/
var templateLightboxClass = Class.create();
templateLightboxClass.prototype = {
	//holds the dialog object for futher use
	templateDialogObj: 	null,
	//the left arrow node
	leftArrow: 			null,
	//the right arrow node
	rightArrow: 		null,
	
	//constructor
	initialize: function(el, settings) {
		if(!this.n) {this.n = {};}

		// initialize nodes
		Object.extend(this.n, {
			el: el,
			templates: $(el).getElementsByClassName('template_lightbox'),
			dialogContent: null
			/* put extensions to nodes here */
		});

		this._attachEvents();
	},
	
	/**
	 * attach event handlers to the select drop down field
	 * on change and on keyup. Use appearing effect (true)
	 * 
	 * @author tthederan 2008-02-26
	 */
	_attachEvents : function() {
		for(var i = 0; i < this.n.templates.length; i++)
		{
			Element.observe(this.n.templates[i], 'click', this.popup.bind(this, this.n.templates[i]));
		}
	},
	
	/**
	 * Popup Action
	 * creates the light box and adds left and right observers
	 */
	popup: function(el, e) {
		e.stop();
		//google tracker
		if(pageTracker && typeof el.title == 'string')
		{
			var imgTitle = el.title != '' ? el.title : 'notitle'; 
			if (el.title == 'Classic' || el.title == 'Contemporary' || el.title == 'Casual' || el.title == 'Modern' || el.title == 'Scrapbook') {
				pageTracker._trackPageview('/lightboxpopup/template/'+imgTitle);
//				console.log('/lightboxpopup/template/'+imgTitle);
			}
			else {
				pageTracker._trackPageview('/lightboxpopup/userphoto/'+imgTitle);
//				console.log('/lightboxpopup/userphoto/'+imgTitle);
			}
		}
		//lets get the html for the box
		this.n.dialogContent = this.createBody(el);
		
		//lets create the lb object
		this.templateDialogObj = new SS.widgets.Dialog({
			s: {
				content:	this.n.dialogContent,
				resizeable: false,
				draggable: false,
				className: 'dialogBox image_viewer',
				exemplarAnchor: 'center center',
				selfAnchor: 'center center'
			}
		});
		
		//lets listen to the left arrow
		Element.observe(this.leftArrow, 'click', this.swap.bind(this, 'lightbox_left_arrow_'));
		
		//lets listen to the right arrow
		Element.observe(this.rightArrow, 'click', this.swap.bind(this, 'lightbox_right_arrow_'));
		
	},
	
	createLoader: function(el) {
		var divNode = document.createElement('div');
		divNode.id = 'throbbloadingmodal';
		divNode.style.position = 'absolute';
		divNode.style.top = '0';
		divNode.style.left = '0';
		divNode.style.width = '100%';
		divNode.style.height = '100%';
		divNode.style.background = '#FFF';
		divNode.style.zIndex = '1000';
		divNode.style.opacity = '.4';
		divNode.style.filter = 'alpha(opacity=40)';
		el.appendChild(divNode);
		
		var img = document.createElement('img');
		img.id = 'throbbloadingimage';
		img.style.position = 'absolute';
		img.style.top = '50%';
		img.style.left = '30%';
		divNode.style.zIndex = '1001';
		img.src = '/themes/newbase/i/throbber.gif';
		el.appendChild(img);
		
	},
	
	destroyLoader: function() {
		var loader = document.getElementById('throbbloadingmodal');
		if(loader)
		{
			Element.remove(loader);
		}
		var loader = document.getElementById('throbbloadingimage');
		if(loader)
		{
			Element.remove(loader);
		}
	},
	
	swap: function(replaceId) {
		Element.stopObserving(this.leftArrow, 'click', this.swap.bind(this, 'lightbox_left_arrow_'));
		Element.stopObserving(this.rightArrow, 'click', this.swap.bind(this, 'lightbox_right_arrow_'));
		var thumb = replaceId.indexOf('left') == -1 ? $(this.rightArrow.id.replace(replaceId,'thumb_')) : $(this.leftArrow.id.replace(replaceId,'thumb_'));
		var temp = this.createBody(thumb); //this.updateBody(thumb);
		this.n.dialogContent.parentNode.update(temp);
		this.n.dialogContent = temp;
		
		this.n.dialogContent.select('a.close')[0].observe('click', this.templateDialogObj.onCloseClick.bind(this.templateDialogObj));

		//lets listen to the left arrow
		Element.observe(this.leftArrow, 'click', this.swap.bind(this, 'lightbox_left_arrow_'));
		
		//lets listen to the right arrow
		Element.observe(this.rightArrow, 'click', this.swap.bind(this, 'lightbox_right_arrow_'));
	},
	
	/**
	 * Create Body
	 * if the image was clicked from the initial screen lets create the body of the lightbox
	 */
	createBody: function(el) {
		//lets get the new id
		var thumbItem = parseInt(el.id.replace('thumb_', ''), 10), totalThumbs = this.n.templates.length;
		
		//lets build the dom and get this out of the way
		var content = new Element('div');
		content.addClassName('content');
		var dialogHead = new Element('div');
		dialogHead.addClassName('header');
		var dialogBody = new Element('div');
		dialogBody.addClassName('body');
		var closeControl = new Element('a');
		closeControl.addClassName('close');
		var pagination = new Element('div');
		pagination.addClassName('pagination');
		var text = new Element('div');
		text.addClassName('content');
		var title = new Element('h2');
		var description = new Element('p');
		
		//lets recreate the left arrow
		//TODO we should store this in a global class var
		this.leftArrow = new Element('a');
		this.leftArrow.addClassName('lightbox_left_arrow');
		this.leftArrow.id = 'lightbox_left_arrow_'+(thumbItem-1);
		this.leftArrow.innerHTML = '<--';
		pagination.appendChild(this.leftArrow);
		
		//lets create a pagination element
		var center = new Element('span');
		center.innerHTML = thumbItem+' of '+totalThumbs;
		pagination.appendChild(center);
		
		//lets recreate the right arrow
		//TODO we should store this in a global class var
		this.rightArrow = new Element('a');
		this.rightArrow.id = 'lightbox_right_arrow_'+(thumbItem+1);
		this.rightArrow.addClassName('lightbox_right_arrow');
		this.rightArrow.innerHTML = '-->';
		pagination.appendChild(this.rightArrow);
		
		//should we sho the left arrow?
		if(!(thumbItem > 1))
		{
			this.leftArrow.style.display = 'none';
		}
		
		//should we show the right arrow?
		if(!(thumbItem < totalThumbs))
		{
			this.rightArrow.style.display = 'none';
		}
		
		//lets set close el
		dialogHead.appendChild(title);
		closeControl.innerHTML = 'Close';
		dialogHead.appendChild(closeControl);
		
		//lets set the title el
		title.innerHTML = el.title; //alert($(el).inspect());
		description.innerHTML = $(el).select('img')[0].alt;
		
		
		//text.appendChild(description);fullimagepopup
		//if the image breaks the box width of 600 lets resize the image so it doesn't
		var hrefArray = el.href.split('/');
		if(el.hasClassName('x_large'))
		{
			hrefArray.push(hrefArray[hrefArray.length-1]);
			hrefArray[hrefArray.length-2] = 'fullimagepopup';
		}
		
		
		
		var imgPreloader = new Image();
        imgPreloader.onload = (function(){
			//lets set the src to the image loc
			var imgNode = new Element('img', {src:hrefArray.join('/'), title:$(el).select('img')[0].alt});	
			dialogBody.appendChild(imgNode);
            dialogBody.appendChild(pagination);
        }).bind(this);
        imgPreloader.src = hrefArray.join('/');
		//imgNode.observe('load', function(){dialogBody.appendChild(pagination);});
		
		//dialogBody.appendChild(text);
		
		content.appendChild(dialogHead);
		content.appendChild(dialogBody);
		return content;
	}
}

/**
 *	Preview Class
 *	For the Creation Flow for SympathyTree
 *	TODO Separate this class into another file
 **
var previewFormClass2 = Class.create();
previewFormClass2.prototype = {
	//constructor
	initialize: function(el, settings) {
		if(!this.n) {this.n = {};}
		this.clicked = false;
		this.frameInitLoaded = true;
		// initialize nodes
		Object.extend(this.n, {
			el: el
			/* put extensions to nodes here *
		});
		this.dialogObj = null;
		
		this._attachEvents();
	},
	
	/**
	 * attach event handlers to the select drop down field
	 * on change and on keyup. Use appearing effect (true)
	 * 
	 * @author tthederan 2008-02-26
	 *
	_attachEvents : function() {
		$(this.n.el).observe('click', this.processAndSubmit.bindAsEventListener(this));
	},
	
	/**
	 *	Process and Submit
	 *	If the butto has been clicked lets emulate a submit and then open up the preview url
	 *
	processAndSubmit: function(e) {
		e.stop();
		this.clicked = true;
		//lets find the overall form
		// hopefully there is only one on this page
		var form = this.findForm();
		if(this.findForm != null)
		{
			//lets create the lightbox
			this.dialogObj = new SS.widgets.Dialog({
				s: {
					content:	'<div class="header" style="margin:auto;"><a href="" class="close">X</a>Preview Form</div>'+
								'<div class="content" align="center"><img style="margin-top:200px;" src="/i/loading.gif" /></div>',
					resizeable: false,
					draggable: false,
					className: 'dialogBox previewBox',
					exemplarAnchor: 'center center',
					selfAnchor: 'center center'
				}
			});
			this.dialogObj.n.el.style.position = 'absolute';
			//submit the form
			
			//there is a FCK Editor flaw that doesnt send it's info on preview
			//lets force this out
			if(typeof(FCKeditorAPI) != 'undefined')
			{
				$('memorialtext').value = FCKeditorAPI.GetInstance('memorialtext').GetXHTML();
			}
			
			//lets emulate the submit
			$(form).request({
							parameters: {preview: 'Preview', preview_x: 'Preview'},
							onComplete: this.loadDialog.bindAsEventListener(this)});
			
			
		}
	},
	
	/**
	 *	Load Dialog
	 *	if the lightbox needs to be updated for some reason lets do it
	 *
	loadDialog: function()
	{
		if(this.dialogObj != null)
		{
			this.dialogObj.loadIFrameURL(this.n.el.value, 'previewIFrame', true);
			Event.observe('previewIFrame','load', function(e){	
				//we are going foward in history
				if(this.clicked)
				{
					this.clicked = false;
				}
				//we are going backward in history
				else if(!this.frameInitLoaded)
				{
					setTimeout(function(){
						this.dialogObj.hide();
						//lets destroy
						this.dialogObj.n.el.remove();
						this.dialogObj = null;
					}.bind(this),0);
					
				}

				else
				{
					//lets do nothing but 
					//allow a popup to be removed the next time
					this.frameInitLoaded = false;
				}
			}.bind(this));
		}
	},
	
	/**
	 *	Find Form
	 *	lets parse up the DOM looking for the first form
	 *	NOTE Does this abaility exist in prototype?
	 *
	findForm: function()
	{
		var parent = this.n.el;
		while(parent.tagName.toLowerCase() != 'body')
		{
			if(parent.tagName.toLowerCase() == 'form')
			{
				return parent;
			}
			parent = parent.parentNode;
	  	}
	  	return null;
	}
}*/


/**
 *	Preview Class
 *	For the Creation Flow for SympathyTree
 *	TODO Separate this class into another file
 **/
var previewFormClass = Class.create();
previewFormClass.prototype = {
	//constructor
	initialize: function(el, settings) {
		if(!this.n) {this.n = {};}

		// initialize nodes
		Object.extend(this.n, {
			el: el
			/* put extensions to nodes here */
		});
		this.dialogObj = null;
		
		//register
		YAHOO.util.History.register('popups', YAHOO.util.History.getBookmarkedState('popups') || 'load', function (state) { 
				// Load the appropriate section: 
				this.loadPopup(state); 
		}.bind(this)); 
		
		this._attachEvents();
		
		//whenever the browser us ready 
		YAHOO.util.History.onReady(function () { 
			this.loadPopup(YAHOO.util.History.getCurrentState('popups')); 
		}.bind(this)); 
		
		// Initialize the browser history management library.
		try {
			YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		} catch (e) {
			// The only exception that gets thrown here is when the browser is
			// not supported (Opera, or not A-grade) Degrade gracefully.
			// Note that we have two options here to degrade gracefully:
			//   1) Call initializeNavigationBar. The page will use Ajax/DHTML,
			//      but the back/forward buttons will not work.
			//   2) Initialize our module. The page will not use Ajax/DHTML,
			//      but the back/forward buttons will work. This is what we
			//      chose to do here:
			this.loadPopup(YAHOO.util.History.getBookmarkedState('popups') || 'load');
		}
	},
	
	loadPopup: function(state) {
		if(this.dialogObj)
		{
			var e;
			//lets generate an event obj
			if(typeof document.createEventObject != 'undefined')
			{ 
				e = document.createEventObject();
			}
			else
			{
				e = document.createEvent("HTMLEvents");
			}
			this.dialogObj.onCloseClick(e);
			this.dialogObj = null;
		}
		if(state == 'popup')
		{
			//lets find the overall form
			// hopefully there is only one on this page
			var form = this.findForm();
			if(this.findForm != null)
			{
				//lets create the lightbox
				this.dialogObj = new SS.widgets.Dialog({
					s: {
						content:	'<div class="header" style="margin:auto;"><a href="" class="close">Close</a>Preview Form</div>'+
									'<div class="content" align="center"><img style="margin-top:200px;" src="/i/loading.gif" /></div>',
						resizeable: false,
						draggable: false,
						className: 'dialogBox previewBox',
						exemplarAnchor: 'center center',
						selfAnchor: 'center center'
					}
				});
				this.dialogObj.n.closes.each(function(el) {
					el.observe('click', this.onCloseClick.bindAsEventListener(this));
				}.bind(this));
				if(this.dialogObj.s.closeOnOverlayClick)
				{
					$(this.dialogObj.overlay.n.background).observe('click', this.onCloseOverlayClick.bindAsEventListener(this));
				}
				
				
				this.dialogObj.n.el.style.position = 'absolute';
				//submit the form
				
				//there is a FCK Editor flaw that doesnt send it's info on preview
				//lets force this out
				if(typeof(FCKeditorAPI) != 'undefined')
				{
					$('memorialtext').value = FCKeditorAPI.GetInstance('memorialtext').GetXHTML();
				}
				
				//lets emulate the submit
				$(form).request({
								parameters: {preview: 'Preview', preview_x: 'Preview'},
								onComplete: this.loadDialog.bindAsEventListener(this)});
				
				
			}
		}
	},
	
	onCloseClick: function(e){
		e.stop();
		try { 
			YAHOO.util.History.navigate('popups', 'load'); 
		} catch (e) { 
			this.loadPopup('load'); 
		}
	},
			
	onCloseOverlayClick: function(e){
		e.stop();
		try { 
			YAHOO.util.History.navigate('popups', 'load'); 
		} catch (e) { 
			this.loadPopup('load'); 
		}
		
	},
	
	/**
	 * attach event handlers to the select drop down field
	 * on change and on keyup. Use appearing effect (true)
	 * 
	 * @author tthederan 2008-02-26
	 */
	_attachEvents : function() {
		$(this.n.el).observe('click', this.processAndSubmit.bindAsEventListener(this));
	},
	
	/**
	 *	Process and Submit
	 *	If the butto has been clicked lets emulate a submit and then open up the preview url
	 */
	processAndSubmit: function(e) {
		e.stop();
		try { 
			YAHOO.util.History.navigate('popups', 'popup'); 
		} catch (e) { 
			this.loadPopup('popup'); 
		}
	},
	
	/**
	 *	Load Dialog
	 *	if the lightbox needs to be updated for some reason lets do it
	 */
	loadDialog: function()
	{
		if(this.dialogObj != null)
		{
			this.dialogObj.loadIFrameURL(this.n.el.value);
		}
	},
	
	/**
	 *	Find Form
	 *	lets parse up the DOM looking for the first form
	 *	NOTE Does this abaility exist in prototype?
	 */
	findForm: function()
	{
		var parent = this.n.el;
		while(parent.tagName.toLowerCase() != 'body')
		{
			if(parent.tagName.toLowerCase() == 'form')
			{
				return parent;
			}
			parent = parent.parentNode;
	  	}
	  	return null;
	}
}

var popupClass = Class.create();
popupClass.prototype = {
	//placeholder for dialog object
	dialogObj: null,
	
	/**
	 * Constructor
	 **/
	initialize: function(el) {
		this.el = el;
		
		//register
		/*YAHOO.util.History.register('popups', YAHOO.util.History.getBookmarkedState('popups') || 'load', function (state) { 
				// Load the appropriate section: 
				this.loadPopup(state); 
		}.bind(this)); */
		
		$(el).observe('click', function(e){
			e.stop();
			var question = $(this.el).select('span')[0] || 'Help';
			question = question.innerHTML || 'Help';
			var answer = $(this.el).select('span')[1] || '';
			answer = answer.innerHTML || '';
			
			if(answer == '')
			{
				window.location = el.href;
			}
			else
			{
				this.dialogObj = new SS.widgets.Dialog({
					s: {
						content:	'<div class="header" style="margin:auto;"><a href="" class="close">Close </a>'+question+'</div>'+
									'<div class="content">'+answer+'</div>',
						resizeable: false,
						draggable: false,
						className: 'dialogBox help',
						exemplarAnchor: 'center center',
						selfAnchor: 'center center'
					}
				});
			}
			/*try { 
				YAHOO.util.History.navigate('popups', 'popup'); 
			} catch (e) { 
				this.loadPopup('popup'); 
			}*/
		}.bind(this));
		/*
		//whenever the browser us ready 
		YAHOO.util.History.onReady(function () { 
			this.loadPopup(YAHOO.util.History.getCurrentState('popups')); 
		}.bind(this)); 
		
		// Initialize the browser history management library.
		try {
			//YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		} catch (e) {
			// The only exception that gets thrown here is when the browser is
			// not supported (Opera, or not A-grade) Degrade gracefully.
			// Note that we have two options here to degrade gracefully:
			//   1) Call initializeNavigationBar. The page will use Ajax/DHTML,
			//      but the back/forward buttons will not work.
			//   2) Initialize our module. The page will not use Ajax/DHTML,
			//      but the back/forward buttons will work. This is what we
			//      chose to do here:
			this.loadPopup(YAHOO.util.History.getBookmarkedState('popups') || 'load');
		}*/
	},
	loadPopup: function(state) {
		if(state == 'popup')
		{
			var question = $(this.el).select('span')[0] || 'Help';
			question = question.innerHTML || 'Help';
			var answer = $(this.el).select('span')[1] || '';
			answer = answer.innerHTML || '';
			
			if(answer == '')
			{
				window.location = el.href;
			}
			else
			{
				this.dialogObj = new SS.widgets.Dialog({
					s: {
						content:	'<div class="header" style="margin:auto;"><a href="" class="close">Close </a>'+question+'</div>'+
									'<div class="content">'+answer+'</div>',
						resizeable: false,
						draggable: false,
						className: 'dialogBox help',
						exemplarAnchor: 'center center',
						selfAnchor: 'center center'
					}
				});
			}
		}
		else
		{
			if(this.dialogObj)
			{
				this.dialogObj.hide();
				//lets destroy
				this.dialogObj.n.el.remove();
				this.dialogObj = null;
			}
		}
	}
};


var tourClass = Class.create();
tourClass.prototype = {
	//placeholder for dialog object
	dialogObj: null,
	
	/**
	 * Constructor
	 **/
	initialize: function(el) {
		this.el = el;
		
		$(el).observe('click', function(e){
			e.stop();
			var largeImg = $(this.el).select('span')[0] || '';
			largeImg = largeImg.innerHTML || '';
			var title = $(this.el).select('span')[1] || '';
			title = title.innerHTML || '';
				this.dialogObj = new SS.widgets.Dialog({
					s: {
						content:	'<div class="header" style="margin:auto;"><a href="" class="close">Close </a>' + title + '</div>'+
									'<div class="content"><img src="'+largeImg+'" alt="large view"/></div>',
						resizeable: false,
						draggable: false,
						className: 'dialogBox image_viewer',
						exemplarAnchor: 'center center',
						selfAnchor: 'center center'
					}
				});
				
		}.bind(this));
		
	}
};


//the big event selector
EventSelectors.register({
	//for create Template
	'#templates': function(el){
		new templateLightboxClass(el);
	},
	
	//for preview in the create flow
	'#preview': function(el) {
		//lets build out what yui requires
		if(document.getElementById('yui-history-iframe') == null)
		{
			document.body.appendChild(new Element('iframe', {id:'yui-history-iframe', style:'display:none;'}));
		}
		if(document.getElementById('yui-history-field') == null)
		{
			document.body.appendChild(new Element('input', {id:'yui-history-field', type:'hidden'}));
		}
		new previewFormClass(el);
	},
	
	//for the front memorial view home page
	//Note we should separate this into another file
	'#slider_center': function(el){
		new templateLightboxClass(el);
	},
	
	//for create Galleries
	'#gallery': function(el){
		new templateLightboxClass(el);
	},
	
	//for the front memorial view home page
	//Note we should separate this into another file
	'a.share' : function(el) {
		$(el).observe('click', function(e){
			e.stop();
			var dialogObj = new SS.widgets.Dialog({
				s: {
					content:	'<div class="header" style="margin:auto;"><a href="" class="close">Close </a>Share this memorial with a friend</div>'+
								'<div class="content">Dialog Content</div>',
					resizeable: false,
					draggable: false,
					className: 'dialogBox popup_module',
					exemplarAnchor: 'center center',
					selfAnchor: 'center center'
				}
			});
			var classNames = el.className.split(' ');
			for(var i in classNames)
			{
				if(typeof(classNames[i]) == 'string' && classNames[i].indexOf('__popup') != -1)
				{ 
					dialogObj.loadURL('/?'+classNames[i]);
					return;
				}
			}
			//dialogObj.loadURL(el.value);
		});
	},//expression(\'document.body.clientHeight > 200 ? "200px" : "100%"; \')
	
	//for the memorial billing page
	//Note we should separate this into another file
	'a.print' : function(el) {
		$(el).observe('click', function(e){
			e.stop();
			window.open(el.href,'Print','width=500,height=400,scrollbars=yes,resizable=yes,menubar=yes,location=no');
		});
	},//expression(\'document.body.clientHeight > 200 ? "200px" : "100%"; \')
	
	//this is for the creation/edit flow
	'.help_popup a': function(el) {
		if($(el).hasClassName('no_pop'))
		{
			return;
		}
		
		//call the class
		new popupClass(el);
	},
	
	//this is for the tour pages
	'.tour a.view': function(el) {		
		//call the class
		new tourClass(el);
	}
}, false);

