/**
 * Event-based Registration Functions
 * @author adam.housman
 */
var JQ = jQuery.noConflict();
var BRAND_CONFIG_BASE_PATH = "/b/site/upm/global/xml/brands/";
var profile = {};
var isLoggedIn = false;
var hasScreenName = false;
var hasMobileNumber = false;
var hasGender = false;
var showDebug = false;
var ajaxProgress = false;

function loadProfile(callback) {
	var url = '/services/profileService?action=getprofile';
	JQ.get( url , function(data) { 
		profile = data;
		var id = JQ('profile', profile).find('id').text();
		if (id != ""){
			isLoggedIn = true;
			var screenName = JQ('profile', profile).find('screenName').text();
			if (screenName !== ""){
				hasScreenName = true;
			}
			var mobileNumber = JQ('profile', profile).find('mobileNumber').text();
			if (mobileNumber !== ""){
				hasMobileNumber = true;
			}
			var gender = JQ('profile', profile).find('gender').text();
			if (gender !== ""){
				hasGender = true;
			}
			var address1 = JQ('profile', profile).find('address1').text();
			if (address1 !== ""){
				hasAddress1 = true;
			}
		}
		callback();
	});
}

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 doLogout(callback) {
	var url = "/services/profileService";
	var data = {};
	data['action']='logout';
	JQ.post( url , data, function(data) { 
		// do stuff with the data
		var status = JQ('status', data).text();
		profile = {};
		isLoggedIn = false;
		callback(status, data);
	});
}

function doAction(data, action, callback) {
	var url = "/services/profileService";
	data['action'] = action;
	if(action == 'logout')
		var data = {};
	showLoader(true);
	ajaxProgress = true;
	JQ.post( url , data, function(data) { 
		// do stuff with the data
		var status = JQ('status', data).text();
		if(action == 'logout'){
			profile = {};
			isLoggedIn = false;
		}
		callback(status, data);
	});
}

/**
 * Put a class of "ebr" on each link that requires the user to be logged in.
 * Put a comma separated list of all user registration fields that are required in the "require" attribute:
 * <a href="page_that_requires_login.html" require="screenname,mobilenumber">Click me</a>
 */
JQ(document).ready( function(){
	JQ("a.ebr").each( function(){
		ebr(JQ(this));
	});
});

function ebr(thisAnchor){
	jqAnchor = JQ(thisAnchor);
	$thisAnchor = jqAnchor;
	
	// Determine where to go after logging in/registering (continueURL)...
	// If the link has no href, continueURL is the current page. Else, continueURL = href.
	if ($thisAnchor.attr('href') == '' || $thisAnchor.attr('href') == '#'){
		var continueURL = escape(window.location.href);
	} else { var continueURL = escape($thisAnchor.attr('href')); }
	
	// Build required fields array.
	if($thisAnchor.attr('require')){
		var updateFields = $thisAnchor.attr('require');
		var updateFieldsArray = updateFields.split(',');
	} else { updateFieldsArray = []; }
	
	// a.ebr.logout
	if ($thisAnchor.hasClass('logout')){ 
		$thisAnchor.click(function(){
			doLogout(function(){});
		});		
	// a.ebr.login
	} else if ($thisAnchor.hasClass('login')){
		$thisAnchor.click(function(){
			loadProfile( function(){
				if (isLoggedIn){
					alert('Already Logged In');
				} else {
					window.location.href='/nikeos/p'+category+locale+'/profile?page=signin&continueURL='+continueURL;
				}
			});
		});
	// a.ebr
	} else { 
		$thisAnchor.click(function(){
			loadProfile( function(){
				var newUpdateFields = [];
				var counter = 0;
				// If this link has required fields, check if the the user's profile (if logged in) has the necessary fields.
				for (var i=0; i<updateFieldsArray.length; i++){
					switch(updateFieldsArray[i].toLowerCase()){
						case 'screenname':
							if(hasScreenName){
							} else {
								newUpdateFields[counter] = 'screenname';
								counter++;
							}
						break;
						case 'mobilenumber':
							if(hasMobileNumber){
							} else {
								newUpdateFields[counter] = 'mobilenumber';
								counter++;
							}
						break;
						case 'gender':
							if(hasGender){
							} else {
								newUpdateFields[counter] = 'gender';
								counter++;
							}
						break;
						case 'address1':
							if(hasAddress1){
							} else {
								newUpdateFields[counter] = 'address1';
								counter++;
							}
						break;
						default:
						
						break;
					}
				}
				if (newUpdateFields[0]){ //rebuild updateFieldsString and redirect...
					var updateFieldsString = '';
					for(var i=0; i<newUpdateFields.length; i++){
						updateFieldsString = updateFieldsString + newUpdateFields[i];
						if (i != newUpdateFields.length-1){
							updateFieldsString = updateFieldsString + ',';
						}
					}
				}
				if (isLoggedIn){
					if (updateFieldsString){
						window.location.href='/nikeos/p'+category+locale+'/profile?page=update&fields='+updateFieldsString+'&continueURL='+continueURL;
					} else { 
						alert('all good - continue to default action!');
					}
				} else {
					if (updateFieldsString){
						window.location.href='/nikeos/p'+category+locale+'/profile?page=regsiter&fields='+updateFieldsString+'&continueURL='+continueURL;
					} else {
						window.location.href='/nikeos/p'+category+locale+'/profile?page=regsiter&continueURL='+continueURL;
					}
				}
			});
			return false; //don't send to href
		});
	}
}
