﻿var one_provider = $('body').attr('id');

$(document).ready(function(){
	logMetric({ page: 'landing-' + one_provider, action: "register_load" });
	
	jQuery.validator.addMethod('nsm', function(value, element){
		return this.optional(element) || !(/^[^+]+@nutshellmail\.com$/i.test(value));
	}, 'Enter your main email address.');
	
	// Disable enter submitting forms (enter gets fb popup blocked)
	$('input').keypress(function(e){if (e.keyCode == 13) return false;});
	validator = jQuery(".one_form").validate({
		rules: {
			primary_email: {
				required: true,
				email: true,
				remote: "/register/webmethods.aspx/PrimaryEmailAddressValid",
				nsm: true
			}
		},
		messages: {
			primary_email: {
				required: "Enter your main email address.",
				email: "Enter your main email address.",
				remote: "This email address has already been registered with NutshellMail."
			}
		},
		errorPlacement: function(error, element) {
			error.appendTo(element.parent());
		},
		submitHandler: function(form) {
			$(form).children('input').each(function(){
				$(this).attr('id', $(this).attr('class').split(' ')[0]);
			});
			connectOne();
			return false;
		}
	});
	
	// retrieve time zone
    jQuery.ajax({
        url: "/register/webmethods.aspx/GetTimeZone",
        data: '{timeZoneOffest:' + timeZoneOffest() + '}',
        success: function(msg) {
            jQuery(".one_timezonecode").val(msg.d.TimeZoneCode);
        },
        error: function(xhr) {
            alert('Error is getTimeZone.');
        }
    });
	
	// capture emails as they are entered
    jQuery(".primary_email").blur(function() {
        logMetric({ page: "landing-" + one_provider, action: "landing_primary_email", email: $(this).val() });
    });
	
});

function addAccount(providerid, connection, username, password) {
	logMetric({ page: 'landing-' + one_provider, action: "account_begin" });

	jQuery.ajax({
		url: "/register/webmethods.aspx/AddAccount",
		data: '{providerid:' + providerid + ',connection:"' + connection + '",username:"' + username + '",password:"' + password + '"}',
		success: function(data) {
			logMetric({ page: 'landing-' + one_provider, action: "account_complete" });
			userRegister();
			//setHelperAddAct(jQuery("#update #provider").length);
		},
		error: function(xhr) {
			var response = JSON.parse(xhr.responseText);
			logMetric({ page: 'landing-' + one_provider, action: "account_error", error: JSON.stringify(response.Message) });
		
			jQuery("#btn_continue").addClass("button_disabled");
			alert(response.ExceptionType);
			unloadSample();
		}
	});
}

function timeZoneOffset() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
	return 0 - (jan1 - jan2) / (1000 * 60);
}

function userRegister() {
	// Generate password
	var pw = Math.floor(Math.random() * 1000000000000);
	$('form .one_password, form .one_password2').val(pw);
	
	logMetric({ page: 'landing-' + one_provider, action: "register_create" });

	jQuery.ajax({
		url: "/register/webmethods.aspx/CreateUser",
		data: '{data:' + JSON.stringify(jQuery(":input").serializeArray()) + '}',
		success: function(msg) {
			logMetric({ page: 'landing-' + one_provider, action: "register_complete" });
			window.location = "/register/complete/";
		},
		error: function(xhr) {
			logMetric({ page: 'landing-' + one_provider, action: "register_error" });
			var response = JSON.parse(xhr.responseText);
			switch (response.Message) {
				case "DuplicateUserName": AlertDialog("alertFailUser", "Email Already Exists", "The email address you entered is already in our system. Please enter another email address or contact support. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
				case "InvalidUserName": AlertDialog("alertFailUser", "Invalid Email", "The email address you entered does not apprear to be valid. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
				case "UserRejected": AlertDialog("alertFailInvalid", "Invalid Data Entry", "There was a problem with the information you submitted. Please verify that the information you entered was correct and then try to resubmit this form. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
				case "InvalidPassword": AlertDialog("alertFailUser", "Invalid Password", "The password you entered is not valid please choose a more secure password and hit Continue. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
				case "DuplicateProviderUserKey": AlertDialog("alertFailInvalid", "Invalid Data Entry", "There was a problem with the information you submitted. Please verify that the information you entered was correct and then try to resubmit this form. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
				default: AlertDialog("alertFailInvalid", "Invalid Data Entry", "There was a problem with the information you submitted. Please verify that the information you entered was correct and then try to resubmit this form. If you continue to experience problems, please contact NutshellMail Support at <a href=\"mailto:support@nutshellmail.com\">support@nutshellmail.com</a>."); break;
			}
		}
	});
}

function connectTwitter() {
	var windowWidth = 780;
	var windowHeight = 405;
	var myleft = (screen.width) ? (screen.width - windowWidth) / 2 : 100;
	var mytop = (screen.height) ? (screen.height - windowHeight - 100) / 2 : 100;
	var properties = "width=" + windowWidth + ",height=" + windowHeight + ", top=" + mytop + ",left=" + myleft + ",scrollbars=no";
	var win = window.open("/providers/twitter/popup/default.aspx", "twitter", properties);
	logMetric({ page: 'landing-' + one_provider, action: "twitter_click" });
	if (win) oneSubmitted();
	else alert('Please click submit once more.  Thanks!');
}

function connectTwitter_callback(name, key, secret) {
	logMetric({ page: 'landing-' + one_provider, action: "twitter_callback" });
	addAccount(75, 'TWITTER', name, key + "|" + secret);
	logMetric({ page: 'landing-' + one_provider, action: "twitter_complete" });
}

function connectLinkedIn() {
    logMetric({ page: 'landing-' + one_provider, action: "linkedin_click", provider: 76, status: 0 });

    var windowWidth = 830;
    var windowHeight = 420;
    var myleft = (screen.width) ? (screen.width - windowWidth) / 2 : 100;
    var mytop = (screen.height) ? (screen.height - windowHeight - 200) / 2 : 100;
    var properties = "width=" + windowWidth + ",height=" + windowHeight + ", top=" + mytop + ",left=" + myleft + ",scrollbars=no";
    var win = window.open("/providers/LinkedIn/popup/default.aspx", "LinkedIn", properties);
	if (win) oneSubmitted();
	else alert('Please click submit once more.  Thanks!');
}

function connectLinkedIn_callback(name, key, secret) {
	logMetric({ page: 'landing-' + one_provider, action: "linkedin_callback" });
    addAccount(76, 'LINKEDIN', name, key + "|" + secret);
	logMetric({ page: 'landing-' + one_provider, action: "linkedin_complete" });
}

function connectMySpace() {
    var windowWidth = 580;
    var windowHeight = 480;
    var myleft = (screen.width) ? (screen.width - windowWidth) / 2 : 100;
    var mytop = (screen.height) ? (screen.height - windowHeight - 100) / 2 : 100;
    var properties = "width=" + windowWidth + ",height=" + windowHeight + ", top=" + mytop + ",left=" + myleft + ",scrollbars=no";
    var win = window.open("/providers/myspace/popuproa/default.aspx", "myspace", properties);
	logMetric({ page: 'landing-' + one_provider, action: "myspace_click" });
	if (win) oneSubmitted();
	else alert('Please click submit once more.  Thanks!');
}

function connectMySpace_callback(name, key, secret) {
    logMetric({ page: 'landing-' + one_provider, action: "myspace_callback" });
    addAccount(77, 'MYSPACE', name, key + "|" + secret);
    logMetric({ page: 'landing-' + one_provider, action: "myspace_complete" });
}

function oneSubmitted(){
	var par = $('#one_primary_email').parent();
	par.children(':submit').attr('disabled', 'disabled');
	par.children('.one_submit').css('opacity', 0.5).css('cursor', 'default');
	par.append('<p style="margin-bottom: 0;"><img src="http://static.ak.facebook.com/images/loaders/indicator_blue_small.gif"/> &nbsp;This takes about 10 seconds.</p>');
}

function timeZoneOffest() {
    var rightNow = new Date();
    var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
    var temp = jan1.toGMTString();
    var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
    return 0 - (jan1 - jan2) / (1000 * 60);
}