CHINET.namespace("AYB.ui.global");

CHINET.AYB.ui.global.BaseBox = new Class({
    Implements: [Options, Events],
    options: {
		CLASSES: {
			applyWhenTooltip: 'basebox-tooltip',
			closeButton: 'basebox-close'
		},
		SELECTORS: {
			autoClick: '.basebox',
			autoForm: '.basebox-form',
			autoTooltip: '.basebox-tooltip'
		},
		IDS: {
			contentWrapper: 'basebox-wrapper',
			contentContainer: 'basebox-container',
			underlay: 'basebox-underlay'
		},
		contentWrapperStyles: {
			opacity: 0,
			zIndex: 999999
		},
		contentContainerStyles: {},
		underlayStyles: {
			backgroundColor: '#FFFFFF',
			display: 'none',
			opacity: 0.5,
			width: '100%',
			zIndex: 999998
		},
		hideDelay: 500,
		imageExtensions: ['jpg','jpeg','gif','png']
    },
	underlay: null,
	contentWrapper: null,
	contentContainer: null,
	autoButtons: [],
	autoTooltips: [],
	hideTimeout: null,
	underlayShim: null,
	wrapperShim: null,
	
	_TooltipTrigger: false,
	
    initialize: function(options) {
        this.setOptions(options);
        this.findElements();
        this.addListeners();
        this.prepareBody();
    },

    findElements: function() {
    	this.underlay = $(this.options.IDS.underlay);
		this.contentWrapper = $(this.options.IDS.contentWrapper);
    	this.contentContainer = $(this.options.IDS.contentContainer);
    	//this.autoButtons = $$(this.options.SELECTORS.autoClick);
    	this.autoTooltips = $$(this.options.SELECTORS.autoTooltip);
		this.resetFrame();
		this.addShims();
    },
    addListeners: function() {
    	if (this.underlay) {
    		this.underlay.removeEvents('click').addEvent('click', this.hide.bindWithEvent(this));
    	}
    	if (this.contentWrapper) {
    		this.contentWrapper.removeEvents('mouseenter');
    		this.contentWrapper.removeEvents('mouseleave');
    		this.contentWrapper.addEvent('mouseenter', this.handleBoxMouseEnter.bindWithEvent(this));
    		this.contentWrapper.addEvent('mouseleave', this.handleMouseLeave.bindWithEvent(this));
    	}
    	//this.autoButtons.addEvent('click', this.handleAutoClick.bindWithEvent(this));
    	this.autoTooltips.removeEvents('mouseenter');
    	this.autoTooltips.removeEvents('mouseleave');
    	this.autoTooltips.addEvent('mouseenter', this.handleAutoMouseEnter.bindWithEvent(this));
    	this.autoTooltips.addEvent('mouseleave', this.handleMouseLeave.bindWithEvent(this));
    	window.addEvent('resize', this.setUnderlayHeight.bind(this));
    },
    prepareBody: function() {
    	$$('html, body').setStyle('height', '100%');
    },
    
    handleAutoClick: function(evt) {
    	if($(evt.target).get('tag') != 'a') {
    		evt.target = $(evt.target).getParent('a');
    	}
    	evt.preventDefault();
		this.resetFrame();
    	this.showXhr($(evt.target).get('href'));
    },
	handleAutoForm: function(evt) {
		evt.preventDefault();
		$(evt.target).set('send', {
				url: $(evt.target).get('action') + '/xhr:1', 
				onSuccess: this.handleXhrSuccess.bind(this),
				evalScripts: true
		});
		$(evt.target).send();
	},
    
    handleAutoMouseEnter: function(evt) {
    	evt.target = $(evt.target);
		this.showTooltip(evt.target.get('rel'), evt.target);
    },
    
    handleBoxMouseEnter: function(evt) {
    	this.hideTimeout = $clear(this.hideTimeout);
    },
    
    handleMouseLeave: function(evt) {
    	if (this._TooltipTrigger) {
    		this.hideTimeout = this.hide.delay(this.options.hideDelay, this);
    	}
    },
	
    showMarkup: function(markup) {
		if (!markup) { return false; }
		this.resetFrame();
		this._TooltipTrigger = false;
		
		switch ($type(markup)) {
		case 'string':
			this.contentContainer.set('html', markup);
			break;
		case 'element':
			this.contentContainer.empty();
			this.contentContainer.adopt($(markup).clone().setStyle('display', 'block'));
			break;
		}
		this.revealBox();
		
		if (Browser.Engine.trident) {
			this.contentContainer.getElements('form').addEvent('submit', this.handleAutoForm.bindWithEvent(this));
			this.contentContainer.getElements('form input').addEvent('keydown', function(evt){
				if (evt.key == 'enter') {
					evt.target = evt.target.getParent('form');
					this.handleAutoForm(evt);
				}
			}.bindWithEvent(this));
		}
	},
	
	showTooltip: function(markup, triggerElement) {
		if (!markup) { return false; }
		this.resetFrame();
    	this.hideTimeout = $clear(this.hideTimeout);
		if (!triggerElement) {
			triggerElement = document.body;
		}
		triggerElement = $(triggerElement);
		this._TooltipTrigger = triggerElement;
		this.contentWrapper.addClass(this.options.CLASSES.applyWhenTooltip);
		
		this.contentContainer.set('html', markup);
		this.revealBox();
	},
	
	showXhr: function(uri) {
		if (uri.test('\.' + this.options.imageExtensions.join('|\.'))) {
			
			var currentTime = (new Date()).getTime();
			uri = uri + '?xhr=' + currentTime;
			
			var newImage = new Element('img');
			
			newImage.set('src',uri);
			newImage.addClass(this.options.CLASSES.closeButton);
			newImage.addEvent('load', function(evt) {
				this.showMarkup(newImage);
			}.bindWithEvent(this));
		} else {
			new Request.HTML({
				url: uri+"/xhr:1",
				method: 'get',
				onSuccess: this.handleXhrSuccess.bind(this),
				evalScripts: true
			}).send();
		}
	},
	
	handleXhrSuccess: function(responseTree, responseElements, responseHTML) {
		
		if (responseHTML) {
			this.showMarkup(responseHTML);
		} else if ($type(responseTree) == 'string' && responseTree) {
			this.showMarkup(responseTree);
		} else {
			this.hide();
		}
	},
	
	revealBox: function() {
		this.positionContentWrapper();
		this.showUnderlay();
		//this.contentWrapper.fade('in');
		this.contentWrapper.set('tween', { onComplete:this.positionContentWrapper() }).fade('in');
	},
	
	showUnderlay: function() {
		if (!this._TooltipTrigger) {
			this.underlay.setStyles({
				'opacity': 0,
				'display': 'block'
			});
			this.setUnderlayHeight();
			this.underlay.fade(this.options.underlayStyles.opacity);
			this.underlay.retrieve('IframeShim').position();
		}
	},
	setUnderlayHeight: function() {
		if (this.underlay) {
			this.underlay.setStyles({
				'height': window.getSize().y + 'px'
			});
		}
	},
	
	positionContentWrapper: function() {
		
		if (this._TooltipTrigger && $type(this._TooltipTrigger) == 'element') {
			this.contentWrapper.position({
				relativeTo: this._TooltipTrigger,
				position: 'bottomLeft'
			});
		} else {
			this.contentWrapper.position();
		}
		this.underlay.retrieve('IframeShim').position();
	},
	
	hide: function() {
		this.underlay.fade('out');
		this.contentWrapper.fade('out');
	},
	
	resetFrame: function() {
		
		var addedElements = false;
		
		//underlay
		if (!this.underlay) {
			this.underlay = new Element('div', {
				'id': this.options.IDS.underlay,
				'styles': this.options.underlayStyles
			});
			this.underlay.inject($(document.body));
			addedElements = true;
		} else {
			this.underlay.setStyles(this.options.underlayStyles);	
		}
		
		//contentWrapper
		if (!this.contentWrapper) {
			this.contentWrapper = new Element('div', {
				'id': this.options.IDS.contentWrapper,
				'styles': this.options.contentWrapperStyles
			});
			this.contentWrapper.inject($(document.body));
			addedElements = true;
		} else {
			this.contentWrapper.setStyles(this.options.contentWrapperStyles);
		}
		
		//contentContainer
		if(!this.contentContainer) {
			this.contentContainer = new Element('div', {
				'id': this.options.IDS.contentContainer,
				'styles': this.options.contentContainerStyles
			});			
			this.contentContainer.inject(this.contentWrapper);
			addedElements = true;
		} else {
			this.contentContainer.setStyles(this.options.contentContainerStyles);
		}
		
		if (addedElements) {
			this.addListeners();
		}
		
		if (!this._TooltipTrigger) {
			this.contentWrapper.removeClass(this.options.CLASSES.applyWhenTooltip);
		}
	},
	
	addShims: function() {
		this.underlayShim = new IframeShim(this.underlay);
		this.wrapperShim = new IframeShim(this.contentWrapper);
	}
	
});

CHINET.basebox = null;
window.addEvent('domready', function() {
    try {
    	CHINET.basebox = new CHINET.AYB.ui.global.BaseBox();
    	// listen for any clicks
    	$(document.body).addEvent('click', function(evt) {
    		if ($(evt.target).match(CHINET.basebox.options.SELECTORS.autoClick)) {
    			evt.preventDefault();
    			CHINET.basebox.handleAutoClick(evt);
			} else {
    			var parent = $(evt.target).getParent(CHINET.basebox.options.SELECTORS.autoClick);
    			if (parent) {
					evt.preventDefault();
					CHINET.basebox.handleAutoClick(evt);
				}
    		} 
			
			if ($(evt.target).match('.' + CHINET.basebox.options.CLASSES.closeButton)) {
    			evt.preventDefault();
    			CHINET.basebox.hide();
			} else {
				parent = $(evt.target).getParent('.' + CHINET.basebox.options.CLASSES.closeButton);
				if (parent) {
					evt.preventDefault();
					CHINET.basebox.hide();
				}
			}
    	});
		
		$(document.body).addEvent('submit', function(evt) {
			if ($(evt.target).match(CHINET.basebox.options.SELECTORS.autoForm)) {
				evt.preventDefault();
				CHINET.basebox.handleAutoForm(evt);
			}
		});
		
		$(document.body).addEvent('click', function(evt) {
			if ($(evt.target).id == 'btn_confirmdelete') {
				
				evt.preventDefault();
				CHINET.basebox.hide();
				
				var itemToDelete =	evt.target.get('rel');
				var list_element = new Fx.Slide($(itemToDelete));
				/* Enable slideOut() effect */
				list_element.slideOut();
				
			}
		});
		
		
    } catch (err) {
        console.warn('BaseBox startup error');
        console.dir(err);
    }
});

