/**
 * This is main script to include generally first of all custom scripts in the pages.
 *
 * Sets up the framework, based on which all other scripts work.
 *
 * @version 1.0.
 * @author Dmitry Tkach.
 * @uses jQuery, jQuery.validate, jQuery.autoclear, jQuery.cookie.
 * @fixes the jQuery.tools interface (missed addTabEffect method).
 *
 * Changes:
 * version 1.0:
 * <ol>
 * 	<li>Added behaviour attaching to the highslide-generated container [v].</li>
 * </ol>
 */


/**
 * Main application controller. Centralizes the controls over all frontend scripts.
 */
(function() {
	var controller = {
		_data : {
			behaviours : {
				early : [],
				medium : [],
				late : []
			}
		},

		init : function()
		{
			this._initValidators()._fixupJqueryTools();

			if (window.hs)
			{
  			hs.Expander.prototype.onBeforeExpand = hs.onActivate = function()
				{
					window['e_planet']['controller'].refreshBehaviours(hs.container);
				}
			}
			
			return this;
		},

		_fixupJqueryTools : function()
		{
			if (jQuery.tools && ! jQuery.tools.addTabEffect)
			{
				jQuery.tools.addTabEffect = function()
				{
					jQuery.tools.tabs.addEffect.apply(jQuery.tools.tabs, arguments);
				};
			}

			return this;
		},

		_initValidators : function()
		{
				if (jQuery.validator) {
				  jQuery.validator.addMethod('captcha', function(val, el, params) {
				     //validate the captcha code.
				     var hash = $('input[name=nc_captcha_hash]').val();
			//       var cache_bypass = Math.random();
				     var ret = false;
				      
				     return jQuery.ajax({
				        url : '/netcat/modules/captcha/verify.php',
				        async : false,
				        cache : false,
				        data : {
				          code : val,
				          hash : hash
				        },
				        dataType : 'html',
				        success : function(result, status, xhr)
				        {
				          ret = parseInt(result);
				        }
				      });
				      
				      return ret;
				  }, '');
			}
			
			return this;
		},

		/**
		 * Adds behaviours to the page`s elements.
		 *
		 * @param {HTMLElement|jQuery} root		root of DOM subtree, for which to apply behaviours. If omitted,
		 * the document element is used.
		 * @return {Object} self.
		 */
		applyBehaviours : function(root)
		{
			root = $(root || document);
			jQuery.each(['early', 'medium', 'late'], function(i, time) {
				controller._invokeTimeBehaviourAdders(time, root);
			});
			return this;
		},

		_invokeTimeBehaviourAdders : function(time, root)
		{
			jQuery.each(this._data.behaviours[time], function(i, cb) {
				cb(root);
			});

			//this._data.behaviours[time] = [];
			return this;
		},

		/**
		 * Adds a behavioural handler to be executed where document is ready.
		 *
		 * @param {Function} cb.
		 * @param {String} time.
		 * @return {Object} self.
		 */
		addBehaviour : function(cb, time)
		{
			if (time != 'early' && time != 'medium' && time != 'late')
				time = 'medium';

			this._data.behaviours[time].push(cb);
			return this;
		},

		/**
		 * Refreshes the behaviours for the elements of DOM subtree.
		 *
		 * @param {HTMLElement|jQuery} root		root of DOM subtree, for which to apply behaviours.
		 * @return {Object} self.
		 */
		refreshBehaviours : function(root)
		{
			this.applyBehaviours(root);
			return this;
		}
	};


	window['e_planet'] = window['e_planet'] || {};
	window['e_planet']['controller'] = {
		/**
		 * Adds a callback function, to be executed when the document is ready.
		 *
		 * @param {Function} cb		Callback function, adding some behaviour to the elements of the page.
		 * @param {String} time		Time, where to call the callback, relative to other callbacks. Possible values:
		 * 'early', 'medium', 'late'. Default is 'medium'. First 'early'-time callbacks are called, then 'medium'
		 * and finally 'late'. Callbacks with the same time specifier are called in order they are added.
		 * @return {Object} self.
		 */
		addBehaviour : function(cb, time)
		{
			controller.addBehaviour(cb, time);
			return this;
		},

		/**
		 * Refreshes the attached behaviours, by applying them if they are unapplied.
		 * 
		 * @param {HTMLElement|jQuery} el		root of DOM subtree, for which to re-apply behaviours.
		 * @return {Object} self.
		 */
		refreshBehaviours : function(el)
		{
			controller.refreshBehaviours(el);
			return this;
		}
	};


	(function($) {
		controller.init();

		head.ready('tools', function() {

		  controller.addBehaviour(function(dom_root)	{
				jQuery.tools.addTabEffect("slowSlide", function(tabIndex, done) {
				  this.getPanes().slideUp(700);
				  var $pane = this.getPanes().eq(tabIndex);
				  var $tab  = this.getCurrentTab();
				  
				  $pane.slideDown(700, function() {
				  	$tab.focus();
				  	if (done)
				  		done.call();
				  });
				// the supplied callback must be called after the effect has finished its job 
		//	    done.call(); 
				});

				$(".accordeon").tabs("div.item-contents", {tabs : 'h3>a', effect : 'slowSlide', initialIndex : 0, current : 'current'});
			}).refreshBehaviours();
		});

		head.ready('validate', function() {
			controller.addBehaviour(function(dom_root) {
				var ff = $("#feedback-form");
				if (ff.length && ! ff[0].behaviour_attached) {
						ff[0].behaviour_attached = true;
						ff.validate({
						  rules: {
						      'nc_captcha_code': {
						          required: true,
						          captcha: 'param'
						      }
						  },
						  messages: {
						      nc_captcha_code: '',
						      f_Name: '',
						      f_Text: '',
						      f_Email: ''
						  }//,
					});
				
					ff.submit(function(evt) {
						if ($(this).validate().form()) {
						} else {
						  evt.preventDefault();
						}
					});
				}
			}).refreshBehaviours();
		});

		controller.addBehaviour(function(dom_root) {

			var get_another_captcha = $('#get_another_captcha');	 
		
			if (get_another_captcha.length && !get_another_captcha[0].behaviour_attached)
			{
					get_another_captcha[0].behaviour_attached = true;
					get_another_captcha.click(function(evt) {
						evt.preventDefault();
						getAnotherCaptcha();
					});
			}
		});

		head.ready('autoclear', function() {
			controller.addBehaviour(function(dom_root) {
		//		if (window.console)
		//			console.log('Autoclear behaviour is applied to the ', dom_root, ' subtree.');

				 dom_root.find('.autoclear').each(function(i) {
						if ( ! this.behaviour_attached) {
		//					if (window.console)
		//						console.log('Autoclear behaviour is applied to the ', this, ' element.');
						  this.behaviour_attached = true;
						  var el = $(this);
						  el.autoclear();
						  el.title = '';
						}
				 });
			}).refreshBehaviours();
		});
	})(jQuery);

})();

/**
 * @deprecated.
 */
attachBehaviours = function(){};//addDynamicBehaviours;


function getAnotherCaptcha()
{
	  jQuery.ajax({
	    type: 'POST',
	    url : '/netcat/modules/captcha/regen.php',
	    complete: function(msg) {
	      if (msg.responseText) {
	        jQuery('#captcha_image').attr('src', '/netcat/modules/captcha/img.php?code=' + msg.responseText);
	        jQuery('#nc_captcha_code').attr('captcha_hash', msg.responseText);
	        jQuery('input[name=nc_captcha_hash]').val(msg.responseText);
	      }
	    }
	  });
	  return false;
}


/*
 * End of file main.js.
 */

