// January 08 2010
// V-Local
// Author:Aaron Buffie
//
//

//Globals

	// Create homeValidation tracking variables
	var homeValid = true;// - sets to false if any field invalid
	var homeValidationMessage = 'Please correct the following errors:\r\n';// - start of invalid message
	var homeValidForm;// - holds ture or false for form being validated
	var homeValidFields = [];// - tracks vaild fields
	var homeinValidFields = [];// - tracks invalid fields
	var validField;
	
	//regex varaibles - for validateing fileds
	var homeValidEmail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	var formString = /^[a-zA-Z]+$/;
	var formNum = /^[0-9]+$/;
	var formUser = /^[a-zA-Z0-9]+$/;
	var usReg = /^\d{5}?$/;//U.S zip
	var caReg = /[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/i;//Canada zip
	
	//invalid and valid field css settings
	var homeinValidTxt = "#f6fc00";
	var homeinValidBorder = "2px solid #ff0000";
	var homeValidTxt = "#ffffff";
	var homeValidBorder = "2px inset #cc0000";
	
	//More signup form globals
	var limit = 0;// button limit counter
	var maxLimit = 8;// max number of buttons allowed
	var lockedFields = [];//save unselected check boxes for locking and unlocking if limit is reached
	var formLocked = false;


	

//End Globals






//===== Custom form functions ==========//



//Functions for adding Buttons
function defaultName(url){
	var nameBox = document.getElementById('cusName');
	if(nameBox.value == ""){
		var name = url.replace(/http:\/\//i, "");//get name for button from url
		name = name.replace(/www\./i, "");
		name = name.replace(/\..*/gi, "");//---------------------------
		nameBox.value = name;
	}

}
function appendAdd(table, index, name, url){//custom button add
	var myTable = document.getElementById(table);
	var c ="";//need to pass something in place of c for cellControllBut() - it gets used in the append function
	if(index){
		index = index - 1;
		var rowid = myTable.rows[index].id;
		myTable.rows[index].cells[0].firstChild.firstChild.nodeValue = "";	   //clear it and add button
		myTable.rows[index].cells[0].firstChild.firstChild.nodeValue = name;
		myTable.rows[index].cells[0].className='customButtonSelected';
		cellControllBut(index, table, rowid, c, name, url);
	}else{
		var customBut = document.getElementById('cusUrl').value;//value from input box
		name = document.getElementById('cusName').value;
		var v = new RegExp(); 
		v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
		
		if (!v.test(customBut)){alert("You must supply a valid URL."); return false; } 
		else if(customBut == ""){alert("Please enter a valid URL.");}		
		
		else if(name == ""){alert("Please enter a name for your custom button.");}
		else if (!name.match(formUser)){alert("Button name can only contain letters and numbers.");}
		
		else{
		
			for(i=0; i < myTable.rows.length; i++){
				if((myTable.rows[i].cells[0].className=='customButton') || (myTable.rows[i].cells[0].className=='customButton customButtonHover')){//find first empty cell clear it and add button
					myTable.rows[i].cells[0].className='customButtonSelected';
					myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = "";	   //clear it and add button
					var rowid = myTable.rows[i].id;
					myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = name;
			
					break;
				}
			}
			
			var url = customBut.replace(/http:\/\//i, "");
			cellControllBut(i, table, rowid, c, name, url);//create delete button ,fields and load fields with button data
			document.getElementById('cusUrl').value = "http://";//clear custom button input field
			document.getElementById('cusName').value = "";//clear custom button input field
		}
	}
}

function append(c, name, table, index){//add predefined buttons
	var myTable = document.getElementById(table);
	if(index){
		index = index - 1;
		c.checked = true;
		c.disabled = true;
		var rowid = myTable.rows[index].id;
		myTable.rows[index].cells[0].firstChild.firstChild.nodeValue = "";
		myTable.rows[index].cells[0].firstChild.firstChild.nodeValue = name;
		myTable.rows[index].cells[0].className='customButtonSelected'; 
		cellControllBut(index, 'selected', rowid, c);
	}else{	
		if(c.checked){
			c.disabled = true;		
			for(i=0; i < myTable.rows.length; i++){
				if((myTable.rows[i].cells[0].className=='customButton') || (myTable.rows[i].cells[0].className=='customButton customButtonHover')){//find first empty cell clear it and add button
					var rowid = myTable.rows[i].id;
					myTable.rows[i].cells[0].className='customButtonSelected'; 
					myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = "";
					myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = name;
					cellControllBut(i, 'selected', rowid, c);//create delete button ,fields and load fields with button data
				
					break;
				}
			}
		}
	}
}

function cellControllBut(i, table, rowid, c, name, url){
	limit++;
	var myTable = document.getElementById(table);	
	var deleteBut = document.createElement('input');//create delete button		
	deleteBut.type = "button";
	deleteBut.id = "buttonD" + rowid;
	deleteBut.value = ("Remove");
	deleteBut.className = "deleteBut";
	//predefined only
	var buttonId = document.createElement('input');//create input box for button id
	buttonId.type = "hidden";
	buttonId.id = "b_id" + rowid;
	buttonId.name = "b_id" + rowid;
	//custom only
	var customName = document.createElement('input');//create input box for custom button 
	customName.type = "hidden";
	customName.id = "c_name" + rowid;
	customName.name = "c_name" + rowid;
	
	var customUrl = document.createElement('input');//create input box forcustom url
	customUrl.type = "hidden";
	customUrl.id = "c_url" + rowid;
	customUrl.name = "c_url" + rowid;
	
	var targetUrl = document.createElement('input');//create input box forcustom url
	targetUrl.type = "hidden";
	targetUrl.id = "target" + rowid;
	targetUrl.name = "target" + rowid;
	//load button values
	if(c.value > -1){//if predefined
		buttonId.value = (c.value);
		targetUrl.value = ('n');
	}else{//if custom
		customName.value = (name);
		customUrl.value = (url);
		targetUrl.value = ('y');
	}
	//deleteBut.setAttribute("onclick","remove(this," + rowid + ", 'customize');"); this line is right by W3C but does not work with IE so we use the line below
	deleteBut.onclick = function() { remove(this, rowid, 'customize'); c.disabled = false; c.checked = false; };
	
	//attach fields to correct table cells
	myTable.rows[i].cells[0].appendChild(deleteBut);
	myTable.rows[i].cells[0].appendChild(buttonId);
	myTable.rows[i].cells[0].appendChild(customName);
	myTable.rows[i].cells[0].appendChild(customUrl);
	myTable.rows[i].cells[0].appendChild(targetUrl);
	if(limit == maxLimit){lockForm();}
	

}
//End adding Functions


//Remove custom button functions

function removeAll(form, table, divid){
	var myForm = document.getElementById(form);
	var myTable = document.getElementById(table);
	
	if(divid == "buttons"){
		limit = 0;
		if(formLocked == true){unlockForm();}
		for(i = 0; i < myTable.rows.length; i++){
			var rowid = myTable.rows[i].id;
			var b_id = document.getElementById("b_id" + rowid);
			var c_url = document.getElementById("c_url" + rowid);
			var c_name = document.getElementById("c_name" + rowid);
			var ctarget = document.getElementById("target" + rowid);
			var button = document.getElementById('buttonD' + rowid);
			if(myTable.rows[i].cells[0].className != 'customButton'){
				myTable.rows[i].cells[0].className='customButton';
				myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = "";
				myTable.rows[i].cells[0].firstChild.firstChild.nodeValue = "Add";
				myTable.rows[i].cells[0].removeChild(button);
				myTable.rows[i].cells[0].removeChild(b_id);
				myTable.rows[i].cells[0].removeChild(c_url);
				myTable.rows[i].cells[0].removeChild(c_name);
				myTable.rows[i].cells[0].removeChild(ctarget);
				
			}
			
		}
		var fieldCheck = myForm.checkSelect;
		for (i = 0; i < fieldCheck.length; i++){ fieldCheck[i].checked = false ; fieldCheck[i].disabled = false ;}
		
	}else if(divid == "userInfo"){
		var resetFields = [];
		myForm.uname.value = "";
			resetFields.push(myForm.uname);
		myForm.password.value = "";
			resetFields.push(myForm.password);
		myForm.password2.value = "";
			resetFields.push(myForm.password2);
		myForm.fname.value = "";
			resetFields.push(myForm.fname);
		myForm.lname.value = "";
			resetFields.push(myForm.lname);
		myForm.age.value = "";
			resetFields.push(myForm.age);
		myForm.email.value = "";
			resetFields.push(myForm.email);
		myForm.zipcode.value = "";	
			resetFields.push(myForm.zipcode);
		myForm.inetid.value = "";
			resetFields.push(myForm.inetid);
		var field = myForm.gender;
		for (i = 0; i < field.length; i++){field[i].checked = false;}
		if(form == "customize"){
			$("#availabilityResult2").html('');
		}else{
			$("#availabilityResult").html('');
		}
		
		for(i = 0; i < resetFields.length; i++){
			resetFields[i].style.background = homeValidTxt;
			resetFields[i].style.border = homeValidBorder;
		}
	}
	return true;
}

function remove(button, rowid, form){
	limit--;
	var myForm = document.getElementById(form);
	var myRowid = document.getElementById(rowid);
	var myTable = document.getElementById('selected');
	var b_id = document.getElementById("b_id" + rowid);
	var c_url = document.getElementById("c_url" + rowid);
	var c_name = document.getElementById("c_name" + rowid);
	var ctarget = document.getElementById("target" + rowid);
	myRowid.cells[0].className='customButton';
	myRowid.cells[0].firstChild.firstChild.nodeValue = "";
	myRowid.cells[0].firstChild.firstChild.nodeValue = "Add";
	myRowid.cells[0].removeChild(button);
	myRowid.cells[0].removeChild(b_id);
	myRowid.cells[0].removeChild(c_url);
	myRowid.cells[0].removeChild(c_name);
	myRowid.cells[0].removeChild(ctarget);
	
	if((formLocked == true) && (limit < maxLimit)){ unlockForm();}
}
// End Remove


//Locking and unlocking form function
//Lock form when max buttons selected

function lockForm(){
	formLocked = true;
	var fieldCheck = document.getElementById('customize').checkSelect;
	for (i = 0; i < fieldCheck.length; i++){
		if(fieldCheck[i].checked == false){
			lockedFields[i] = fieldCheck[i];
			fieldCheck[i].disabled = true;
		}
	}
	document.getElementById('cusName').disabled = true;
	
}

function unlockForm(){
	formLocked = false;
	document.getElementById('cusName').disabled = false;
	for(i = 0; i < lockedFields.length; i++){
		if(lockedFields[i]){
			lockedFields[i].disabled = false;
		}
	}
	
}
// End Lock functions

function updateSubmit(form, table){
	var field;
	var fieldpram = "";
	var i = 1;
	var navHTML;
	if(hLogin){		
		var myTable = document.getElementById(table);
		var elem = document.getElementById(form).elements;
					
		for(i = 0; i < myTable.rows.length; i++){
			var sortBox = document.createElement("input");
			var index = myTable.rows[i].id;
			sortBox.type = 'hidden';
			sortBox.id = 'sort' + index;	
			sortBox.name = 'sort' + index;
			sortBox.value = (i + 1);
			myTable.rows[i].cells[0].appendChild(sortBox);
			myTable.rows[i].cells[0].firstChild.nodeValue = "";
			myTable.rows[i].cells[0].firstChild.nodeValue = "Add";
			var button = document.getElementById('buttonD' + index);
			if(button){
				myTable.rows[i].cells[0].removeChild(button);
			}
		}     
        for(i=1; i < 9; i++){
            field = document.getElementById("c_url" + i);
			if(field){
				fieldpram += "url" + i + "="+ field.value + "&";
			}else{
				fieldpram += "url" + i + "=&";
			}
			field = document.getElementById("b_id" + i);
			if(field){
				fieldpram += "bid" + i + "="+ field.value + "&";
			}else{
				fieldpram += "bid" + i + "=&";
			}
			field = document.getElementById("c_name" + i);
			if(field){
				fieldpram += "name" + i + "="+ field.value + "&";
			}else{
				fieldpram += "name" + i + "=&";
			}
			field = document.getElementById("target" + i);
			if(field){
				fieldpram += "target" + i + "="+ field.value + "&";
			}else{
				fieldpram += "target" + i + "=n&";
			}
			field = document.getElementById("sort" + i);
				fieldpram += "sort" + i + "="+ field.value + "&";	
			
		}
		
		 $("#navBar").load("/gajet/classes/update.php?" + fieldpram);
		 	
		closeContainer('customizeBox', 'userSignUp');
		limit = 0;
	}else{openContainer('userSignUp');}
}



function finalSubmit(form, table){
	var myForm = document.getElementById(form);	
	
		var myTable = document.getElementById(table);		
		var homeValidForm = homeValidateMyForm(form);			
		if(!homeValidForm){
			alert(homeValidationMessage);
			
		}else{
			if(form == "customize"){
				for(i = 0; i < myTable.rows.length; i++){
					var sortBox = document.createElement("input");
					var index = myTable.rows[i].id;
					sortBox.type = 'hidden';
					sortBox.id = 'sort' + index;	
					sortBox.name = 'sort' + index;
					sortBox.value = (i);
					myTable.rows[i].cells[0].appendChild(sortBox);			
				}
			}
			myForm.submit();
		}
		
	
	
}


//Checks password field 1 and 2 on sign up form before submitting
function passwordCheck(p2, form){
	var myForm = document.getElementById(form);
	var p1 = myForm.password;
	if(p1.value != p2.value){
		alert("Password does not match");
		p1.value = "";
		p2.value = "";
		p1.style.background = homeinValidTxt;
		p2.style.background = homeinValidTxt;
		p1.style.border = homeinValidBorder;
		p2.style.border = homeinValidBorder;
		p1.focus();
	}else{
		p1.style.background = homeValidTxt;
		p2.style.background = homeValidTxt;
		p1.style.border = homeValidBorder;
		p2.style.border = homeValidBorder;
	}	
}
function php_urlencode (str) {
    str = escape(str);
    return str.replace(/[*+\/@]|%20/g,
    function (s) {
        switch (s) {
            case "*": s = "%2A"; break;
            case "+": s = "%2B"; break;
            case "/": s = "%2F"; break;
            case "@": s = "%40"; break;
            case "%20": s = "+"; break;
        }
            return s;
        }
    );
}
//User name availablity functions
function checkUNA(form, submit){	
	homeValidationMessage = 'Please correct the following errors:\r\n';
	homeValid = true;// - reset valid tracker
	homeValidFields = [];// - reset vaild fields
	homeinValidFields = [];// - reset invaild fields
	
	var myForm = document.getElementById(form);
	var uname = myForm.uname;
	var email = myForm.email;
	var username = uname.value;
	var mailAdd;
	
	//validate username
		validField = valUsername(uname);
		if (!validField){
			homeinValidFields.push(uname);
			username = '';
		}
	
	if(submit == 'submit'){
		if(email.value){
			mailAdd = php_urlencode(email.value);//encode email for $_GET
		}
		// homeValidate email
		validField = valEmail(email);
		if (!validField){
			homeinValidFields.push(email);
			mailAdd = '';
		}else{
			email.style.border = homeValidBorder;
			email.style.background = homeValidTxt;
		}
	}else{
		mailAdd = '';
	}
		if(form == 'customize'){
				$("#availabilityResult2").load(defaultUrl + "/gajet/test/una.php?uname="+username+"&form="+form+"&div=availabilityResult2&submit="+submit+"&mail="+mailAdd);
		}else{
				$("#availabilityResult").load(defaultUrl + "/gajet/test/una.php?uname="+username+"&form="+form+"&div=availabilityResult&submit="+submit+"&mail="+mailAdd);
		}
	
	
}

function unaTaken(status, form, div, submit, mail){	
	var myForm = document.getElementById(form);
	var color = document.getElementById(div);
	if(submit == "submit"){
		if(mail){
			homeValid = false;
			homeValidationMessage += '  - This email is all ready in the system\r\n';
			homeinValidFields.push(myForm.email);
		}
		if(status == "Not Available"){	
			homeValid = false;
			homeValidationMessage += '  - User name not available\r\n';
			myForm.uname.focus();
			myForm.uname.value = myForm.uname.value;
			homeinValidFields.push(myForm.uname);
			color.style.color = '#cc0000';
		}else{
			if(!mail){
				homeValid = true;
			}
			color.style.color = 'GREEN';
			homeValidFields.push(myForm.uname);
		}
		finalSubmit(form, 'selected'); 
	}else{
		if(status == "Not Available"){	
			homeValid = false;
			homeValidationMessage += '  - User name not available\r\n';
			myForm.uname.focus();
			myForm.uname.value = myForm.uname.value;
			myForm.uname.style.background = homeinValidTxt;
			myForm.uname.style.border = homeinValidBorder;
			color.style.color = '#cc0000';
		}else{
			homeValid = true;
			myForm.uname.style.background = homeValidTxt;
			myForm.uname.style.border = homeValidBorder;
			color.style.color = 'GREEN';
			homeValidFields.push(myForm.uname);
		}
	}
}




function homeValidateMyForm(form){
	
//Field variables
	var myForm = document.getElementById(form);
	var uname = myForm.uname;
	var pword = myForm.password;
	var pword2 = myForm.password2;
	var fname = myForm.fname;
	var lname = myForm.lname;
	var age = myForm.age;
	var email = myForm.email;
	var zip = myForm.zipcode;
	var inetid = myForm.inetid;
	
	
	
//run validation on each field
	
	// homeValidate UserName
	//		Validated in checkUNA
		
	// homeValidate Password
		validField = valPword(pword, pword2);
		if (!validField){
			homeinValidFields.push(pword);
			homeinValidFields.push(pword2);
			pword.value = '';
			pword2.value = '';
		}else{
			homeValidFields.push(pword);
			homeValidFields.push(pword2);
		}
		
	// homeValidate first and last name
	//First
		validField = valNames(fname, 'First');
		if (!validField){
			homeinValidFields.push(fname);
		}else{
			homeValidFields.push(fname);
		}
	//Last	
		validField = valNames(lname, 'Last');
		if (!validField){
			homeinValidFields.push(lname);
		}else{
			homeValidFields.push(lname);
		}
		
	// homeValidate age
		validField = valAge(age);
		if (!validField){
			homeinValidFields.push(age);
		}else{
			homeValidFields.push(age);
		}
		
	// homeValidate email
	//		Validated in checkUNA
		
	// homeValidate zipcode	
		validField = valZip(zip);
		if (!validField){
			homeinValidFields.push(zip);
		}else{
			homeValidFields.push(zip);
		}
		
	//homeValid inet id
		validField = valInetId(inetid);
		if (!validField){
			homeinValidFields.push(inetid);
		}else{
			homeValidFields.push(inetid);
		}		
//end field validation
	
// Handle validation results
		//form is not vaild
		if (!homeValid){
			for(i = 0; i < homeinValidFields.length; i++){//change css for invaild fields
				homeinValidFields[i].style.background = homeinValidTxt;			
				homeinValidFields[i].style.border = homeinValidBorder;
			}
			for(i = 0; i < homeValidFields.length; i++){//change css back to default for any vaild fields
				homeValidFields[i].style.background = homeValidTxt;
				homeValidFields[i].style.border = homeValidBorder;
			}
			//reset homeVaild and return false for invaild form
			
			homeValid = true;
			return false;
			
		}else{
		// form is valid set css back to default and return true for vaild form
			for(i = 0; i < homeValidFields.length; i++){
				homeValidFields[i].style.background = homeValidTxt;
				homeValidFields[i].style.border = homeValidBorder;
			}
			return true;
		}
}



function valUsername(uname){
	 // homeValidate user name
	 var valid = true; 
	if (uname.value.length < 3) {
		homeValidationMessage += '  - User name must be between 3 and 15 characters long\r\n';
		homeValid = false;
		vaild = false;
	}
	if ((!uname.value.match(formUser)) || (!uname.value)) {
		homeValidationMessage += '  - User name can only contain letters and numbers\r\n';
		homeValid = false;
		valid = false;
	}
	return valid;
}

function valPword(pword, pword2){
// homeValidate password
	var valid = true;
    if ((pword.value.match(/ /g)) || (pword.value.length < 6) || (pword2.value.length < 6))  {
		homeValidationMessage += '  - Password can not have spaces and needs to be 6 to 10 characters long\r\n';
		homeValid = false;
		valid = false;		
	}
	return valid;
}

function valNames(name, namePos){
	// homeValidate first name
	var valid = true;
	if ((name.value.length > 3) && (!name.value.match(formString)) || (name.value.length > 0) && (name.value.length < 3)) {
		homeValidationMessage += '  - '+namePos+' name may only contain letters\r\n';
		homeValid = false;
		valid = false;
	}
	return valid;
}

function valAge(age){
	// homeValidate age
	var valid = true;
	if ((age.value.length > 0) && (!age.value.match(formNum))) {
		homeValidationMessage += '  - Age my only contain numbers\r\n';
		homeValid = false;
		valid = false;
	}
	return valid;
}

function valEmail(email){
	// homeValidate email	
	var valid = true;
	if((!homeValidEmail.test(email.value)) || (!email.value)){
		homeValidationMessage += '  - You must enter a vaild email\r\n';
		homeValid = false;
		valid = false;
	}
	return valid;
}

function valZip(zip){
	// homeValidate zipcode	
	var valid = true;
	var zipbox = document.getElementById("setZipCode");
	zip = zip.value.toUpperCase();
	if (!zip.match(usReg)){
		if(!zip.match(caReg)){
			homeValidationMessage += '  - You must enter a vaild zip\r\n';
			homeValid = false;
			valid = false;
		}else{
			//Zip vaild
		}
	}else{
		//Zip vaild
	}
	
	return valid;
}

function valInetId(inetid){
	//homeValid inet id
	var valid = true;
	if ((inetid.value.length > 0) && (!inetid.value.match(formNum))) {
		homeValidationMessage += '  - InetGlobal Id my only contain numbers\r\n';
		homeValid = false;
		valid = false;
	}
	return valid;
}
