/* Utility functions */
/* (C) 2008 Alexandru Ionut Lixandru */
/* Email: alex.lixandru@gmail.com */
/* You may use, copy, distribute, modify... do whatever you want with this file */
/* For commercial applications, this notice should (ideally) stay intact */


if( typeof(ie) === 'undefined') ie = 0;
/**
 * AddSearch Provider
 */
function addProvider(url) {
	try {
		window.external.AddSearchProvider(url);
	} catch (e) {
		alert("Trebuie sa aveti minim Firefox 2 si/sau Internet Explorer 7 pentru a putea instala");
	return;
	}
}

/**
 *
 */
function toggle( eid ) {
	var elem = document.getElementById( eid );
	if ( $( elem ).hasClass( 'visible' ) ) {
		$( elem ).removeClass( 'visible' ); 
		$( elem ).addClass( 'hidden' );
	} else { 
		$( elem ).removeClass( 'hidden' ); 
		$( elem ).addClass( 'visible' ); 
	}
}
/**
 * Hides or displays all elements
 */
function toggleall( show ) {
	if( show ) {
		$( '.help-faq' ).removeClass( 'hidden' ); 
		$( '.help-faq' ).addClass( 'visible' );
	} else {
		$( '.help-faq' ).removeClass( 'visible' ); 
		$( '.help-faq' ).addClass( 'hidden' );
	}
}

/**
 * Redirects to the specified URL
 */
function navigateTo( url ) {
	window.location = url;
	return false;
}


/**
 * Utility function to add an event listener
 */
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}


/**
 * Sets a certain opacity for an element (cross browser) 
 */
function setOpacity(object, opacity, jqueryStyle ) {
	if( !object ) return false;
	if( jqueryStyle ) {
		object.css( 'opacity', opacity );
		object.css( 'MozOpacity', opacity );
		object.css( 'KhtmlOpacity', opacity );
		object.css( 'filter', "alpha(opacity=" + parseInt(opacity * 100 ) + ")" );
	} else {
		object.style.opacity = opacity;
		object.style.MozOpacity = opacity;
		object.style.KhtmlOpacity = opacity;
		object.style.filter = "alpha(opacity=" + parseInt(opacity * 100 ) + ")";
	}
}


/**
 * Prints a HTML hyperlink to the specified email address in attempt to prevent theft and spam
 * @param 	outputText 	text to display
 * @param 	address 		email ID
 * @param 	provider 		email provider
 * @param 	attributes 		extra HTML attributes like ' target="_blank" '
 */
function printEmail( outputText, address, provider, attributes ) {
	if( !attributes ) attributes = '';
	document.write( '<a href="mailto:' + address + '&#64;' + provider + '" ' + attributes + '>' + outputText + '</a>' );
}


/**
 * Add-on function for form validation [might not be used] 
 */
function validateThisForm( fo ) {
		if ( typeof( error_msg ) === 'undefined' ) { error_msg = 0; }
		return validateForm( fo.id, error_msg, 0, 'form-field-error' );
}

/**
 * Validates a form submitted by the user
 * @param 	fid 		form ID
 * @param 	errm 	json object containing error messages for each form field
 *								example of object: err = { name: { required:'this is required', fullname:'please provide first and last name' } }
 * @param 	defm 	string with the default error message in case errm does not contain messages for some fields
 * @param	errc		class to be assigned to faulty elements
 * @return 	true | false
 * @author 	Alexandru Lixandru (alex.lixandru@gmail.com) 
 */
function validateForm( fid, errm, defm, errc ) {

	if ( ! fid ) return false;
	var default_msg = 'Eroare! Va rugăm completati toate câmpurile obligatorii pentru a putea merge mai departe.';
	var error_class = 'form-field-error';
	
	// types of validation
	var x_submitted = 'x-submit-flag';
	if( document.getElementById('submitted') && document.getElementById('submitted').value != 1) return false;
	
	var v_required = 'v-required';
	var v_fullname = 'v-fullname';
	var v_email = 'v-email';
	var v_password = 'v-password';
	var v_length = 'v-exactlength';
	var v_minlength = 'v-minlength';
	var v_maxlength = 'v-maxlength';
	var v_nospace = 'v-nospace';
	var v_value = 'v-value';
	var v_username = 'v-username';
	//var v_digits = 'numeric';
	//var v_text = 'letters';
	
	
	// this is the function that alerts the user
	Alert = function( inp ) {
		// determine the error message
		var msg = '';
		if ( errm )
		try { 
			// an error array might be: err = { name: { required:'this is required', fullname:'please provide first and last name' } }
			// it might be as well: err = { name: 'incorrect name' } - without separation per validation type
			var omsg = eval( 'errm.' + inputs[i].id );
			if( typeof( omsg ) !== 'object' ) { msg = omsg; }
			else { msg = eval( 'omsg.' + inp.substr(2) ); }
		} catch (e) { msg = default_msg; }
		if( !msg ) { msg = default_msg; }
		
		// prompt the user
		alert( msg );
		
		// enable the form, put the focus on the faulty object and exit
		fobj.disabled = false;
		inputs[i].focus();
		$( inputs[i] ).addClass( error_class );
		return false;
	};

	// set up variables
	if ( defm ) { default_msg = defm; }
	if ( errc ) { error_class = errc; }
	//if( typeof( fid ) != 'string' ) fid = fid.id;
	var fobj = document.getElementById( fid );
	fobj.disabled = true;
	var inputs = new Array();
	var tinp = fobj.getElementsByTagName( 'INPUT' );
	for( i = 0; i < tinp.length; i++ ) inputs.push( tinp[i] );
	tinp = fobj.getElementsByTagName( 'TEXTAREA' );
	for( i = 0; i < tinp.length; i++ ) inputs.push( tinp[i] );
	tinp = fobj.getElementsByTagName( 'SELECT' );
	for( i = 0; i < tinp.length; i++ ) inputs.push( tinp[i] );
	
	// loop thru form fields
	for( i = 0; i < inputs.length; i++ ) {
		var validation = inputs[i].getAttribute( 'class' );
		if( !validation && inputs[i].attributes['class']) validation = inputs[i].attributes['class'].value;
		var field = inputs[i].value;
		field = field.replace( /\s+$/, '');
		field = field.replace( /^\s+/, '');
		
		// required
		vreg = new RegExp( v_required, 'i');
		if ( vreg.test( validation )  ) {

			// this is for checkboxes and radio buttons only
			if( inputs[i].type === 'checkbox' || inputs[i].type === 'radio') 
				if ( !inputs[i].checked ) return Alert( v_required );
			if( inputs[i].type === 'textarea' )
				if ( inputs[i].text == '') return Alert( v_required );
			if ( !field ) return Alert( v_required );
		}
		
		// fullname
		vreg = new RegExp( v_fullname, 'i');
		if ( vreg.test( validation )  ) {
			var atoms = field.split( ' ' );
			if ( atoms.length < 2 ) return Alert( v_fullname );
		}
		
		// email
		vreg = new RegExp( v_email, 'i');
		if ( vreg.test( validation )  ) {
			var ereg = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$/i;
			if ( ! ereg.test ( field ) ) return Alert( v_email );
		}
		
		// nospace
		vreg = new RegExp( v_nospace, 'i');
		if ( vreg.test( validation )  ) {
			var ereg = /\s/i;
			if ( ereg.test ( inputs[i].value ) ) return Alert( v_nospace );
		}
		
		// password
		vreg = new RegExp( v_password, 'i');
		if ( vreg.test( validation )  ) {
			var pconfirm = document.getElementById( 're' + inputs[i].id );
			if ( pconfirm ) {
				var pcvalue = pconfirm.value; pcvalue = pcvalue.replace( /\s+$/, ''); pcvalue = pcvalue.replace( /^\s+/, '');
				if ( field != pcvalue ) {
					// highlight the other password field too
					$( pconfirm ).addClass( error_class );
					return Alert( v_password );
				}
			}
		}
		
		// value:x
		vreg = new RegExp( v_value + '\:(\\w+)' );
		var mreg = vreg.exec( validation );
		if ( mreg ) {
			if ( mreg.length && mreg[1] && field != mreg[1] ) {
				return Alert( v_value );
			}
		}
		
		// exactlength:x
		vreg = new RegExp( v_length + '\:(\\d+)' );
		var mreg = vreg.exec( validation );
		if ( mreg ) {
			if ( mreg.length && mreg[1] && field.length != mreg[1] ) {
				return Alert( v_length );
			}
		}
		
		// minlength:x
		vreg = new RegExp( v_minlength + '\:(\\d+)' );
		var mreg = vreg.exec( validation );
		if ( mreg ) {
			if ( mreg.length && mreg[1] && field.length > 0 && field.length < mreg[1] ) {
				return Alert( v_minlength );
			}
		}
		
		// maxlength:x
		vreg = new RegExp( v_maxlength + '\:(\\d+)' );
		var mreg = vreg.exec( validation );
		if ( mreg ) {
			if ( mreg.length && mreg[1] && field.length > mreg[1] ) {
				return Alert( v_maxlength );
			}
		}
		
		// username ?
		vreg = new RegExp( v_username, 'i');
		if ( vreg.test( validation )  && field.length) {
			var ereg = /^[a-z]+[0-9]*[a-z]/i;
			if ( !ereg.test ( inputs[i].value ) ) return Alert( v_nospace );
		}
		
		$( inputs[i] ).removeClass( error_class );
	}
	
	fobj.disabled = false;
	return true;
}