
// INPUT SWITCH CONTENT ON FOCUS
Element.implement({
	inputHint : function(val){
		switch(this.get('tag')){
			case 'form':
				this.getElements('input[type="text"],textarea').inputHint(val);
				return this;
			case 'input':
			case 'textarea':
				this.store('default',(val||this.get('value')));
				this.addEvents({
					'focus':function(){
						if(this.get('value') == this.retrieve('default')){
							this.set('value', '');
						}
					},
					'blur':function(){
						if(this.get('value').clean() == ''){
							this.set('value', this.retrieve('default'));
						}
					}
				}).fireEvent('blur');
			default: return this;
		}
	}
});


// ADD TO FAVORITES
var urlAddress = "http://www.evolvetele.com";
var pageName = "Evolve Telecommunications"; 

function addToFavorites() { 
	if (window.external) {
		window.external.AddFavorite(urlAddress,pageName) 
	} 
	else { 
		alert("Sorry! Your browser doesn't support this function."); 
	}
}


window.addEvent('domready', function() {
	
	//EXTERNAL LINKS			
	$(document.body).getElements('a[rel=external]').set('target', '_blank');	
	
	// BACKGROUND IMAGE CACHE
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
	
	// SMOOTH SCROLL PAGE
 	new SmoothScroll({ duration:700 }, window);
	
	// TOOL TIPS														 
	var tooltip = new Tips($$('.tooltip'));
	
	// INPUT SWITCH CONTENT ON FOCUS
	$('site_search').inputHint();
		
	// HOME SLIDESHOW
	//new slideshow('menu', 'pictures', 'loading', {transition: 'fade', auto: true});														 

});



/*
* Validates data types below using regular expressions
* 
*		-	email
*		-	date
*		-	mobile
*		-	postcode
*		-	password
*/
function validateType(type, val){
	switch(type){
		case 'email':
			var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
			break;
		case 'date':
			var pattern = /^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))$/;
			break;
		case 'mobile':
			var pattern = /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/;
			break;
		case 'telephone':
			var pattern = /^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
			break;
		case 'postcode':
			var pattern = /^((([A-PR-UWYZ](\d([A-HJKSTUW]|\d)?|[A-HK-Y]\d([ABEHMNPRVWXY]|\d)?))\s*(\d[ABD-HJLNP-UW-Z]{2})?)|GIR\s*0AA)$/;
			break;
		case 'password':
			var pattern = /(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$/;
			break;
		default:
			break;
	}
	return pattern.test(val); 
}

/*
*  Validates form content
*/
function validateForm(frm,reporting_div_id){
	/*------------------------------------------*/
	/*  CHECK ALL REQUIRED FIELDS HAVE A VALUE  */
	/*------------------------------------------*/
	//alert(frm);
	var errors = [];
	var req;
	var error_string = '';
	//  Check for required hidden field so we know which fields are mandatory
	if(typeof frm.required==undefined){
		alert('Required hidden field missing');
		return false;
	}
	//  Check all required fields exist and have a value
	req = frm.required.value.split(",");
	/*var e = '';
	for(var o=0; o<frm.elements.length; o++){
		e+=frm.elements[o].name+' : '+frm.elements[o].value+'\n';
	}
	alert(e);*/
	for(var x=0; x<req.length; x++){
		if(typeof frm.elements[req[x]]=="undefined")
			errors[errors.length] = req[x] + ' field doesn\'t exist';
		else{
			if(frm.elements[req[x]].value=='')
				errors[errors.length] = 'the ' + req[x] + ' field must contain a value';
		}
	}
	if(document.getElementById('terms')){
		if(frm.elements['terms'].checked==false && in_array('terms', req)){
			errors[errors.length] = 'you must accept the terms and conditions to continue';
		}
	}
	//  Output errors if there are any
	if(errors.length>0){
		if(reporting_div_id!==false){						//  Either, print to screen within supplied <div>.....
			for(var x=0; x<errors.length; x++)
				error_string += '<li>' + errors[x] + '</li>';
			document.getElementById(reporting_div_id).innerHTML = '<ul class="error">' + error_string + '</ul>';
		}
		else{																			//	Or, show in alert box
			for(var x=0; x<errors.length; x++)
				error_string += '- ' + errors[x] + "\n";
			alert(error_string);
		}
		return false;
	}
	/*--------------------------------------------------------*/
	/*  PERFORM VALIDATION OF FIELD DATA BASED ON FIELD NAME  */
	/*--------------------------------------------------------*/
	var elems = frm.elements;
	for(var x=0; x<elems.length; x++){
		if(elems[x].name!='required' && in_array(elems[x].name, req)){
			switch(true){
				case elems[x].name.search('email')!=-1:
					if(!validateType('email', elems[x].value))
						errors[errors.length] = 'Invalid email address';
					break;
				case elems[x].name.search('date')>-1:
					if(!validateType('date', elems[x].value))
						errors[errors.length] = 'Invalid date (DD/MM/YY)';
					break;
				case elems[x].name.search('mobile')>-1:
					if(!validateType('mobile', elems[x].value))
						errors[errors.length] = 'Invalid mobile phone number';
					break;
				case elems[x].name.search('telephone')>-1:
					if(!validateType('telephone', elems[x].value))
						errors[errors.length] = 'Invalid phone number';
					break;
				case elems[x].name.search('postcode')>-1:
					if(!validateType('postcode', elems[x].value))
						errors[errors.length] = 'Invalid postcode';
					break;
				/*case elems[x].name.search('password')>-1:
					if(!validateType('password', elems[x].value))
						errors[errors.length] = 'Invalid password (must contain 1 number, 1 capital letter and be between 6 and 15 characters)';
					break;*/
				default:
					break;
			}
		}
	}
	//  Output errors if there are any
	if(errors.length>0){
		if(reporting_div_id!==false){						//  Either, print to screen within supplied <div>.....
			for(var x=0; x<errors.length; x++)
				error_string += '<li>' + errors[x] + '</li>';
			document.getElementById(reporting_div_id).innerHTML = '<ul class="error">' + error_string + '</ul>';
		}
		else{																			//	Or, show in alert box
			for(var x=0; x<errors.length; x++)
				error_string += '- ' + errors[x] + "\n";
			alert(error_string);
		}
		return false;
	}
	return true;
}


/*
* Replaces all occurrences of search in haystack with replace  
*/
function str_replace(search, replace, subject, count) {
	var 	i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
				f = [].concat(search),
				r = [].concat(replace),
				s = subject,
				ra = r instanceof Array, sa = s instanceof Array;
	s = [].concat(s);
	if (count) {
		this.window[count] = 0;
	}
	for (i=0, sl=s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		for (j=0, fl=f.length; j < fl; j++) {
			temp = s[i]+'';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
			if (count && s[i] !== temp) {
				this.window[count] += (temp.length-s[i].length)/f[j].length;
			}
		}
	}
	return sa ? s : s[0];
}

/*
* Equivalent to php in_array function
*/
function in_array(needle, haystack, argStrict) {
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	}
	else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}
	return false;
}

/*
* Returns true if variable is an array  
*/
function is_array( mixed_var ) {
    var key = '';
    var getFuncName = function (fn) {
			var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
			if(!name) {
				return '(Anonymous)';
			}
			return name[1];
    };

    if (!mixed_var) {
    	return false;
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    if (typeof mixed_var === 'object') {
			if (this.php_js.ini['phpjs.objectsAsArrays'] &&  // Strict checking for being a JavaScript array (only check this way if call ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays)
				(
				(this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase &&
								this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase() === 'off') ||
						parseInt(this.php_js.ini['phpjs.objectsAsArrays'].local_value, 10) === 0)
				) {
				return mixed_var.hasOwnProperty('length') && // Not non-enumerable because of being on parent class
												!mixed_var.propertyIsEnumerable('length') && // Since is own property, if not enumerable, it must be a built-in function
														getFuncName(mixed_var.constructor) !== 'String'; // exclude String()
			}
			if (mixed_var.hasOwnProperty) {
				for (key in mixed_var) {
					// Checks whether the object has the specified property
					// if not, we figure it's not an object in the sense of a php-associative-array.
					if (false === mixed_var.hasOwnProperty(key)) {
						return false;
					}
				}
			}
			// Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
			return true;
    }
    return false;
}
