// Author: Nathan Hallford
// Version: 7.09.2009
// Description: JS for user registration page

tfy.userreg = {};
tfy.userreg.inDocumentRef = false;
tfy.userreg.dataURL = false;
tfy.userreg.register_5_count = 0;

tfy.userreg.Init = 
	function(inDocumentRef) { 
		tfy.userreg.inDocumentRef = inDocumentRef;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
	};
	
tfy.userreg.whatsThis = 
	function() { 
				$('popUp').style.display = 'block';		
	};
	
tfy.userreg.displaySMSform = 
	function() { 
		$('sms_box').style.display = 'block';
		$('email_box').style.display = 'none';
		$('sms_box_res').style.display = 'none';		
	};

tfy.userreg.ShowPasswordPopUp = 
	function() { 
		$('pop_password_strength').style.display = 'block';
		var pos = $('show_password_pop').cumulativeOffset();
		var window_scroll_position = tfy.main.getYOffset();
		var pop_content_position = pos.top - $('pop_password_strength').getHeight();
		//Scroll to pop up content position if window scroll position is greater
		if(window_scroll_position > pop_content_position){
			window.scrollTo(0,pop_content_position);
		}
	};

tfy.userreg.HidePasswordPopUp = 
	function() { 
		$('pop_password_strength').style.display = 'none';
			
	};	
	
tfy.userreg.checkUsernameExists = 
	function(member_id) { 
		//$('center-LOAD').style.display = 'block';
		var msg_data = {};
		msg_data.cmd = 'check_if_username_exists';
		msg_data.member_id = member_id;
		msg_data.username_entry = $("username_reg").value;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
		new Ajax.Request(tfy.userreg.dataURL, {
			parameters: $H(msg_data).toQueryString(),
			evalScripts: true,
			onSuccess: function(transport) {
				try {
					var JSON = eval("("+transport.responseText+")");
					if (JSON.emsg) {
						alert(JSON.emsg);
						return false;
					}
					$('usernameEntryResponse').innerHTML = JSON.response;
					
				}catch(e) {
					alert("The server's response could not be understood.\nPlease try again.");
					return false;
				}
			},
			onComplete: function(){
				//$('center-LOAD').style.display = 'none';
			}			
		});
	};
	
tfy.userreg.sendEmailAjax = 
	function() { 
		$('center-LOAD').style.display = 'block';
		var msg_data = {};
		msg_data.cmd = 'send_confirmation_email';
		msg_data.member_id = document.getElementById("member_id").value;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
		new Ajax.Request(tfy.userreg.dataURL, {
			parameters: $H(msg_data).toQueryString(),
			evalScripts: true,
			onSuccess: function(transport) {
				try {
					var JSON = eval("("+transport.responseText+")");
					if (JSON.emsg) {
						alert(JSON.emsg);
						return false;
					}
					$('email_box').innerHTML = JSON.response;
					document.getElementById('sms_box').style.display = 'none' 
					document.getElementById('email_box').style.display = 'block';
					/*
					if(JSON.is_sent == 'true'){
						$('reg_mail').onclick = function() {};
					}
					*/
				}catch(e) {
					alert("The server's response could not be understood.\nPlease try again.");
					return false;
				}
			},
			onComplete: function(){
				$('center-LOAD').style.display = 'none';
			}			
		});
	};
	
tfy.userreg.sendTextMessageAjax = 
	function() { 
		$('center-LOAD').style.display = 'block';
		var msg_data = {};
		msg_data.cmd = 'send_confirmation_text_message';
		msg_data.member_id = document.getElementById("member_id").value;
		msg_data.phone_number = document.getElementById("phone_number").value;
		msg_data.special_message = document.getElementById("special_message").value;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
		new Ajax.Request(tfy.userreg.dataURL, {
			parameters: $H(msg_data).toQueryString(),
			evalScripts: true,
			onSuccess: function(transport) {
				try {
					var JSON = eval("("+transport.responseText+")");
					if (JSON.emsg) {
						alert(JSON.emsg);
						return false;
					}
					$('sms_box_res').innerHTML = JSON.response;
					document.getElementById('sms_box').style.display = 'none';
					document.getElementById('sms_box_res').style.display = 'block';
					document.getElementById('email_box').style.display = 'none';

					
				}catch(e) {
					alert("The server's response could not be understood.\nPlease try again.");
					return false;
				}
			},
			onComplete: function(){
				$('center-LOAD').style.display = 'none';
			}			
		});
	};
	
	
	tfy.userreg.validateCode = 
	function() { 
		var confirmCode = document.getElementById('confirmation_code_1').value;
		if(!validateString(confirmCode)) {
			alert("Please enter a confirmation code to proceed.");
			return false;
		}
		var msg_data = {};
		msg_data.cmd = 'check_confirmation_code';
		msg_data.member_id = document.getElementById("member_id").value;
		msg_data.phone_number = document.getElementById("phone_number").value;
		msg_data.special_message = document.getElementById("special_message").value;
		msg_data.confirmation_code = confirmCode;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
		new Ajax.Request(tfy.userreg.dataURL, {
			parameters: $H(msg_data).toQueryString(),
			evalScripts: true,
			onSuccess: function(transport) {
				try {
					var JSON = eval("("+transport.responseText+")");
					if (JSON.emsg) {
						alert(JSON.emsg);
						return false;
					}
					$('sms_box_res').innerHTML = JSON.response;

					
				}catch(e) {
					alert("The server's response could not be understood.\nPlease try again.");
					return false;
				}
			},
			onComplete: function(){
				//$('center-LOAD').style.display = 'none';
			}			
		});
	};
	
	tfy.userreg.getMoreInfoOnQuestion = 
	function(question_id) { 
		var valueCheck = $('more_info_clicked').value;
		if(valueCheck == 0) {
			var msg_data = {};
			msg_data.cmd = 'get_more_info_on_question';
			msg_data.question_id = question_id;
			tfy.userreg.dataURL='scripts/php/user_reg.php?';
			var questionBox = "question_id_" + question_id;
			new Ajax.Request(tfy.userreg.dataURL, {
				parameters: $H(msg_data).toQueryString(),
				evalScripts: true,
				onSuccess: function(transport) {
					try {
						var JSON = eval("("+transport.responseText+")");
						if (JSON.emsg) {
							alert(JSON.emsg);
							return false;
						}
						$(questionBox).removeClassName('startInfo');
						$(questionBox).addClassName('showInfo');
						$(questionBox).innerHTML = JSON.response;
						var imageArrowBox = "imageArrowBox_" + question_id;
						$(imageArrowBox).innerHTML = "<img src=\"/images/buttons/down_down_arrow_03.gif\" alt=\"go\" />";
					//	$('more_info_clicked').value = 1;
						document.getElementById('more_info_clicked').value = '0';
						
					}catch(e) {
						alert("The server's response could not be understood.\nPlease try again.");
						return false;
					}
				},
				onComplete: function(){
					//$('center-LOAD').style.display = 'none';
					
				}			
			});
		}
		else {
			var questionBox = "question_id_" + question_id;
			$(questionBox).removeClassName('showInfo');
			$(questionBox).addClassName('startInfo');
			$('imageArrowBox').innerHTML = "<img src=\"/images/buttons/down_arrow_03.gif\" alt=\"go\" />";
			$('more_info_clicked').value = '0';
		}
	};


/**********************************************************************************************************************/
// Check If Username Already Exists Function
/**********************************************************************************************************************/


/**********************************************************************************************************************/
// 
/**********************************************************************************************************************/

function passwordChanged() {
	document.getElementById('strength_indicator').style.display = 'block';
	var strength = document.getElementById("strength_indicator");
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");
	var pwd = document.getElementById("password_reg");
	if (pwd.value.length==0) {
		strength.innerHTML = 'Type Password';
	} else if (false == enoughRegex.test(pwd.value)) {
		strength.innerHTML = 'More Characters';
	} else if (strongRegex.test(pwd.value)) {
		strength.innerHTML = '<span style="color:green">Strong!</span>';
	} else if (mediumRegex.test(pwd.value)) {
		strength.innerHTML = '<span style="color:orange">Medium!</span>';
	} else {
		strength.innerHTML = '<span style="color:red">Weak!</span>';
	}
}

function validateString(s) {
        if(s==undefined || s==null || s.length==0) {
            return false;
        }
        
        // Check for white space
        reWhiteSpace = new RegExp(/^\s+$/);
        if (reWhiteSpace.test(s)) {
            return false;
        }
     
        //Check for html tags
        reHtmlTags = new RegExp(/<(.|\n)/);
        if (reHtmlTags.test(s)) {
            return false;
        }
        return true;
}

var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				}
			}
		}
	}
	
function addDivBox(value) {
	if (typeof $value === 'undefined') $value = "";
	var divBoxCount = $('div_box_count').value;
	divBoxCount = divBoxCount * 1;
	$('div_box_count').value = divBoxCount + 1;
	var container = 'container_' + divBoxCount;
	var attrs = {
                name   : 'divBox',
                id :  container
            };

	var link = new Element('div', attrs);
 	 $('answer_dynamic_box').insert(link);
	 $(container).addClassName('answer_dynamic_box_clone');
	
	//check if we have a field we can show
	/*
	var ajaxField = $('autocomplete_hidden').value;
	if(ajaxField != "") {
		var cerealNames = explode( ",", ajaxField, 100000 );
		var value = cerealNames[divBoxCount+1];
	}
	else {
		var value = "";
	}
	*/
	var inputId = container + "_input";
	var inputBox = new Element('input', { 'id': inputId, 'type': 'text', 'class': 'newAjaxBox', 'name': 'dietary_survey[2][]', 'value': value });
	$(container).insert(inputBox);
	new Autocomplete(inputBox, { serviceUrl:'scripts/php/user_reg.php?cmd=autocomplete' });
	//new Autocomplete($('cerealAjax'), { serviceUrl:'scripts/php/user_reg.php?cmd=autocomplete' });
	
	//Add Div which will contain image file
	//var imageBoxId = container + "_del";
	//var image = new Element('div', { 'class': 'imageBox', 'id': imageBoxId });
	//$(container).insert(image);
	var img = "<div class=\"minus_box\"><a href=\"javascript: delDivBox(" + divBoxCount + ")\"><img src=\"/images/buttons/minus_button_03.gif\" /></a></div>";
	$(container).insert(img);
}

function delDivBox(divBoxCount) {
	var container = 'container_' + divBoxCount;
	$(container).remove();
}

function disableInputs(boxId) {
	var inputBox = "answ_input_" + boxId;
	var selectBox = "answ_dropdown_" + boxId;
	var checkBox = "answ_checkbox_" + boxId;
	if(document.getElementById(checkBox).checked == true) {
		document.getElementById(inputBox).disabled = true;
		document.getElementById(selectBox).disabled = true;
	}
	else {
		document.getElementById(inputBox).disabled = false;
		document.getElementById(selectBox).disabled = false;
	}
}
//For Dietary Survey
function checkInputBoxNumeric(obj){
	if(!tfy.main.ValidateNumber(obj.value)){
		alert('The input in this box must be a number.');
		obj.value = '';
	}
}	

function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
//For the Pop Up in the My Account Edit page
tfy.userreg.UpdateUserMailing = 
	function(choice) {
		var x = $("mailing_accept-"+choice);
		if($("mailing_accept-"+choice).value == 'N'){
			return ;
		}
		var msg_data = {};
		msg_data.cmd = 'UpdateUserMailing';
		msg_data.mailing_accept = choice;
		tfy.userreg.dataURL='scripts/php/user_reg.php?';
		updateMailing(choice);
		Element.update.delay(0,$('pop-content'),'<p><strong>Update my email settings</strong></p><div class="popup" style="height:100px"><strong>Thank you!</strong><br />Your email preferences have been updated.</div>');
		new Ajax.Request(tfy.userreg.dataURL, {
			parameters: $H(msg_data).toQueryString(),
			evalScripts: true,
			onSuccess: function(transport) {
				try {
					var JSON = eval("("+transport.responseText+")");
					if (JSON.emsg) {
						alert(JSON.emsg);
						return false;
					}
				}catch(e) {
					alert("The server's response could not be understood.\nPlease try again.");
					return false;
				}
			},
			onComplete: function(){
				if(choice == 'Y'){
					$('mail_accept_verbage').innerHTML = 'currently';
					$('mailing_accept_d-Y').style.display = 'none';
					$('mailing_accept_d-N').style.display = 'block';
				} else {
					$('mail_accept_verbage').innerHTML = 'not currently';
					$('mailing_accept_d-N').style.display = 'none';
					$('mailing_accept_d-Y').style.display = 'block';
				}
				$("mailing_accept-Y").value == 'N';
				$("mailing_accept-N").value == 'N';
			}			
		});
	};
function updateMailing(choice) {
	var mailing_accept =  $("mailing_accept-"+choice);
	var x = mailing_accept.value;
	if(x == 'N'){
		 mailing_accept.value = 'Y';
	}else {
		 mailing_accept.value = 'N';
	}
}