function prodAppender(baseurl)
{
	//sample usage:
	//var mycontent = prodAppender('/daily_caloric_goal/modal');

	var server_name = top.location.host;
	if (server_name.search(/resoluted/i) == -1 && server_name.search(/fitnessmagazine/i) == -1 )
	{
		//not found - just return the url since we are not on prod
		return new String(baseurl).valueOf();
	}
	else
	{
		//found - return url prepended with /fitness-tracker as required for production
		return new String("/fitness-tracker"+baseurl).valueOf();
	}
}

jQuery(document).ready(function(){ 

    function registerUser() {
    	//alert('registerUser called');
    	$('#regStep1Btn').hide();
    	$('#regStep1BtnLoader').show();
      var email = $('#email_registration').val();
      var first_name = $('#first_name').val();
      var password = $('#pwd_registration').val();
      var display_name = $('#display_name').val();
      var m_id = $('#m_id').val();
      var opt_in = $('#opt_in').is(':checked');

	  var ajaxreg = prodAppender("/registration/ajaxreg");	  
      $.ajax({
         type: "POST",
         url: ajaxreg,
         data: "email=" + email + 
          "&first_name=" + first_name +
          "&password=" + password + 
          "&display_name=" + display_name + 
          "&m_id=" + m_id +
          "&opt_in=" + opt_in,
         dataType: "json",
         success: function(msg){
          if (msg.status == 'error')
          {
          	//alert(msg.errorText);
    		$('#regStep1BtnLoader').hide();
    		$('#regStep1Btn').show();
            var label = $('#errorBox');
            label.html(msg.errorText);
            label.slideDown('slow');
            return false;
          }
          else if (msg.status == 'ok')
          {
          	//alert("here:"+msg.m_id[0]);	//ben

			// send data to omniture
			referrer = "fitnesstracker-reg-step1";
			s.pageName = 'Registration:Step2:7665:'+ referrer;
			s.channel = 'YCDI';
			s.server = 'www.fitness.com';
			s.eVar6 = '7665:Page2:'+ referrer;
			s.eVar9 = 'Registration:Step2:7665:'+ referrer;
			s.eVar14 = 'Registration';
			s.eVar18 = '7665';
			s.eVar24 = 'TRUE';
			s.prop1 = 'Registration';
			s.prop7 = 'TRUE';
			
			var randomnumber=Math.floor(Math.random()*10000001)+10000000;
			s.events = 'scRemove:'+randomnumber;
			//void(s.t());          	
			var s_code=s.t();if(s_code)document.write(s_code);
			
          	$('#regStep1BtnLoader').hide();
            $('#regStep1Btn').show();
            $('#m_id').val(msg.m_id[0]);
            //api.click(1);
            $('#regStep1').hide();
            $('.sub-reg-1 a').removeClass('active');
            $('#regStep2').show();
            $('.sub-reg-2 a').addClass('active');

            $('#newsletters').html(msg.nl_html);
              //checkbox - fitness shortcuts
             $("#newsletter3").click(function(){
                 if( $(this).is(':checked') ) {              
                    $("#newsletterShortcuts").removeClass('hide');
                 } else {
                    $("#newsletterShortcuts").addClass('hide');
                 }
             });
          }
         }
       });
      return true;
    }

    function newsletterSignup() {
    
    	$('#regStep2Btn').hide();
    	$('#regStep2BtnLoader').show();

      plan_id = $('input:radio:checked').val();

      var nl = '';
      $('input[name=nl]:checked').each(function(i, checked){
          nl += $(checked).val() + ',';
        })

      var snl = '';
      $('input[name=snl]:checked').each(function(i, checked){
          snl += $(checked).val() + ',';
        })

      var profileid = $('#m_id').val();
      
	  var ajaxnl = prodAppender("/registration/ajaxnl");      
      $.ajax({
         type: "POST",
         url: ajaxnl,
         data: "plan_id=" + plan_id + 
          "&nl=" + nl +
          "&snl=" + snl +
          "&profileid=" + profileid,
         dataType: "json",
         success: function(msg){
          if (msg.status == 'error')
          {
          	$('#regStep2BtnLoader').hide();
          	$('#regStep2Btn').show();
            var label = $('#errorBox');
            label.html(msg.errorText);
            label.slideDown('slow');
            return false;
          }
          else if (msg.status == 'ok')
          {
          	$('#regStep2BtnLoader').hide();
          	$('#regStep2Btn').show();
            $('#regStep2').hide();
            $('.sub-reg-2 a').removeClass('active');
            $('#regStep3').show();
            $('.sub-reg-3 a').addClass('active');
          }
         }
       });

      return false;

    }

    function setWeight() {

      var current = $('#current_weight').val();
      var goal = $('#goal_weight').val();
      var avatar_id = $('#avatar_id').val();
      
      $('#registerBtn').hide();
      $('#registerBtnLoader').show();
      
	  var ajaxweight = prodAppender("/registration/ajaxweight");      
      $.ajax({
         type: "POST",
         url: ajaxweight,
         data: "current=" + current + 
          "&goal=" + goal +
          "&avatar_id=" + avatar_id,
         dataType: "json",
         success: function(msg){
          if (msg.status == 'error')
          {
          	$('#registerBtnLoader').hide();
          	$('#registerBtn').show();
            var label = $('#errorBox');
            label.html(msg.errorText);
            label.slideDown('slow');
            return false;
          }
          else if (msg.status == 'ok')
          {
             window.location = prodAppender('/homepage');
          }
          else if (msg.status == 'invited')
          {
             window.location = prodAppender('/my_team');
          }
         }
       });

      return false;

    }

		$("ul.regTabs").tabs("div.panes > div",{
			//effect: 'fade',
			current: 'active'
		});
		
		// register the tabs object so that we can reference the api
		var api = $("ul.regTabs").tabs();	 	
   	 	
   	 	$('#loginBtn').click(function() {
   	 		$('#errorBox').hide();
   	 		
   	 		if (!strCheck('#email_login', '#errorBox', 'ERROR: You must enter your email address', 'Email Address')) return false;
   	 		if (!emailCheck('#email_login', '#errorBox', 'ERROR: You must enter a valid email address')) return false;
   	 		
   	 		if (!strCheck('#pwd_login', '#errorBox', 'ERROR: You must enter your password', 'Password')) return false;
        var user = $("#email_login").val(); 
        var pass = $("#pwd_login").val(); 
        $(this).hide();
        $('#loginBtnLoader').show();


    var reg_login = prodAppender("/registration/login");    
    $.ajax({
       type: "POST",
       url: reg_login,
       data: "user=" + user + "&password=" + pass,
       dataType: "json",
       success: function(msg){
        if (msg.status == "good")
        {
         window.location = prodAppender('/homepage');
        }
        if (msg.status == "pid")
        {
         window.location = prodAppender('/user/profile?pid=' + msg.pid);
        }
        else if(msg.status == "bad")
        {
          $('#loginBtnLoader').hide();
          $('#loginBtn').show();
          alert('The login and password do not match.' );
        }
        else if(msg.status == "eh")
        {
          $('#loginBtnLoader').hide();
          $('#loginBtn').show();
          $('#email_registration').val(user);
          $('#email_registration').css({'color' : '#dadada'});

          $('#pwd_registration').val(pass);
          $('#pwd_registration').css({'color' : '#dadada'});

          $('#first_name').val(msg.firstname);
          $('#first_name').css({'color' : '#dadada'});
      
          $('#display_name').val(msg.displayname);
          $('#display_name').css({'color' : '#dadada'});

          $('#m_id').val(msg.mid[0]);
          registerUser();
        }
        
       }
     });
    return false;
        


   	 	});
   	 	
   	 	$('#forgotBtn').click(function() {
   	 		$('#errorBox').hide();
			
			if (!strCheck('#email_forgot', '#errorBox', 'ERROR: You must enter your email address', 'Email Address')) return false;
   	 		if (!emailCheck('#email_forgot', '#errorBox', 'ERROR: You must enter a valid email address')) return false;

      		var email = $("#email_forgot").val(); 
          	$(this).hide();
          	$('#forgotBtnLoader').show();

          /* post to forgot function */
      var reg_forgot = prodAppender("/registration/forgot");                
      $.ajax({
         type: "POST",
         url: reg_forgot,
         data: "email=" + email,
         success: function(msg){
          if (msg == 1)
          {
          	$('#forgotBtnLoader').hide();
          	$('#forgotBtn').show();
            alert('Password sent to ' + email);
          }
          else
          {
          	$('#forgotBtnLoader').hide();
          	$('#forgotBtn').show();
            alert('Failed to find profile for ' + email + '. Please check and try again');
          }
         }
       });
      return false;
		});
		
		api.onBeforeClick(function(e, tabIndex) { 
			if (tabIndex == 1) {
        return false;
			}
			if (tabIndex == 2) {
        return false;
			}
			if (tabIndex == 3) {
        return false;
			}
		});
		
		$('#regStep1Btn').click(function() {
        if (!strCheck('#first_name', '#errorBox', 'ERROR: You must enter your first name', 'First Name')) {
        return false;
   	 		}
   	 		if (!strCheck('#email_registration', '#errorBox', 'ERROR: You must enter your email address', 'Email')) {
   	 			return false;
   	 		}
   	 		if (!emailCheck('#email_registration', '#errorBox', 'ERROR: You must enter a valid email address')) {
   	 			return false;
   	 		}
   	 		if (!strCheck('#pwd_registration', '#errorBox', 'ERROR: You must enter your password', 'Password')) {
   	 			return false;
   	 		}
   	 		if (!strCheck('#display_name', '#errorBox', 'ERROR: You must enter your display name', 'Display Name')) {
   	 			return false;
   	 		}
   	 		if (!dnCheck('#display_name', '#errorBox', 'ERROR: Your display name must be between 3 and 15 characters, start with a letter, and the remaining characters can be alpha, numeric or underscore or dash.', 'Display Name')) {
   	 			return false;
   	 		}

        $('#errorBox').hide();
        registerUser();  	 		
		});

		
		$('#regStep2Btn').click(function() {
			if (!radioCheck('#radioPlanGroup input:radio:checked', '#errorBox', 'ERROR: You must choose a newsletter')) {
   	 			return false;
   	 		}
   	 		if ( $('#newsletter3').is(':checked') ) {
   	 			if (!radioCheck('#newsletterShortcuts input:checkbox:checked', '#errorBox', 'ERROR: You must at least one Fitness Shortcut Newsletter')) {
	   	 			return false;
	   	 		}
   	 		}
			$('#errorBox').hide();
      newsletterSignup();
		});
		
		
		$('#registerBtn').click(function() {
   	 		$('#errorBox').hide();
   	 		
   	 		if (!strCheck('#first_name', '#errorBox', 'ERROR: You must enter your first name', 'First Name')) {
   	 			api.click(0);
   	 			return false;
   	 		}
   	 		if (!strCheck('#email_registration', '#errorBox', 'ERROR: You must enter your email address', 'Email')) {
   	 			api.click(0);
   	 			return false;
   	 		}
   	 		if (!emailCheck('#email_registration', '#errorBox', 'ERROR: You must enter a valid email address')) {
   	 			api.click(0);
   	 			return false;
   	 		}
   	 		if (!strCheck('#pwd_registration', '#errorBox', 'ERROR: You must enter your password', 'Password')) {
   	 			api.click(0);
   	 			return false;
   	 		}

   	 		if (!strCheck('#display_name', '#errorBox', 'ERROR: You must enter your display name', 'Display Name')) {
   	 			api.click(0);
   	 			return false;
   	 		}
   	 		   	 		
   	 		
   	 		if (!radioCheck('#radioPlanGroup input:radio:checked', '#errorBox', 'ERROR: You must choose a newsletter')) {
   	 			api.click(1);
   	 			return false;
   	 		}
   	 		
   	 		if ( $('#newsletter3').is(':checked') ) {
   	 			if (!radioCheck('#newsletterShortcuts input:checkbox:checked', '#errorBox', 'ERROR: You must at least one Fitness Shortcut Newsletter')) {
	   	 			api.click(1);
	   	 			return false;
	   	 		}
   	 		}
   	 		
   	 		
   	 		if (!strCheck('#goal_weight', '#errorBox', 'ERROR: You must enter your goal weight', 'Enter Your Goal Weight')) return false;
   	 		if (!numCheck('#goal_weight', '#errorBox', 'integer', 0, 'ERROR: Your goal weight must be an integer value')) return false;
   	 		
   	 		if (!strCheck('#current_weight', '#errorBox', 'ERROR: You must enter your current weight', 'Enter Your Current Weight')) return false;
   	 		if (!numCheck('#current_weight', '#errorBox', 'integer', 0, 'ERROR: Your current weight must be an integer value')) return false;

        setWeight();
   	 		
   	 	});
   	 	
  $('#email_login').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#loginBtn').click();
    }
  });

  $('#pwd_login').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#loginBtn').click();
    }
  });

  $('#email_forgot').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#forgotBtn').click();
    }
  });

  $('#first_name').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#regStep1Btn').click();
    }
  });

  $('#email_registration').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#regStep1Btn').click();
    }
  });

  $('#pwd_registration').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#regStep1Btn').click();
    }
  });

  $('#display_name').bind('keypress', function(e) {
    if(e.keyCode==13){
      $('#regStep1Btn').click();
    }
  });
		
});
