/*	behavior.js */

var Joomla = Joomla || {};

window.addEvent('domready',function() {
	
	// FORMVALIDATOR
	formvalidator_plus = function() {
		
		// MTloader('Class.refactor', 'More', URLS.template + 'js/mootools-more/', 'Asset', function() {
		
		/**
		 *	methods:	initialize(), setHandler(name, fn, en), attachToForm(form), validate(el), validate(form), handleResponse(state, el)
		 *	handlers: 	username, password, numeric, email
		 *	hadnlers+:	name, emailverify, one-required
		 */
		
		// name
		document.formvalidator.setHandler('name',
			function (value) {
				// regex = /^\S[\S ]{2,98}\S$/;
				regex = /^[\w\s]{2,98}$/;
				return  regex.test(value);
			}
		);
		
		// email verify (compares to first name=email)
		document.formvalidator.setHandler('emailverify',
			function (value, el) {
				el = el || arguments.callee.caller.caller.arguments[0] || null;
				name = el.get('name') || 'Email';
				return (document.getElement('form.form-validate input[name^="'+ name +'"]').value == value);
			}
		);
		
		// match verify
		// ref: http://mootools.net/docs/more/Forms/Form.Validator.Extras#Validators:validate-match
		document.formvalidator.setHandler('match', 
			function (value, el) {
				
				var valid;
				
				// fetch element (validate(function(el)));
				el = el || arguments.callee.caller.caller.arguments[0] || null;
				if (!el) return;
				
				// match name [class="matchName:email]
				if (el.get('class').search(/matchName\:([a-zA-Z0-9\_\-]+)/) != -1) {
					matchName = el.get('class').match(/matchName\:([a-zA-Z0-9\_\-]+)/)[1];
					similar = el.form.getElement( '*[name="' +matchName+ '"])' );
				// match input id [class="matchInput:email]
				} else if (el.get('class').search(/matchInput\:([a-zA-Z0-9\_\-]+)/) != -1) {
					matchInput = el.get('class').match(/matchInput\:([a-zA-Z0-9\_\-]+)/)[1];
					similar = el.form.getElement( '#' +matchInput );
				// guess name
				} else {
					guessName = el.get('name') ? el.get('name') : "email";
					similar = el.form.getElement( '*[name^="' +guessName+ '"]' );
				}				
				
				if (similar) {
					valid = (value == similar.get('value'));
				} else {
					valid = false;
				}
				
				// document.formvalidator.handleResponse( valid, similar );
				return valid;
			}
		);
		
		// one-required
		document.formvalidator.setHandler('one-required', 
			function (value, el) {
			
				var valid;
				// fetch element (validate(function(el)));
				el = el || arguments.callee.caller.caller.arguments[0] || null;
				if (!el) return false; // !!
				
				// fech all elements with same name inside current form
				similar = el.form.getElements( '*([name="' +el.get('name')+ '"])');
				
				// check if any checked
				valid = (null != el.form.getElement( '*[name="' +el.get('name')+ '"]:checked' ));
				
				// similar elements valid/ invalid
				similar.each(function(el2, i){
					document.formvalidator.handleResponse( valid, el2 );
				});
				return valid;
			}
		);
		
		// recheck for special needs
		document.formvalidator.customZ = [{ // may remove
			exec: function() { return true;}
		}];
		
		// store handlers
		document.getElements('form.form-validate *([class^="validate-"])').each(function(el, i){
			el.store('handler', el.get('class').match(/validate-([a-zA-Z0-9\_\-]+)/)[1] );
		});
		
		// add events
		document.getElements('form.form-validate input([type!="submit"]), form.form-validate button([type!="submit"])').addEvents({
			'keyup': function(){ this.fireEvent('blur', this); },
			'focus': function(){ this.fireEvent('blur', this, 100); } // old value on focus
		});
	}
	
	
	// BEHAVIORS
	Joomla.registered = Joomla.registered || { };
	/*
	Joomla.JBehaviour = {
		registered	: {},
		JLoad		: function{},
		JImport		: function(){},
	}
	*/
	
	
	behaviors = {
		/*
		// Form validation
		formvalidation 	: {
			test		: function(){ return (document.getElement('form.form-validate') != null && typeof JFormValidator == "undefined"); },
			require		: (URLS.base||"") + "media/system/js/validate.js",
			success		: formvalidator_plus
		},
		
		// Form validation in case validate.js already loaded
		formvalidation2	: {
			test		: function() { return (document.getElement('form.form-validate') != null && typeof JFormValidator != "undefined"); },
			success		: formvalidator_plus
		},
		/* */
		
		// Form validation
		formvalidation	: {
			test		: function() { return (document.getElement('form.form-validate') != null); },
			require		: (typeof JFormValidator == "undefined" ? (URLS.base||"") + "media/system/js/validate.js" : null),
			success		: formvalidator_plus
		},
		
		// Mediabox Advanced
		MediaboxAdv: {
			test		: function() { return (document.getElement('a([rel^="lightbox"])') != null && typeof Mediabox == "undefined"); },
			require		: [
				(URLS.base||"") + "media/tool_mediaboxAdv/js/mediaboxAdv-1.3.4b-yc.js",
				(URLS.template) + "css/gallery.css"
			]
		}
	}
	//		require		: ['some.js', 'some.css', 'some']
	
	/**
	 * JLoad
	 *
	 * <code>
	 *	JLoad(['script1.js', 'script2.js'], function() { alert('loaded'); } );
	 * </code>
	 *
	 * @param	string | array	paths to load
	 * @param	function		callback to execute
	 * @return 	bool 			True on success, false on failure
	 */
	JLoad = function(items, callback){
		if (typeof Asset == "undefined") return false;
		var callback 		= callback || function(){};
		// items 			= typeof items != "object" ? [items] : items; // convert to array
		var items			= (items instanceof Array) ? items : [items];
		var loaded 			= 0;
		
		check = function() {
			loaded++;
			if (loaded == items.length) {
				callback();
			}
		}
		
		// loop
		Array.each(items, function(item, i){
		
			type = item.match(/\.([^.]+)$/)[1];
			
			// css
			if ( type == "css" && document.getElement('head script[src*="' +item+ '"]') == null ) {
				Asset.css ( item );
				check();
			}
			
			// javascript
			if ( type == "js" && document.getElement('head link[href*="' +item+ '"]') == null ) {

				Asset.javascript ( item, {
					events: {
						load: check
					}
				});
			}
			
		});
		
		return;
	}

	
	// check https://github.com/oskarkrawczyk/dependon/blob/master/dependon.js
	/**
	 * JImport
	 *
	 * <code>
	 * 	JImport({
	 *			name: 'modal',
	 *			test: function() { return document.getElement('a.modal') }, 
	 *			requireJs: ['modal.js', 'modal2.js'], 
	 *			requireCss: 'modal.css'], 
	 *			success: function() { window.modal.init(); }
	 *	}, 'modal');
	 * </code>
	 *
	 * @param	object	library to load
	 * @param	string	library name
	 * @param	boolean	True on success, false on failure
	 */
	JImport = function(lib, library) {
		register 	= library || lib['name'] || false;

		// check condition
		if (typeof lib['test'] == "undefined" || lib['test']() != false ) {
			
			// check if registered
			if (register == false || typeof Joomla.registered[library] == "undefined" ){ // namespace ref

				/*
				// depends
				if (typeof lib['depends'] == "object" && lib['depends'] instanceof Array) {
					Array.each(lib['depends'], function(depend, i) {
						if (typeof behaviors[depend] == "object") {
							JImport(behaviors[depend], depend);
						}
					});
				}
				*/
			
				// load js & css
				if (typeof lib['require'] != "undefined" && lib['require']) {
					JLoad(lib['require'], lib['success'] || null);
				} else {
					lib['success']();
				}

				// register in namespace & pass there
				if (register != false) {
					window.Joomla.registered[register] = lib['success'] || true;  // namespace ref
				}
				
			} else if (typeof lib['success'] == "function") {
				lib['success']();
			}
			return true;
		// no need to load
		} else {
			return false;
		}
		
	};
	
	/* */
	// Joomla.init
	(function(behaviors){
		for (library in behaviors) {
			JImport(behaviors[library], library);
		}
	})(behaviors);
	/* */
	
	/* *
	// loop
	JBehaviors = function(behaviors) {
		for (library in behaviors) {
			JImport(behaviors[library], library);
		}
	}
	// startup
	JBehaviors(behaviors);
	/* *
	
	
	/*
	

	// JHTML::_( 'behavior.formvalidation' );
	if (document.getElement('form.form-validate')) {
		
		if (typeof JFormValidator != "function") {
			
			// check if MT Asset is on
			if (typeof Asset == "object") {
				Asset.javascript( (URLS.base || '') + 'media/system/js/validate.js', {
					events : {
						'load': function() { formvalidator_plus(); }
					}
				});
			}
		} else {
			formvalidator_plus();
		}
	}
	
	
	
	// MEDIABOXaDVANCED LOADER
	// JHTML::script( 'mediaboxAdv.js', 'media/ext_mediaboxAdv/js/' );
	// JHTML::stylesheet( 'mediaboxAdv.css', 'media/ext_mediaboxAdv/css/');
	if (
		typeof Joomla.behavior['MediaboxAdv'] == "undefined"
		&& (document.getElement('a[rel^=lightbox]') && typeof Mediabox == "undefined")
	){
		Asset.javascript( (URLS.base||'') + 'media/tool_mediaboxAdv/js/mediaboxAdv-1.3.4b-yc.js', {'defer': "defer"});// ga.async = true;
		// Asset.css( (URLS.base||'') + 'media/tool_mediaboxAdv/css/mediaboxAdvBlack21.css', {});
		Asset.css( (URLS.template) + 'css/gallery.css', {});
		
		Joomla.behavior['Mediabox'] = true;
	}
	*/
});
