// JavaScript Document

/// validation functions code starts -------------------------------------------------------------


// need to work
// must be in a form with id=form1
// window.addEvent('domready', addeventallFields); must be included on page
// input should have class="validateimage" second word is the type of validation - to add another style add a " " eg: class="validateimage formBGwhite"
// input need id
// submit button needs to be an image :<img src="../../Scripts/images/saveboxsave.gif" border="0"  onclick="checkallFields()"/>

function redirect(){
	window.location = "client_home.php";
}

function checkallFields(){
	failed = 0;	
	//fieldarray = $('input.validate');
	//fieldarray = $('form1').getElements('input[class^=validate]');
	fieldarray = $ES('input[class^=validate]')
	
	fieldarray.each(function(el){
							  
		classtype = el.className;
		
		if(classtype.indexOf(" ") != -1){
		stringarray = classtype.split(" ");	
		classtype = stringarray[0];
		}
		classtype = classtype.replace("validate", "");
		
		if(!validateval(el.id ,classtype)){
			failed++;	
		};
						  
	})
	//alert(failed)
	if(failed < 1){
		$('form1').submit();
	}else{
		
		errordiv = document.getElementById('errormessage');
		if(errordiv != null){
			document.getElementById('errormessage').innerHTML="Please fill in missing fields";
		}
		
	}
 
}

function addeventallFields(){
	failed = 0;	
	//fieldarray = $$('.^=validate');
	theform = $('form1');
	//fieldarray = theform.getElements('input[class^=validate]');
	fieldarray = $ES('input[class^=validate]')
	
	
	fieldarray.each(function(el){
		el.addEvent("mouseout", function(event){
			checkfield(el)
		})
	});
	
	fieldarray.each(function(el){
		el.addEvent("keydown", function(event){
			checkfield(el)
		})
	});
	
	fieldarray.each(function(el){
		el.addEvent("change", function(event){
			checkfield(el)
		})
	});
	
 
}

function checkfield(el){
	classtype = el.className;
				
				
				if(classtype.indexOf(" ") != -1){
				stringarray = classtype.split(" ");	
				classtype = stringarray[0];
				}
				
				classtype = classtype.replace("validate", "");
				
				if(!validateval(el.id ,classtype)){
					failed++;	
				};
}
	
	
	
function validateval(ojbid ,type){
	errorcode = 0;
	var ojb = $(ojbid);

	
	switch(type){
		case "name":
		if(ojb.value == ""){
		errorcode = 9;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "txarea":
		if(ojb.value == ""){
		errorcode = 16;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "email":
		checkemailaddress(ojb.value)
		if(!IsMatchingEmailAddress(ojb.value)){
			errorcode = 2;
			outputerror(ojb, errorcode);
		}
		break; 
		
		
		case "money":
		
		/* strips any commas*/
		moneyvalue = stripCommas ($(ojbid).value);
		
		if(!isInteger(moneyvalue)){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		if(moneyvalue.length < 4){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		break; 
		
		case "number":
		if(!isInteger(ojb.value)){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		if(ojb.value.length < 4){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		break; 
		
		case "date":
		if(!isValidDate(ojb.value)){
			errorcode = 3;
			outputerror(ojb, errorcode);
		}
		break; 
		
		
		case "checkbox":
		if(ojb.checked == ""){
			errorcode = 4;
			outputerror(ojb, errorcode);
		}
		break; 
		
		case "radio":
		if(ojb.value == ""){
			errorcode = 14;
			outputerror(ojb, errorcode);
		}
		break; 
		
		case "phone":
		
		phonevalue = stripPhone ($(ojbid).value);
		
		if(!isInteger(phonevalue)){
			errorcode = 15;
			outputerror(ojb, errorcode);
		}
		if(phonevalue == ""){
		errorcode = 15;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "internationalphone":
		if(checkInternationalPhone(ojb.value)){
			errorcode = 6;
			outputerror(ojb, errorcode);
		}
		if(ojb.value == ""){
		errorcode = 1;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "image":
		if(!IsMatchingImage(ojb.value)){
		errorcode = 7;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "nickname":
		checknickname(ojb.value)
		if(ojb.value == ""){
		errorcode = 10;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "password1":
		if(ojb.value == ""){
		errorcode = 11;
		outputerror(ojb, errorcode);
		}
		break; 
		
		case "password":
		if(ojb.value != $('pass1').value){
		errorcode = 8;
		outputerror(ojb, errorcode);	
		}
		if(ojb.value == ""){
		errorcode = 12;
		outputerror(ojb, errorcode);
		}
		break; 
		
		default:
		if(ojb.value == ""){
		errorcode = 1;
		outputerror(ojb, errorcode);	
		}
		break; 
	
	}
	if(errorcode == 0){
		
	 	outputerror(ojb, 0);
		return true;
	}else{
		return false;
	}
	
}

function errorlist(num){
	var spaces = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
	error = new Array();
	
	error[0] = "";
	error[1] = spaces+"Value required.";
	error[2] = spaces+"Please enter a valid email.";
	error[3] = spaces+"Please enter a valid date e.g. yyyy-mm-dd.";
	error[4] = spaces+"Please check box.";
	error[5] = spaces+"Please enter number.";
	error[6] = spaces+"Please enter correct international telephone number.";
	error[7] = spaces+"Select an image.";
	error[8] = "Your Passwords do not match.";
	error[9] = spaces+"Please enter you name";
	error[10] = spaces+"Please enter a nickname";
	error[11] = spaces+"Please enter a password";
	error[12] = spaces+"Please verify your password";
	error[13] = spaces+"Please enter a number to the nearest thousand";
	error[14] = spaces+"Please choose payment method";
	error[15] = spaces+"Enter valid phone number e.g. 028 1234 1234";
	error[16] = spaces+"This field must be completed.";
	

	
	return error[num];
	
}

function IsMatchingImage(str){
    var myImage = /^.*(\.(gif|jpg|bmp|GIF|JPG|BMP))$/;
    return myImage.test(str)
}

function IsMatchingEmailAddress(str){
    var myRegExp = /[a-z0-9-]{1,30}@[a-z0-9-]{1,65}.[a-z]{3}/ ;
    return myRegExp.test(str)
}

function isValidDate(sText) {
		var reDate = /(?:19|20\d{2})\-(?:0[1-9]|1[0-2])\-(?:0[1-9]|[12][0-9]|3[01])/;
        return reDate.test(sText);
}

function outputerror(ojb, errornumber){
	var ojbitem = $(ojb).getParent();
	var ojbitemstyle = $(ojb).getParent().getParent().getParent();
	
	errordiv = $('error'+ojb.id)
	//alert(errordiv)
	if(errordiv == null){
		if(errornumber != 0){
			var errordiv = new Element('div', {'id':'error'+ojb.id}).setStyles('float:left; font-weight:bold; background-image:url(../images/error.jpg); background-repeat:no-repeat; padding:6px 0 4px 0; font-size:11px; color:#FF0000; margin-left:10px;');
			errordiv.setHTML(errorlist(errornumber))
			//$('submit').disabled="disabled";
			errordiv.injectAfter(ojbitem);
			ojbitemstyle.setStyles('color:#FF0000;')
		}
	}else{
		if(errornumber != 0){
			errordiv.setHTML(errorlist(errornumber))
			ojbitemstyle.setStyles('color:#FF0000;')
			//$('submit').disabled="disabled";
		}else{
			errordiv.setHTML("")
			ojbitemstyle.setStyles('color:#000000;')
			//$('submit').disabled="";
		}
	}
}

function stripPhone (numString){
	
	value = numString;
	value = value.replace(/ /g, "");
    return value;
	
}

function stringFilter (input) {
				s = input;
				filteredValues = ", "; // Characters stripped out
				var i;
				var returnString = "";
				for (i = 0; i < s.length; i++) { // Search through string and append to unfiltered values to returnString.
				var c = s.charAt(i);
				if (filteredValues.indexOf(c) == -1) returnString += c;
				}
			return returnString; 
}

function stripCommas(numString) {
	value = numString;
	value = value.replace(/,/g, "");
	value = value.replace(/ /g, "");
    return value;
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 11;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}


/// validation functions code ends -------------------------------------------------------------





function navchange(page){
	
	$('menuhome').removeClass('navitem');
	$('menuaboutus').removeClass('navitem');
	$('menuservices').removeClass('navitem');
	$('menupeople').removeClass('navitem');
	$('menuclient').removeClass('navitem');
	$('menucase').removeClass('navitem');
	$('menublogs').removeClass('navitem');
	$('menucontact').removeClass('navitem');
	
	$('menuhome').removeClass('navitem_current');
	$('menuaboutus').removeClass('navitem_current');
	$('menuservices').removeClass('navitem_current');
	$('menupeople').removeClass('navitem_current');
	$('menuclient').removeClass('navitem_current');
	$('menucase').removeClass('navitem_current');
	$('menublogs').removeClass('navitem_current');
	$('menucontact').removeClass('navitem_current');
	
	/* ----------------------------------------------- */
	
	if(page=='home'){
		$('menuhome').addClass('navitem_current');
		document.title = "63G Communications  | home | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menuhome').addClass('navitem');
	}
	
	if(page=='aboutus'){
		$('menuaboutus').addClass('navitem_current');
		document.title = "63G Communications  | about us | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menuaboutus').addClass('navitem');
		
	}
	
	
	if(page=='services'){
		$('menuservices').addClass('navitem_current');
		document.title = "63G Communications  | services | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menuservices').addClass('navitem');
	}
	
	if(page=='people'){
		$('menupeople').addClass('navitem_current');
		document.title = "63G Communications  | people | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menupeople').addClass('navitem');
	}
	
	if(page=='client'){
		$('menuclient').addClass('navitem_current');
		document.title = "63G Communications  | client | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menuclient').addClass('navitem');
	}
	
	if(page=='case'){
		$('menucase').addClass('navitem_current');
		document.title = "63G Communications  | case studies | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menucase').addClass('navitem');
	}
	
	if(page=='blogs'){
		$('menublogs').addClass('navitem_current');
		document.title = "63G Communications  | blogs | +44 (0)20 7549 5800 info@63G.com";
		
	}else{
		$('menublogs').addClass('navitem');
	}
	
	if(page=='contact'){
		$('menucontact').addClass('navitem_current');
		document.title = "63G Communications  | contact | +44 (0)20 7549 5800 info@63G.com";
	}else{
		$('menucontact').addClass('navitem');
	}
	
}
	
window.addEvent('domready', function() {
var fade = new Fx.Style('floater', 'opacity' ,{duration:500});//animate new page bio


$ES('.popup').addEvent('click', function(e) { //find all 'class=staffurl' and add an onclick event
	e = new Event(e).stop();
	
 url = this.href; //pull url from a href (a tag only for SEO)
	urllinks.push(this.href);
	id = this.rev;
	title = this.title;
	
	if(url != "#" && url != ""){
		if($('floater').getStyle('display') != 'block'){
		
			$('floater').setStyle('display','block');
			
			new Ajax(url, {
				method: 'get',
				update: $('floater'),
				evalScripts: true  //for the scroll bar in the new page loaded
			}).request();
			
			fade.start(0, 1); // animate
		}else{
			changepage(url,id,title)
		}
	}
		
});

});

addhistoryvar = 1;

function changepage(url,id,title){
var fadeonly = new Fx.Style('floater', 'opacity' ,{duration:500}); //animate with no oncomplete

var fadeajax = new Fx.Style('floater', 'opacity' ,{//animate with oncomplete
duration:500,
	//on complete loading page 
	onComplete: function() {
			
		new Ajax(url, {
		method: 'get',
		update: $('floater'),
		evalScripts: true,
		onComplete: function() {
		//on complete fade in using ainmation with on oncomplete
			if(addhistoryvar == 1){
				dhtmlHistory.add('t='+id,title);
			}
			fadeonly.start(0, 1);
		}
	}).request();
	
		}
});
	
	fadeajax.start(1, 0)
	
}


//// ------------------------------- history for ajax --------------------------------------------
function historyChange(newLocation, historyData) {
	window.addEvent('domready', function(){
	
	if(newLocation == 0){
		addhistoryvar = 0;
	}else{
		addhistoryvar = 1;
	}

	if(newLocation != 0){
	hash = getUrlVars(newLocation)
		if(hash.length > 0){
   	otherpage = hash['t'];
		}
	}else{
		hash = getUrlVars()
		if(hash.length > 0){
   	otherpage = hash['t'];
		}
	}
	
	if(otherpage!='' && otherpage!= undefined){
		url = urllinks[otherpage];
		if(url != ''){
			changepage(url);
		}	
	}
		addhistoryvar = 1;
	})
};

function getUrlVars(str){
	var vars = [], hash;
	if(str == undefined){
		if(window.location.href.indexOf('?') > 0){
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		}else{
		var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
		}
	}else{
		var hashes = str.split('&');
	}
	
	for(var i = 0; i < hashes.length; i++){
	hash = hashes[i].split('=');
	vars.push(hash[0]);
	vars[hash[0]] = hash[1];
	}
	return vars;
}

//// ------------------------------- end history for ajax --------------------------------------------

oldheight = 0;

function ResizeElements(){
	windheight = window.getScrollHeight();	
	footerheight = $('footer').getStyle('height').toInt() + 38;
	perfectHeight = (windheight - 253) - footerheight;
	
	if(oldheight != 0){
		contentheight = oldheight;
	}else{
		contentheight = $('main_content').getStyle('height').toInt();
	}
	if(window.ie){
		addon = 28	
	}else{
		addon = 0
	}
	
	if(contentheight < perfectHeight){
		if(oldheight == 0){oldheight = contentheight;}
		$('main_content').setStyle('height', perfectHeight);	
		if($('right_sidebar')){
			$('right_sidebar').setStyle('height', perfectHeight +104 + addon);
		}
	}else{
		if($('right_sidebar')){
			$('right_sidebar').setStyle('height', contentheight +104 + addon);
		}
	}

		
}

//window.addEvent('domready', function() {
//	$('logout').addEvent('click', function(e) {
//		var e = new Event(e);
//		e.stop();
//		showLogin('logout');
//		
//	});						 
//});

function showLogin(parObj) {
	var obj = document.getElementById('login');
	if(obj.style.display == 'none'){
		obj.style.display = 'block';
		document.getElementById(parObj).className = 'logout_flatten';
	}else{
		obj.style.display = 'none';
		document.getElementById(parObj).className = 'logout';
	}
}

function showRegister() {
	var url = 'inc_register.php';
	new Ajax(url, {
		method: 'get',
		evalScripts: true,
		update: $('login')
	}).request();
}

function showReset() {
	var url = 'inc_reset.php';
	new Ajax(url, {
		method: 'get',
		evalScripts: true,
		update: $('login')
	}).request();
}

function backToLogin() {
		var url = 'inc_login.php';
	new Ajax(url, {
		method: 'get',
		evalScripts: true,
		update: $('login')
	}).request();
}
function submitlogin(){
	$('formlogin').send({
		update: $('login'),
		onComplete: function() {
			//alert();
			//if($('login').innerHTML=="You are now logged in."){
			//window.location = "client_home.php";
			//}
		}
	});
}

function addloginevent(){
if($('formlogin')){
		$('formlogin').addEvent('submit', function(e){
		e = new Event(e).stop();
		var myValidator = new fValidator(this);
		if(($('Username').value=="")||($('Password').value=="")){
				//----empty so dont send;
		}else{
		submitlogin();
		}
	})
	}
}
window.addEvent('domready', function(){
	addloginevent()
})


function submitregister(){
	$('form2').send({
		update: $('login'),
		onComplete: function() {
			//alert();
			if($('login').innerHTML=="You are now logged in."){
			//window.location = "client_home.php";
			}
		}
	});
}


function addregisterevent(){
if($('form2')){
		$('form2').addEvent('submit', function(e){
		e = new Event(e).stop();
		
		//var myValidator = new fValidator(this);
		
		if($('Email_side').value==""){
				//----empty so dont send;
		}else{
		submitregister();
		}
	})
	}
}
window.addEvent('domready', function(){
	addregisterevent()
})

function dropDown(obj){
	var ID = obj.id;
	var theImage = document.getElementById(ID+'_image');
	var theDiv = document.getElementById(ID+'_dropdown');
	
	if(theDiv.style.display == 'none'){
		theDiv.style.display = 'block';
		theImage.src = 'images/check_arrow_down.gif';
	}else{
		theDiv.style.display = 'none';
		theImage.src = 'images/check_arrow.gif';
	}
}

function optionChange(obj) {
	var theParent = obj.getParent().getParent();
	//alert(theParent.style.backgroundColor);
	if(obj.checked == true){
		theParent.style.backgroundColor = '#ECECEC';
	}else{
		theParent.style.backgroundColor = '#f8f8f8';
	}
	
}
//window.addEvent('domready', function(){
//	if(document.getElementById("formlogin") != null){
//	var myValidator = new fValidator(id);
//	}
//	
//})


window.addEvent('load', function(){
	if(!$E('body').hasClass('game') && !$('ContactForm')){
		ResizeElements();
	}
})
//if(!$E('body').hasClass('game')){
//	window.onresize = ResizeElements;
//}
function checkEmail(emailAdd, errorDiv, submitButton){
    var myRegExp = /[a-z0-9-]{1,30}@[a-z0-9-]{1,65}.[a-z]{3}/ ;
    var theResult = myRegExp.test(emailAdd);
	if(theResult == false){
	//document.getElementById(submitButton).disabled = true;
	document.getElementById(errorDiv).innerHTML = 'Invaild Email';
	return false;
	}else{
	document.getElementById(errorDiv).innerHTML = '';
	return true;
	}
}
	function senddetails(){
	
	$('formreg').send({
		update: 'login',
		evalScripts: true,
		onComplete: function() {
		//$('returnmessage').setHTML("Welcome, to your Content management");
		}
	});
	}