var JQ = jQuery.noConflict();
var profile = {};
var isLoggedIn = false;
var validForm = false;
var isSwooshUser = false;
var hasLastName = false;
var hasEmail = false;
var showDebug = false;
var allowSubmit = false;
var showLabelError = false;
var ajaxProgress = false;
var confirmation = false;
if (!locale){
	locale = '';
}

function swfAjaxRequest(url, method, data, callback){ 
	this.url = url || '';
	this.method = method || 'POST';
	this.data = data || {};
	this.callback = callback || function(){ alert('No callback provided') };
	this.req = {'url':this.url,'meth':this.method,'data':this.data,'onready':function(data){ callback(data) }};
	this.sendRequest = function() { f4a.open(this.req) };
}

function validateProtocol() {
	// if we're live switch to HTTPS
	if (location.href.indexOf(".nike.com") >= 1 && location.href.indexOf("env") < 0) {
		if (location.protocol == "http:") {
			window.location.href = location.href.replace(/http:/, "https:");
		}
	}
}

function showLoader(f){
	if (f){
		ajaxProgress = true;
		JQ('.loader').show();
	}
	else{
		ajaxProgress = false;
		JQ('.loader').hide();
	}
}

function loadProfile(callback) {
	var url = COMMERCE_PROFILE_SERVICE_URL;
	var data = 'action=getprofile';
	var loadProfileRequest = new swfAjaxRequest(url,'POST',data,function(data){
		data = data.replace(/\&(?!amp;)/g,'&amp;');
		var profileService = JQ.xml2json(data);
		var id = profileService.profile.id;
		var lastName = profileService.profile.lastName;
		var userType = profileService.profile.userType;
		var email = profileService.profile.email;
		if (id != "") isLoggedIn = true;
		if (userType == 'swooshUser') isSwooshUser = true;
		if (lastName != '') hasLastName = true;
		callback();
	});
	loadProfileRequest.sendRequest();
}

function logout(callback) {
	var url = COMMERCE_PROFILE_SERVICE_URL;
	var data = 'action=logout';
	var logoutRequest = new swfAjaxRequest(url,'POST',data,function(data){
		callback ? callback() : void(0);
	});
	logoutRequest.sendRequest();
}

function trySwooshLogin(JQform) {
	if(!ajaxProgress){
		showLoader(true);
		validForm = true;
		clearLoginErrors();
		
		validate(JQform, function() { 
			if(validForm){
				var data = JQform.serialize();
				var loginRequest = new swfAjaxRequest(COMMERCE_PROFILE_SERVICE_URL,'POST',data,function(data){
					showLoader(false);
					data = data.replace(/\&(?!amp;)/g,'&amp;');
					var profileService = JQ.xml2json(data);
					ajaxProgress = false;
					if (profileService.status == 'failure') {
						var msg = "";
						JQ(profileService.exceptions.error).each(function(){
							if (this.message){
								var error = this.message;
								msg += error;
							}
						});
						if(msg != ""){
							JQ('.form-errors-msg').html(msg);
							JQ('.form-errors-msg').show();
						}
					} else {
						if (JQ.getURLParam('continueURL')){
							window.location.href = unescape(JQ.getURLParam('continueURL'));
						} else {
							window.location.href = SWOOSH_HOMEPAGE_URL;
						}
					}
				});
				loginRequest.sendRequest();
			} else {
				showLoader(false);
			}
		});
	}
}

function tryFamilyMemberVerification() {
	if(!ajaxProgress){
		showLoader(true);
		var data = 'emailAddr='+JQ.getURLParam("emailAddr")+'&inviteId='+JQ.getURLParam("inviteId")+'&action=verifyFamily';
		var verifyRequest = new swfAjaxRequest(SWOOSH_VERIFICATION_URL,'POST',data,function(data){
			showLoader(false);
			data = data.replace(/\&(?!amp;)/g,'&amp;');
			var profileService = JQ.xml2json(data);
			ajaxProgress = false;
			if (profileService.status == 'failure') {
				var msg = "";
				JQ(profileService.exceptions.error).each(function(){
					if (this.message){
						var error = this.message;
						msg += error;
					}
				});
				if(msg != ""){
					JQ('.form-errors-msg').html(msg);
					JQ('.form-errors-msg').show();
				} else {
					msg = 'We were unable to verify your information.';
					JQ('.form-errors-msg').html(msg);
					JQ('.form-errors-msg').show();
				}
			} else {
				JQ('.form-errors-msg').html('Press continue to start the registration process.');
				JQ('.buttons-container').show();
			}
		});
		verifyRequest.sendRequest();
	}
}

function trySwooshSubmit(JQform) {
	if(!ajaxProgress){
		showLoader(true);
		validForm = true;
		clearErrors(JQform);
		
		validate(JQform, function() { 
			if(validForm){
				var isRegistration = (JQform.attr('id') == 'register_form');
				var URL = isRegistration ? COMMERCE_PROFILE_SERVICE_URL : SWOOSH_VERIFICATION_URL;
				var data = JQform.serialize();
				var submitRequest = new swfAjaxRequest(URL,'POST',data,function(data){
					showLoader(false);
					data = data.replace(/\&(?!amp;)/g,'&amp;');
					var profileService = JQ.xml2json(data);
					showLoader(false);
					ajaxProgress = false;
					if (profileService.status == 'failure') {
						var msg = "";
						JQ(profileService.exceptions.error).each(function(){
							var error = this.message || '';
							var field = this.property || '';
							var f = findField(field);
							if(f != ''){
								showError(f, true, true);
							} else {
								msg += error;
							}
						});
						if(msg != ""){
							JQ('#form-errors-msg').html(msg);
							JQ('#form-errors-msg').show();
						} else {
							msg = 'We were unable to validate your information. Please check the form and try again.';
							JQ('#form-errors-msg').html(msg);
							JQ('#form-errors-msg').show();
						}
					} else {
						window.location.href = isRegistration ? "swoosh.html?page=welcome" : "swoosh.html?page=terms";
					}
				});
				submitRequest.sendRequest();
			}
		});
	}
}

function forgotSwooshPassword(JQform){
	if(!ajaxProgress){
		showLoader(true);
		validForm = true;
		clearLoginErrors();
		profile.login = JQ('#inputfield-login').val();
		var data = JQform.serialize();
		var loginRequest = new swfAjaxRequest(COMMERCE_PROFILE_SERVICE_URL,'POST',data,function(data){
			showLoader(false);
			data = data.replace(/\&(?!amp;)/g,'&amp;');
			var profileService = JQ.xml2json(data);
			console.log(profileService);
			ajaxProgress = false;
			if (profileService.status == 'failure') {
				var msg = "";
				JQ(profileService.exceptions.error).each(function(){
					if (this.message){
						var error = this.message;
						msg += error;
					}
				});
				if(msg != ""){
					JQ('.form-errors-msg').html(msg);
					JQ('.form-errors-msg').show();
				}
			} else {
				JQ('#forgot').hide();
				JQ('#security').show();
				JQ('#label-passwordAnswer strong').html(profileService.passwordQuestion);
			}
		});
		loginRequest.sendRequest();
	}
}

function submitSecurityQuestion(JQform){
	if(!ajaxProgress){
		showLoader(true);
		validForm = true;
		clearLoginErrors();
		var data = JQform.serialize();
		data += '&login='+JQ('#inputfield-login').val();
		var loginRequest = new swfAjaxRequest(COMMERCE_PROFILE_SERVICE_URL,'POST',data,function(data){
			showLoader(false);
			data = data.replace(/\&(?!amp;)/g,'&amp;');
			var profileService = JQ.xml2json(data);
			console.log(profileService);
			ajaxProgress = false;
			if (profileService.status == 'failure') {
				var msg = "";
				JQ(profileService.exceptions.error).each(function(){
					if (this.message){
						var error = this.message;
						if(!error.match('null')){
							msg += error;
						}
					}
				});
				if(msg != ""){
					JQ('.form-errors-msg').html(msg);
					JQ('.form-errors-msg').show();
				}
			} else {
				JQ('#security').hide();
				JQ('#success').show();
			}
		});
		loginRequest.sendRequest();
	}
}

function findField(name){
	var obj = '';
	JQ(allFields).each(function(){
		if(this.id == name || this.group == name){
			obj = this;
			//return this;
		}
	});
	return obj;
}

function showLoginError(f){
	JQ('#inputfield-'+f.id).parent().addClass("error");
	JQ('#inputfield-'+f.id).addClass("error");
}

function clearLoginErrors(){
	JQ('.form-errors-msg').html('');
	JQ('.form-errors-msg').hide();
	JQ(allFields).each(function(){
		JQ('#inputfield-'+this.id).parent().removeClass("error");
		JQ('#inputfield-'+this.id).removeClass("error");
	});
}

function clearErrors(JQform){
	JQ('.form-errors-msg').html('');
	JQ('.form-errors-msg').hide();
	JQform.find('.loading').hide().end().find('p.error').html('').hide();
	JQ(allFields).each(function(){
		if(this.group != undefined){
			JQ('#label-'+this.group, JQform).html(this.label);
			JQ('#label-'+this.group, JQform).removeClass('error');
		}
		else{
			JQ('#label-'+this.id, JQform).html(this.label);
			JQ('#label-'+this.id, JQform).removeClass('error');
		}
		JQ('#inputfield-'+this.id, JQform).removeClass("error");
	});
}

function showError(f, label, server, empty){
	if(empty == undefined){
		empty = false;	
	}

	if (f.formId) {
		formId = '#'+f.formId+' ';
	} else {
		formId = '';
	}
	if(label && server && f.labelServerError != undefined){
		var labelError = f.labelServerError;
	}
	else{
		var labelError = f.labelError;
	}
	if(label){
		if(f.group != undefined){
			if(labelError){
				JQ(formId+'#label-'+f.group).html(labelError.toUpperCase());
			}
			JQ(formId+'#label-'+f.group).addClass('error');
		}
		else{
			if(labelError){
				JQ(formId+'#label-'+f.id).html(labelError.toUpperCase());
			}
			JQ(formId+'#label-'+f.id).addClass('error');
		}
	}
	if(empty){
		if(f.group != undefined){
			JQ(formId+'#label-'+f.group).addClass('error');
		}
		else{
			JQ(formId+'#label-'+f.id).addClass('error');
		}
	}
	
	if(f.group != undefined){
		var group = f.groupOrder.split(',');
		JQ(group).each(function(){
			JQ(formId+'#inputfield-'+this).addClass("error");
		});
	}
	else{
		JQ(formId+'#inputfield-'+f.id).addClass("error");
		if(f.matchField != undefined){
			JQ(formId+'#inputfield-'+f.matchField).addClass("error");
		}
	}
}

function initForm(formID){
	JQ(fieldData[formID]).each(function() {
		var f = new Object();
		f.formId = formID;
		if(this.id != undefined){
			f.id = this.id;
		}
		else if(this.name != undefined){
			f.id = this.name;
		}
		if(this.required != undefined){
			f.required = this.required;
		}
		if(this.labelError != undefined){
			f.labelError = this.labelError;
		}
		if(this.labelServerError != undefined){
			f.labelServerError = this.labelServerError;
		}
		if(this.validationType != undefined){
			f.validationType = this.validationType;
		}
		if(this.group != undefined){
			f.group = this.group;
			f.groupOrder = this.groupOrder;
			f.label = JQ('#label-'+this.group).html();
		}
		else{
			f.label = JQ('#label-'+f.id).html();
		}
		if(this.matchField != undefined){
			f.matchField = this.matchField;
		}
		allFields.push(f);
		f = null;
	});
}

function validate(JQform, callback){
	var validForm = true;
	clearErrors(JQform);
	JQ(allFields).each(function(){
		showLabelError = true;
		if(this.formId == JQform.attr('id')){
			if((JQ('#inputfield-'+this.id, JQform).val() == '' || JQ('#inputfield-'+this.id, JQform).val() == '-1') && this.required != "no"){
				if(this.formId == 'swoosh_login'){
					showLoginError(this);
				}
				showError(this, showLabelError, false, true);
				validForm = false;
			}
			else{
				if(this.validationType){
					if(!validateField(this)){
						if(this.formId == 'swoosh_login'){
							showLoginError(this);
						}
						showError(this, showLabelError, false);
						validForm = false;
					}
				}
				if(this.matchField != undefined){
					if(!validateMatch(this)){
						showError(this, showLabelError, false);
						validForm = false;
					}
				}
			}
		}
	});
	if(validForm){
		callback();
	} else {
		showLoader(false);
	}
}

function validateSsNumber(ssNumber){
	showLabelError = true;
	return (ssNumber.length < 4) ? false : true;
}

function validateZipcode(zipcode){
	showLabelError = true;
	return (zipcode.length < 5) ? false : true;
}

function validateDate(m, d, y){
	if(m == -1 && d == -1 && y == -1){
		showLabelError = false;
		return false;
	}
	else if(m == -1 || d == -1 || y == -1){
		showLabelError = true;
		return false;
	}
	else{
		showLabelError = true;
		m = m - 1;
		var testDate = new Date(y, m, d);
		if ((testDate.getFullYear() == y) && (testDate.getMonth() == m) && (testDate.getDate() == d))
			return true;
		else
			return false;
	}
}

function validateEmail(email){
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	showLabelError = true;
	return (filter.test(email)) ? true : false;
}

function validateRadioButtons(f){
	showLabelError = true;
	return (JQ("input[@name='"+f.id+"']:checked").val() != undefined) ? true : false;
}

function validateMatch(f){
	showLabelError = true;
	return (JQ('#edit-'+f.id).val() == JQ('#edit-'+f.matchField).val()) ? true : false;
}

function validateField(f){
	if(f.group == undefined){
		if(f.validationType == 'ssNumber'){
			return validateSsNumber(JQ('#'+f.formId+' #inputfield-'+f.id).val());
		}
		if(f.validationType == 'email'){
			return validateEmail(JQ('#'+f.formId+' #inputfield-'+f.id).val());
		}
		if(f.validationType == 'zipcode'){
			return validateZipcode(JQ('#'+f.formId+' #inputfield-'+f.id).val());
		}
		if(f.validationType == 'radio'){
			return validateRadioButtons(f);
		}
	} else {
		if(f.validationType == 'date'){
			var group = f.groupOrder.split(',');
			return validateDate(JQ('#inputfield-'+group[0]).val(), JQ('#inputfield-'+group[1]).val(), JQ('#inputfield-'+group[2]).val());
		}
	}
}

function blockNonNumericChars(e){
	if ( e.which == 32 || (33 <= e.which && e.which <= 44) || e.which == 47 || (58 <= e.which && e.which <= 95) || 96 <= e.which){
		return false;
	} else {
		return true;
	}
}

/* Terms & Conditions */
function nextTerm(JQlink){
	var sInc = JQlink.attr('id').split('_')[1];
	var iInc = parseFloat(sInc);
	console.log(sInc);
	if (JQlink.parents('.buttons-container').find('#check_'+sInc).is(':checked')){
		if(iInc == 4){} else {
			JQlink.parents('.terms_copy').hide().end().parents('.step').removeClass('on').addClass('off');
			var iCurrentStepInc = '0' + (iInc + 1);
			JQ('#step_'+iCurrentStepInc).removeClass('off').addClass('on').find('.terms_copy').show();
		}
	} else { return false; }
}




/*
function Phonebook(yellowPagesURL,country){
	this.commerceProfileServiceURL = '';
	var self = this;
	this.getCommerceProfileServiceURL = function() {
		//If not already set, call yellow pages for URL
		if(self.commerceProfileServiceURL == ''){
			var yellowPagesRequest = new swfAjaxRequest(yellowPagesURL+'?service=commerceProfileService','GET',null,function(data){
				self.commerceProfileServiceURL = JQ.xml2json(data).serviceURL;
			});
			yellowPagesRequest.sendRequest();
		}
		return self.commerceProfileServiceURL;
	}
}
*/


