var MGFX = MGFX || {};
var Arkonas = Arkonas || {};

MGFX.Rotater = new Class({
	
	Implements: [Options, Events],
	
	options: {
		slideInterval: 5000,
		transitionDuration: 1000,
		startIndex: 0,
		autoplay: true,
		hover:true,
		hash: true,
		onAutoPlay: $empty,
		onRotate: $empty,
		onShowSlide: $empty,
		onStop: $empty,
		onPause: $empty,
		onResume: $empty
	},
	
	initialize: function(slides,options) {
		this.setOptions(options);
		this.slides = $$(slides);
		this.createFx();
		this.showSlide(this.options.startIndex);
		if(this.slides.length < 2) this.options.autoplay = false;
		if(this.options.autoplay) this.autoplay();
		return this;
	},
	
	createFx: function(){
		if (!this.slideFx) this.slideFx = new Fx.Elements(this.slides, {duration: this.options.transitionDuration, link: 'cancel'});
		this.slides.each(function(slide) {
			slide.setStyle('opacity',0);
		});
	}.protect(),
	
	setupHover: function() {
		var _timeLastRotate = new Date(),
			_timeLastPause,
			_timeTillRotate = this.options.slideInterval,
			_resumeDelay;
			
		var onRotate = this._onRotate = function() {
			if(this.slideshowInt) {
				_timeLastRotate = new Date();
				_timeTillRotate = this.options.slideInterval;
			}
		};
		var onMouseEnter = this._onMouseEnter = function() {
			this.stop();
			_timeLastPause = new Date();
			$clear(_resumeDelay);
			this.fireEvent('onPause');
		}.bind(this);
		
		var onMouseLeave = this._onMouseLeave = function() {
			var timePassed = (_timeLastPause - _timeLastRotate);
			_timeLastRotate = new Date() - timePassed;
			_resumeDelay = (function() {
				this.autoplay();
				this.rotate();
				this.fireEvent('onResume');
			}).delay(_timeTillRotate - timePassed, this);			
		}.bind(this);
		
		this.addEvent('onRotate', onRotate);
		this.slides.addEvents({
			'mouseenter': onMouseEnter,
			'mouseleave': onMouseLeave
		});
	}.protect(),
	
	removeHover: function() {
		this.removeEvent('onRotate', this._onRotate);
		this.slides.removeEvents({
			'mouseenter': this._onMouseEnter,
			'mouseleave': this._onMouseLeave
		});
	},
	
	showSlide: function(slideIndex){
		if(slideIndex == this.currentSlide) return this;
		var action = {};
		this.slides.each(function(slide, index) {
			if(index == slideIndex && index != this.currentSlide) { //show
				action[index.toString()] = {
					opacity: 1
				};
			} else {
				action[index.toString()] = {
					opacity:0
				};
			}
		}, this);
		this.fireEvent('onShowSlide', slideIndex);
		this.currentSlide = slideIndex;
		this.slideFx.start(action);
		return this;
	},
	
	autoplay: function() {
		if(this.options.hover) this.setupHover();
		this.slideshowInt = this.rotate.periodical(this.options.slideInterval, this);
		this.fireEvent('onAutoPlay');
		return this;
	},
	
	stop: function(not_pause) {
		$clear(this.slideshowInt);
		this.fireEvent('onStop');
		if(not_pause && this.options.hover) this.removeHover();
		return this;
	},
	
	rotate: function() {
		var current = this.currentSlide;
		var next = (current+1 >= this.slides.length) ? 0 : current+1;
		this.showSlide(next);
		this.fireEvent('onRotate', next);
		return this;
	}

});

MGFX.Tabs = new Class({
	
	Extends: MGFX.Rotater,
	
	options: {
		autoplay: false,
		onShowSlide: function(slideIndex) {
			this.tabs.removeClass('selected');
			this.tabs[slideIndex].addClass('selected');
		}
	},
	
	initialize: function(tabs, slides, options) {
		this.setOptions(options);
		this.tabs = $$(tabs);
		this.createTabs();
		if(this.options.hash && window.location.hash) {
			var hash = window.location.hash.substring(1);
			this.tabs.each(function(el, index) {
				if(el.get('id') == hash) {
					options.startIndex = index;
				}
			});
		}
		return this.parent(slides,options);
	},
	
	createTabs: function () {
		this.tabs.each(function(tab,index ){
		  tab.addEvent('click', function(event) { 
				event.preventDefault();
				this.showSlide(index);
				this.stop(true);
			}.bind(this));
		}.bind(this));
	}.protect()
});

Arkonas.SubmitManager = new Class({
    Implements: Options,
    	
    options: {
        responseContainer: 'document.body',
        failureMsg_en: 'Something\'s wrong in our system. Please come back later...',
        failureMsg_es: 'En este momento no podemos procesar su solicitud.<br/>Por favor intente m&#225;s tarde.',
        successMsg_en: 'Request processed successfully',
        successMsg_es: 'Solicitud procesada exitosamente'
    },
  	
  	initialize: function(frm, options) {
  	    this.frm = $(frm);
  	    this.setOptions(options);
  	    this.responseContainer = $defined(this.options.responseContainer) ? $(this.options.responseContainer) : this.frm;
  	    this.responseCanvas = null;
  	    this.validator = null;
  	    window.addEvent('domready', this.domReady.bind(this));
  	},
  	
  	domReady: function() {
  	    this.createResponse();
  	    
        this.validator = new FormCheck(this.frm, {
            submitByAjax: 1,
            onAjaxRequest: function() {
                this.responseCanvas.setStyle('display', 'block');
                this.frm.setStyle('display', 'none');
  	        }.bind(this),
            onAjaxSuccess: function(args) {
                this.onAjaxResponse(args);
      	    }.bind(this),
            onAjaxFailure: function() {
      	        this.onAjaxResponse('{ success : 0 }');
      	    }.bind(this),
            display : {
                errorsLocation : 0,
                indicateErrors : 2,
                showErrors : 1,
                scrollToFirst: false,
                addClassErrorToField : 1
            }
        });
  	},
  	
  	onAjaxResponse: function(args) {
  	    if ($defined(args)) {
            try {
                var response = JSON.decode(args);
                
                if ($defined(response) && response.success == 1) {
                   this.responseContainer.set('html', this.getSuccessMessage(this.frm.lang));
                } else {
                    this.responseContainer.set('html', this.getFailureMessage(this.frm.lang));
                }
            } catch (err) {
                this.responseContainer.set('html', this.getFailureMessage(this.frm.lang));
            }
        }
        
        this.responseContainer.setStyle('display', 'block');
        this.responseCanvas.setStyle('display', 'none');
  	},
  	
  	getFailureMessage: function(lang) {
  	    if ($defined(this.options.failureMsg)) {
  	        return this.options.failureMsg;
  	    } else {
  	        var lang = ($defined(lang)) ? lang.toLowerCase() : 'en';
  	        return eval('this.options.failureMsg_' + lang);
  	    }
  	},
  	
  	getSuccessMessage: function(lang) {
  	    if ($defined(this.options.successMsg)) {
  	        return this.options.successMsg;
  	    } else {
  	        var lang = ($defined(lang)) ? lang.toLowerCase() : 'en';
  	        return eval('this.options.successMsg_' + lang);
  	    }
  	},  	
  	
  	createResponse: function() {
  	    this.responseCanvas = new Element('div', { id: 'response-canvas' });
  	    this.responseCanvas.setStyles({
  	        position: this.frm.getStyle('position'),
  	        display: 'none',
  	        top: this.frm.getStyle('top'),
  	        left: this.frm.getStyle('left'),
  	        width: this.frm.getParent().getStyle('width'),
  	        height: this.frm.getParent().getStyle('height'),
  	        background : this.frm.getStyle('background-color') + ' url(images/multibox/loader.gif) no-repeat center'
  	    });
  	    
  	    $(document.body).grab(this.responseCanvas);
  	    
  	},
  	
  	reset: function() {
  	    this.frm.reset();
  	    this.frm.getElements('select').each(function(el, i) {
  	        el.value = el.options[0].value;
  	        el.onchange();
  	    }, this);
  	}
});

function validateSelect(el) {
    if (el.value == '') {
        return false;
    } else {
        return true;
    }
}
