/*

MoDi - for modal dialogues

*/
var MoDi = new Class({
	Implements: [Events, Options],
	options: {
			backgroundOpacity: 0.8,
           panelStyles: {
               width: 600,
               height: 400,
               backgroundColor: '#323232',
           },
           backStyles: {
              backgroundColor: '#000000',

           },
		   closeImage: "url('assets/acbs/img/close.png')"
	},
	initialize: function(options) {
         this.setOptions(options);
      this.createElements();

	},
   show: function() {
      //panel math
      var panel = {};
      panel.height = this.elements.moDiPanel.getSize();
      panel.height = panel.height.y;
      panel.from = (panel.height / 2) * -1;
      panel.to = window.getSize();
      panel.to = (panel.to.y / 2)
      this.elements.moDiBack.setStyles({
         'visibility': 'visible',
         'opacity': 0,
      });
      this.elements.moDiPanel.setStyles({
         'visibility': 'visible',
         'top': panel.from,
      });
      var fx = {
         moDiBack: new Fx.Tween(this.elements.moDiBack, {
            complete: function() {
               
            },
            duration: '500',
            property: 'opacity'
         }),
         moDiPanel: new Fx.Tween(this.elements.moDiPanel, {
            complete: function() {
               
            },
            duration: '750',
            property: 'top',
         transition: Fx.Transitions.Quad.easeOut
         })
      };
      fx.moDiBack.start(0,this.options.backgroundOpacity);
      fx.moDiPanel.start(panel.from, panel.to);
   },
   hide: function() {
      //panel math
      var panel = {};
      panel.height = this.elements.moDiPanel.getSize();
      panel.height = panel.height.y;
      panel.from = this.elements.moDiPanel.getStyle('top');
      panel.to = (panel.height / 2) * -1;

      var fx = {
         moDiBack: new Fx.Tween(this.elements.moDiBack, {
            complete: function() {
               this.elements.moDiBack.setStyles({
                  'visibility': 'hidden',
               });
            }.bind(this),
            duration: '750',
            property: 'opacity'
         }),
         moDiPanel: new Fx.Tween(this.elements.moDiPanel, {
            complete: function() {
               this.elements.moDiPanel.setStyles({
                  'visibility': 'hidden',
                  'top': panel.from,
               });
            },
            duration: '500',
            property: 'top',
            transition: Fx.Transitions.Quad.easeIn
         })
      };
      fx.moDiBack.start(this.options.backgroundOpacity,0);
      fx.moDiPanel.start(panel.from, panel.to);

   },
   setContent: function(content) {
   //console.log(content);
      //if (typeOf(content) == 'string') content = Mooml.render(content, moomlParm);
      this.elements.moDiPanel.empty();
      this.elements.moDiPanel.grab(this.elements.moDiClose);
      this.elements.moDiPanel.adopt(content);
   },
   spin: function() {
      this.spinner = new Spinner(this.elements.moDiPanel);
      this.spinner.show();
   },
   unspin: function() {
      this.spinner.hide();
      this.spinner.destroy();
      this.spinner = null;
   },
	createElements: function() {
		this.options.panelStyles.marginTop = this.options.panelStyles.height * -0.5;
		this.options.panelStyles.marginLeft = this.options.panelStyles.width * -0.5;
		this.elements.moDiBack = $$([
			'div#moDiBack.moDi',
			{
				styles: this.options.backStyles,
				events: { click: this.hide.bind(this) }
			}
		]);
		this.elements.moDiPanel = $$([
			'div#moDiPanel.moDi',
			{
				styles: this.options.panelStyles
			}
		]);
      this.elements.moDiClose = $$([
		'div#moDiClose.moDi',
		{ 
			styles: { backgroundImage: this.options.closeImage },
			events: { click: this.hide.bind(this) }
		}
		]);
	  /*
      this.elements.moDiBack = new Slicker(this.elements.moDiBack);
      this.elements.moDiPanel = new Slicker(this.elements.moDiPanel);
      this.elements.moDiClose = new Slicker(this.elements.moDiClose);
	  this.elements.moDiBack = this.elements.moDiBack.render();
	  this.elements.moDiPanel = this.elements.moDiPanel.render();
	  this.elements.moDiClose = this.elements.moDiClose.render(this.options.closeImage);
      this.elements.moDiBack.setStyles(this.options.backStyles);
      this.elements.moDiPanel.setStyles(this.options.panelStyles);
      this.elements.moDiBack.addEvent('click', this.hide.bind(this));
      this.elements.moDiClose.addEvent('click', this.hide.bind(this));
	  console.log(this.elements.moDiBack);
	  */
	  //console.log(this.elements.moDiBack);
      $$('body').adopt(this.elements.moDiBack);
      $$('body').adopt(this.elements.moDiPanel);
	  /*
	  var panel = {
		marginTop: (this.options.panelStyles.height * -0.5) + 'px',
		marginLeft: (this.options.panelStyles.width * -0.5) + 'px',
	  };
	  this.elements.moDiPanel.setStyles(panel);
	  */
	  utils.styleSheet(this.moDiStyles);
      //this.applyStyles();
   },
   /*
   applyStyles: function(panelStyles, backStyles) {
   
      var back = Object.merge(
         this.options.backStyles,
         backStyles
      );
      var panel = Object.merge(
         this.options.panelStyles,
         panelStyles
      );
	  
      panel['margin-top'] = (panel.height * -0.5) + 'px';
      panel['margin-left'] = (panel.width * -0.5) + 'px';
      //console.log(panel);
      this.elements.moDiPanel.setStyles(panel);
      this.elements.moDiBack.setStyles(back);
   },
   */
	moDiStyles: {
		'#moDiBack': {
			visibility: 'hidden',
			position: 'fixed',
			display: 'block',
			width: '100%',
			height: '100%',
			left: 0,
			top: 0,
			zIndex: 50
		},
		'#moDiPanel': {
			visibility: 'hidden',
			position: 'fixed',
			display: 'block',
			left: '50%',
			zIndex: '51'
		},
		'#moDiClose': {
			position: 'absolute',
			display: 'block',
			right: '0px',
			top: '0px',
			margin: '-18px',
			width: '36px',
			height: '36px',
			//backgroundImage: closeImage,
			zIndex: 100
		}
	},
   elements: {},
   spinner: null,
});

Window.implement('render', function(template) {
	var elements = [];
	template.each(function(item, index) {
		if (typeOf(item) == 'element') elements.push(item);
		else if (typeOf(item) == 'array') elements[elements.length - 1].adopt(render(item));
		else if (typeOf(item) == 'object') elements[elements.length - 1].set(item);
		else if ((typeOf(item) == 'string') && (item.substr(0,1) == '"')) elements.push(document.createTextNode(item.substr(1)));
		else if (typeOf(item) == 'string') elements.push(new Element(item));
		else return null; //items must be string or array.
	});
	if (elements.length == 1) return elements[0];
	else return elements;
});


Window.implement('$$', function(selector){
//console.log(selector);
	if (arguments.length == 1){
		if (typeOf(selector) == 'string') return Slick.search(this.document, selector, new Elements);
		if (typeOf(selector) == 'array') {
			//console.log('slick');
			
			var elements = [];
			selector.each(function(item, index) {
			//console.log(item);
			//console.log(elements);
			//console.log(elements.length);
				if (typeOf(item) == 'element') elements.push(item);
				else if (typeOf(item) == 'array') elements[elements.length - 1].adopt($$(item));
				else if (typeOf(item) == 'object') elements[elements.length - 1].set(item);
				else if ((typeOf(item) == 'string') && (item.substr(0,1) == '"')) elements.push(document.createTextNode(item.substr(1)));
				else if (typeOf(item) == 'string') elements.push(new Element(item));
				else return null; //items must be string or array.
			});
			if (elements.length == 1) return elements[0];
			else return elements;
		} else if (Type.isEnumerable(selector)) return new Elements(selector);
	}
	return new Elements(arguments);
});
/*
Slicker...
return value: if there's more than one element in the 'root' level, then an array is returned. if there is a single root element, then the element is returned. It does not return an Elements instance, ie has dramas converting an array containing textNodes to an Elements instance
var template = new Slicker(function(foo, bar) { return [
	'div#fooDiv[text=' + foo + ']',
		[
		'div.' + bar,
		]
	];
});
*/
/*
var Slicker = new Class({
	initialize: function(template) {
		this.template = template;
	},
	render: function() {
		if (typeOf(this.template) == 'array') this.elements = this.parse(this.template);
		else if (typeOf(this.template) == 'function') this.elements = this.parse(this.template.apply(this, arguments));
		return this.elements;
	},
	parse: function(template) {
		template = template.clean();
		if (typeOf(template[0]) == 'array') return null; //first item should always be a string / element
		var elements = [];
		template.each(function(item, index) {
			if (typeOf(item) == 'element') elements.push(item);
			else if (typeOf(item) == 'array') elements[elements.length - 1].adopt(this.parse(item));
			else if (typeOf(item) == 'object') elements[elements.length - 1].setStyles(item);
			else if ((typeOf(item) == 'string') && (item.substr(0,1) == '"')) elements.push(document.createTextNode(item.substr(1)));
			else if (typeOf(item) == 'string') elements.push(new Element(item));
			else return null; //items must be string or array.
		}, this);
		if (elements.length == 1) elements = elements[0];
		return elements;
	},
	toElement: function() {
		return this.elements;
	},
	elements: null
});
*/
var utils = {};
utils.styleSheet = function(styles) {
	this.temp = new Element('div');
	var style = new Element('style').inject(document.head);
	style = style.styleSheet || style.sheet;
	Object.each(styles, function(rules, selector){
		this.temp.setStyles(rules);
		if (style.addRule) style.addRule(selector, this.temp.style.cssText);   
		else style.insertRule(selector+'{'+this.temp.style.cssText+'}', sheet.cssRules.length);
		this.temp.style.cssText = '';
	}, this);
};

var AjaxMailStuff = new Class({
   Implements: [Events, Options],
   options: {
      requestUrl: '/13', 
      debug: 1,
   },
   initialize: function(options) {
      this.setOptions(options);
      this.createRequest();
   },
   createRequest: function() {
      this.request = new Request.JSON({
         url: this.options.requestUrl,
         onSuccess: function(response) {
            this.response(response);
         }.bind(this),
         onError: function(text, error) {
            if (this.options.debug) console.log(error);
            if (this.options.debug) console.log(text);
            this.response({'flag':8});
         }.bind(this),
         onFailure: function(response) {
			if (this.options.debug) console.log(response);
			if (this.options.debug) console.log('onFailure triggered');
            this.response({'flag':9});
         }.bind(this)
      });      
   },
   response: function(flag) {
      var codesConsole = {
         1: 'Successfully subscribed',
         2: 'Error: Already Subscribed',
         3: 'Error: Not Subscribed (cannot unsub)',
         4: 'Successfully unsubscribed',
         5: 'Nothing to do.. no action specified',
         6: 'Email sent successfully',
         7: 'Email not sent',
         8: 'data could not be JSON encoded',
         9: 'no response - ajax error',
      };
      var codesUser = {
         1: 'Thankyou! You have been added to our mailing list.',
         2: 'It looks like you were already on our mailing list!',
         3: 'We do not seem to have that email address on our list.',
         4: 'You are no longer subscribed to our mailing list. Sorry to see you go.',
         5: 'Oh dear. Some error has occurred - our trained monkeys have been notified and are working to resolve the problem, please try again later.',
         6: 'Thankyou! Your email has been sent, someone will be in touch as soon as possible.',
         7: 'Oh dear. Some error has occurred - our trained monkeys have been notified and are working to resolve the problem, please try again later.',
         8: 'Oh dear. Some error has occurred - our trained monkeys have been notified and are working to resolve the problem, please try again later.',
         9: 'Oh dear. Some error has occurred - our trained monkeys have been notified and are working to resolve the problem, please try again later.',
      };
      //if (this.options.debug) console.log(codesConsole[flag['flag']]);
      this.callback(codesUser[flag['flag']]);
   },
   request: null,
});
