﻿function addAccount(providerid, connection, displayname, username, password, next) {
    logMetric({ page: 'home', action: "account_begin" });

	//console.log('{providerid:' + providerid + ',connection:"' + connection + '",displayname:"' + displayname + '",username:"' + username + '",password:"' + password + '"}');
    jQuery.ajax({
        url: "/register/webmethods.aspx/AddAccount",
        data: '{providerid:' + providerid + ',connection:"' + connection + '",displayname:"' + displayname + '",username:"' + username + '",password:"' + password + '"}',
        success: function (data) {
            logMetric({ page: 'home', action: "account_complete" });
            if (next) {
				$('#dlg_page').dialog('close');
				$('#dlg_email').dialog('open');
			}
        },
        error: function (xhr) {
            var response = JSON.parse(xhr.responseText);
            logMetric({ page: 'home', action: "account_error", error: JSON.stringify(response.Message) });
            window.location = '/register/';
        }
    });
}

function connectFacebook_callback_page(uid, pages, key, secret) {
    pages = eval(pages);
	if (pages.length > 1){
		$('#dlg_page').append('<input type="hidden" id="fb_page_key" value="' + key + '">');
		$('#dlg_page').append('<input type="hidden" id="fb_page_secret" value="' + secret + '">');
		$('#dlg_page_list').empty();
		$(pages).each(function(i,v){
			$('#dlg_page_list').append('<div><label for="' + v.page_id + '"><input type="checkbox" id="' + v.page_id + '" class="dlg_page_check"/> ' + v.name + '</label></div>');
		});
		$('#dlg_page').dialog('open');
	}
	else {
		addAccount(79, 'FACEBOOK_GRAPH', pages[0].name, pages[0].page_id, key + "|" + secret, true);
		$('#home_try_facebook').css('opacity', 0.25).css('cursor', 'default').blur().unbind('click').click(function(){return false;});
	}
}

function connectFacebook_callback(uid, name, key, secret) {
	$('#fb_form').append('<p style="margin-bottom: 0;"><img src="http://static.ak.facebook.com/images/loaders/indicator_blue_small.gif"/> &nbsp;Creating your account... this takes about ten seconds.</p>');
	logMetric({ page: 'home', action: "facebook_callback" });

	jQuery.ajax({
		url: "/providers/fb/default.aspx/HasAppPerms",
		data: '{\"perms\":\"offline_access,read_stream\", \"key\":\"' + key + '\", \"secret\":\"' + secret + '\"}',
		success: function(msg) {
			if (msg.d) {
			    logMetric({ page: 'home', action: "facebook_complete" });
			    $('#referrer_source').val('home_facebook');
				addAccount(71, 'FACEBOOK', name, name, key + '|' + secret, true);
				$('#home_try_facebook').css('opacity', 0.25).css('cursor', 'default').blur().unbind('click').click(function(){return false;});
			} else {
				logMetric({ page: 'home', action: "facebook_perms_error" });
				alert('We cannot perform the selected actions with these permssions. Please click Connect and authorize the permissions.');
			}
		},
		error: function(xhr) {
			var response = JSON.parse(xhr.responseText);
			logMetric({ page: 'home', action: "facebook_error", error: JSON.stringify(response.Message) });
			window.location = '/register/';
		}
	});
}

function connectTwitter_callback(name, key, secret) {
	logMetric({ page: 'home', action: "twitter_callback" });
	$('#referrer_source').val('home_twitter');
	addAccount(75, 'TWITTER', name, name, key + "|" + secret, true);
	logMetric({ page: 'home', action: "twitter_complete" });
	$('#home_try_twitter').css('opacity', 0.25).css('cursor', 'default').blur().unbind('click').click(function(){return false;});
}

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);
}

function userRegister() {
	logMetric({ page: 'home', action: "register_create" });

	jQuery.ajax({
		url: "/register/webmethods.aspx/CreateUser",
		data: '{data:' + JSON.stringify(jQuery('#primary_email, #timezonecode, #referrer_source').serializeArray()) + '}',
		success: function(msg) {
			logMetric({ page: 'home', action: "register_complete" });
			window.location = "/register/complete/";
		},
		error: function(xhr) {
			logMetric({ page: 'home', action: "register_error" });
			var response = JSON.parse(xhr.responseText);
			alert (response.Message);
			//window.location = '/register/';
			/*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;
			}*/
		}
	});
	
	$('#dlg_email').html('<div class="dlg_wait"><p>Creating your account... &lt;10 seconds.</p><p><img src="http://facebook.com/images/loaders/indicator_blue_large.gif" /></p></div>').parent().children('.ui-dialog-buttonpane').hide();
}
			
$(document).ready(function(){
	$('#home_try_facebook').click(function(){
		var myleft = (screen.width) ? (screen.width - 480) / 2 : 100;
		var mytop = (screen.height) ? (screen.height - 460 - 100) / 2 : 100;
		var win = window.open('/providers/fb/popup/?perms=offline_access,read_stream', 'facebook', "width=480,height=460, top=" + mytop + ",left=" + myleft + ",resizable=yes", true);
		if (!win) window.location = '/register/';
		logMetric({ page: 'home', action: "facebook_click" });
		return false;
	});
	$('#home_try_twitter').click(function(){
		var myleft = (screen.width) ? (screen.width - 780) / 2 : 100;
		var mytop = (screen.height) ? (screen.height - 405 - 100) / 2 : 100;
		var win = window.open('/providers/twitter/popup/default.aspx', 'twitter', "width=780,height=405, top=" + mytop + ",left=" + myleft + ",resizable=yes", true);
		if (!win) window.location = '/register/';
		logMetric({ page: 'home', action: "twitter_click" });
		return false;
	});
	// retrieve time zone
	jQuery.ajax({
		url: "/register/webmethods.aspx/GetTimeZone",
		data: '{timeZoneOffest:' + timeZoneOffest() + '}',
		success: function(msg) {
			jQuery("#timezonecode").val(msg.d.TimeZoneCode);
			jQuery("#timezone").html(msg.d.TimeZoneName);
		},
		error: function(xhr) {
			alert('Error is getTimeZone.');
		}
	});
	jQuery.validator.addMethod('nsm', function(value, element){
		return this.optional(element) || !(/^[^+]+@nutshellmail\.com$/i.test(value));
	}, 'Enter your main email address.');
	validator = jQuery("#home_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."
            }
        },
        submitHandler: function(form) {
            logMetric({ page: "home", action: "register_create" });
			
			userRegister();
        }
    });

	$('#dlg_email').dialog({
		title: 'One last step...',
		modal: true,
		buttons: {
			'Ok': function(){$('#home_form').submit();}
		},
		autoOpen: false
	});
	
	$('#dlg_page').dialog({
		title: 'Select your page(s)',
		modal: true,
		buttons: {
			'Ok': function(){
				$('.dlg_page_check:checked').each(function(i,v){
					// next = true only when it's the last one, we only want to show the next dialog then
					/*console.log(79 + '---' + 
						'FACEBOOK_GRAPH' + '---' +
						$.trim($(v).parent().text()) + '---' +
						$(v).attr('id') + '---' +
						$('#fb_page_key').val() + "|" + $('#fb_page_secret').val() + '---' +
						(i == $('.dlg_page_check:checked').length - 1)
					);*/
					addAccount(
						79,
						'FACEBOOK_GRAPH',
						$(v).parent().children('span').text(),
						$(v).attr('id'),
						$('#fb_page_key').val() + "|" + $('#fb_page_secret').val(),
						(i == $('.dlg_page_check:checked').length - 1)
					);
				});
				if ($('.dlg_page_check:checked').length){
					$('#home_try_facebook').css('opacity', 0.25).css('cursor', 'default').blur().unbind('click').click(function(){return false;});
				}
			}
		},
		autoOpen: false
	});
	
	// Buzz rotator
	var buzz_interval = setInterval(function(){
		var current = $('.home_buzz:visible');
		var next = ($(current).next().length) ? $(current).next() : $('.home_buzz')[0];
		$(current).fadeOut('slow', function(){
			$(next).fadeIn('slow');
		});
	}, 6000);
	
	// Add video demo
	$('#home_video').html('<object width="465" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8048795&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8048795&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="465" height="300"></embed></object>');
	
	// Get recent blog entries
	/*$.ajax({
		type: 'GET',
		url: '/blog/feed/',
		dataType: 'xml',
		success: function(xml){
			$('#home_blog').text('');
			$(xml).find('item').each(function(i){
				if (i>2) return;
				var link = $(this).children('link').text();
				var entry = '<div class="home_blog_title"><h4><a href="' + link + '">' + $(this).children('title').text() + '</a></h4></div>';
				entry += '<div class="home_blog_desc"><p>' + $(this).children('description').text().replace('[...]', '<a href="' + link + '">Read more &raquo;</a>') + '</p></div>';
				$('#home_blog').append(entry);
			});
		}
	});*/
});

function stripIt(x) {
    return x.replace(/['"]/g, '');
};