﻿/// <reference path="../jq/jquery.intellisense.js"/>

var setuppage = {
	// properties
	channels: null,
	selectedChannel: null,
	otherchannelmodal: '#other-channel-modal',
	otherchannelsavebutton: '#other-channel-save-button',
	savingtext: 'Saving',

	// methods
	init: function (_channels) {
		setuppage.channels = _channels;

		// Prevent form submit (especially for google chrome)
		$('.blnfrm').submit(function () {
			return false;
		});

		$('.delchnl').live('click', function () {
			setuppage.removeChannel($(this));
		});

		$('.add-channel').click(function () {
			setuppage.showBalloon($(this).attr('rel'));
		});

		// Cancel balloon popup
		$('.abtcls').click(function () {
			setuppage.closeBalloon();
		});

		// Finish buttom
		$('#startbutton').click(function () {
			setuppage.finishSetup();
		});

		// Resolve channel hostname
		$('#sdusername').change(function () {
			setuppage.resolveHostname();
		});

		// Check button click
		$('#check-button').click(function () {
			setuppage.checkCredentials();
		});

		// Keypress in username
		$('#sdusername').keypress(function (e) {
			var code = (e.keyCode ? e.keyCode : e.which);
			if (code == 27) {
				$('.abtcls').click();
			}
		});

		// Keypress in password
		$('#sdpassword').live('keypress', function (e) {
			var code = (e.keyCode ? e.keyCode : e.which);
			if (code == 13) {
				$('#check-button').click();
			}
			else if (code == 27) {
				$('.abtcls').click();
			}
		});

		// The text 'password' in the password field
		$('#sdpassword').focus(unvalpw);

		$('#sdpin').live('keypress', function (e) {
			var code = (e.keyCode ? e.keyCode : e.which);
			if (code == 13) {
				$('#check-button').click();
			}
			else if (code == 27) {
				$('.abtcls').click();
			}
		});

		// error popup
		$('#channel-error-modal').jqm({ modal: 'true', onShow: function (hash) {
			hash.w.show();
			// Register usage
			analytics.track('Channel setup error');
		}, onHide: function (hash) {
			hash.w.hide();
			hash.o.remove();
		}
		}),

        $('#channel-error-modal').find('.modal-close').click(function () { $('#channel-error-modal').jqmHide(); }),

		$('#fbconnect-button').click(function () {
			FB_RequireFeatures(["Api"], function () {
				FB.Facebook.init(facebook.fbApiKey, "/xd_receiver.htm");
				FB.Connect.requireSession(function () {
					FB.Facebook.apiClient.users_hasAppPermission('offline_access', function (result, exception) {
						if (result == 0) {
							// Ask for extended permissions
							FB.Connect.showPermissionDialog('offline_access, read_stream, publish_stream, read_mailbox', function (res) {
								setuppage.checkFbCredentials();							
							});
						} else {
							setuppage.checkFbCredentials();
						}
					});
				});
			});
		});

		$(document).bind('CHANNEL_LIST_UPDATED', function () {
			setuppage.reset();
		});

		// In case we allready have configured channels
		$(document).trigger('CHANNEL_LIST_UPDATED');

		// Other Channel
		$(setuppage.otherchannelmodal).jqm({ trigger: '.other-channel-button', modal: 'true', center: false, onShow: function (hash) {
			hash.w.show();
			setuppage.resetOtherChannelPopup();

			// Register usage
			analytics.track('Other channel modal');

			/* TODO :
			var attr = hash.t.rel;
			var attrs = hash.t.rel.toString().split('|');
			setuppage.selectChannel(attrs[0]);
			setuppage.updateeditfiels(attrs[1]);
			*/
		}, onHide: function (hash) {
			hash.w.hide();
			hash.o.remove();
		}
		});
		$(setuppage.otherchannelmodal).find('.modal-close').click(function () { $(setuppage.otherchannelmodal).jqmHide(); });
		$(setuppage.otherchannelmodal).find(setuppage.otherchannelsavebutton).click(function () { setuppage.saveotherchannel(); });
	},
	showBalloon: function (displayName) {
		// Balloon allready shown
		if (setuppage.selectedChannel != null)
			return;

		setuppage.selectChannel(displayName);
		setuppage.updatefields();

		$('#channellist').append('<li class="channelname" id="new">'
				+ '<img class="inlinechannelicon" src="' + document.contentbase + '/i/c/logo_' + displayName.toLowerCase() + '_dock.png" alt="" width="23" height="25" />');

		// Show and position balloon
		$('#auth-popup').show('normal');
		$('#auth-popup').css('top', $('#channellist').children('li:last').position().top - 3);
	},
	checkCredentials: function () {

		if (jQuery.trim($('#sdusername').val()) == '' && setuppage.selectedChannel.displayStyle != 'RedirectWithPin') {
			alert(l('Please fill in username'));
			return false;
		}

		if (jQuery.trim($('#sdpassword').val()) == '' && setuppage.selectedChannel.displayStyle != 'RedirectWithPin') {
			alert(l('Please fill in password'));
			return false;
		}

		// Track usage of feature
		analytics.track_funnel('A3');

		$('#sderror, #sdloading').addClass('hide');

		// Virual value
        var sendViral = null;
        if (setuppage.selectedChannel.displayName == 'Facebook' ||
            setuppage.selectedChannel.displayName == 'Twitter') {
            sendViral = $('#sdviral').is(':checked');
        }
		
		$.ajax({
			type: "POST",
			url: '/services/validatechannel',
			data:
				{
					'displayName': setuppage.selectedChannel.displayName,
					'hostname': $('#sdhostname').val(),
					'username': $('#sdusername').val(),
					'password': $('#sdpassword').val(),
					'sendViral': sendViral,
					'pincode': $('#sdpin').val(),
					'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
				},
			dataType: 'json',
			beforeSend: function (XMLHttpRequest) {
				$('#sderror').addClass('hide');
				$('#sdloading').removeClass('hide');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#sderror').removeClass('hide');
				$('#sdloading').addClass('hide');
			},
			success: function (data, textStatus) {
				$('#sderror').addClass('hide');
				$('#sdloading').addClass('hide');

				if (data.result == 'Success') {
					// Remove temporary placeholder and add success message
					$('#channellist').children('#new').remove();

					$('#channellist').append('<li class="channelname">'
					    + '<img class="inlinechannelicon" src="' + document.contentbase + '/i/c/logo_' + setuppage.selectedChannel.displayName.toLowerCase() + '_dock.png" alt="" width="23" height="25" />'
					    + data.username + ' | <a class="delchnl" rel="' + setuppage.selectedChannel.displayName + '|' + data.username + '" relid="' + data.newChannelId + '">' + l('Remove')
					    + '</a><img class="setupverifiediconaccount" alt="verified" src="' + document.contentbase + '/i/icon_verified.png" /></li>');

					setuppage.closeBalloon();

					if (typeof (toolbar) != 'undefined' && toolbar.exists == true)
						toolbar.refresh();

				} else {
					$('#channel-in-error').html(setuppage.selectedChannel.displayName);

					if (jQuery.trim(data.message).length > 0) {
						// Show detailed message if there is one
						$('#channel-error-custom-text').replaceWith('<li id="channel-error-custom-text">' + data.message + '</li>');
						$('#channel-error-custom-text').show();
					}
					else {
						$('#channel-error-custom-text').hide();
					}

					// AuthFailure, etc. Show generic error message
					$('#channel-error-modal').jqmShow();
				}
			}
		});
	},
	checkFbCredentials: function () {
		// Track usage of feature
		analytics.track_funnel('A3');

		$('#sderror, #sdloading').addClass('hide');

		$.ajax({
			type: "POST",
			url: '/services/validatefbchannel',
			data: { 'sendviral': $('#sdviral').is(':checked') },
			dataType: 'json',
			beforeSend: function (XMLHttpRequest) {
				$('#sderror').addClass('hide');
				$('#sdloading').removeClass('hide');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#sderror').removeClass('hide');
				$('#sdloading').addClass('hide');
			},
			success: function (data, textStatus) {
				$('#sderror').addClass('hide');
				$('#sdloading').addClass('hide');

				if (data.result == 'Success') {
					// Remove temporary placeholder and add success message
					$('#channellist').children('#new').remove();

					$('#channellist').append('<li class="channelname">'
					    + '<img class="inlinechannelicon" src="' + document.contentbase + '/i/c/logo_' + setuppage.selectedChannel.displayName.toLowerCase() + '_dock.png" alt="" width="23" height="25" />'
					    + data.username + ' | <a class="delchnl" rel="' + setuppage.selectedChannel.displayName + '|' + data.username + '" relid="' + data.newChannelId + '">' + l('Remove')
					    + '</a><img class="setupverifiediconaccount" alt="verified" src="' + document.contentbase + '/i/icon_verified.png" /></li>');

					setuppage.closeBalloon();

				} else {
					$('#channel-in-error').html(setuppage.selectedChannel.displayName);

					if (jQuery.trim(data.message).length > 0) {
						// Show detailed message if there is one
						$('#channel-error-custom-text').replaceWith('<li id="channel-error-custom-text">' + data.message + '</li>');
						$('#channel-error-custom-text').show();
					}
					else {
						$('#channel-error-custom-text').hide();
					}

					// AuthFailure, etc. Show generic error message
					$('#channel-error-modal').jqmShow();
				}
			}
		});
	},
	saveotherchannel: function () {
		var username = $(setuppage.otherchannelmodal).find('#otherchanneleditusername').val();
		var password = $(setuppage.otherchannelmodal).find('#otherchanneleditpassword').val();
		var channeltype = $(setuppage.otherchannelmodal).find("input[name='otherchanneledittype']:checked");
		var incomingserver = $(setuppage.otherchannelmodal).find('#otherchannelincominghostname').val();
		var incommingport = $(setuppage.otherchannelmodal).find('#otherchannelincomingport').val();
		var incommingssl = $(setuppage.otherchannelmodal).find('#otherchannelincomingssl').is(':checked');
		var outgoingserver = $(setuppage.otherchannelmodal).find('#otherchanneloutgoinghostname').val();
		var outgoingport = $(setuppage.otherchannelmodal).find('#otherchanneloutgoingport').val();
		var outgoingssl = $(setuppage.otherchannelmodal).find('#otherchanneloutgoingssl').is(':checked');

		$.ajax({
			type: "POST",
			url: '/services/validateotherchannel',
			data: {
				'username': username,
				'password': password,
				'channeltype': channeltype,
				'incomingserver': incomingserver,
				'incommingport': incommingport,
				'incommingssl': incommingssl,
				'outgoingserver': outgoingserver,
				'outgoingport': outgoingport,
				'outgoingssl': outgoingssl
			},
			dataType: 'json',
			beforeSend: function (XMLHttpRequest) {
				var height = $(setuppage.otherchannelmodal).find('.inner-other-channel-modal').height();
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal').css('height', height);
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal .row').addClass('hidden');
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal').addClass('loading');
				$(setuppage.otherchannelmodal).find('.status-list ul li').remove();
				$(setuppage.otherchannelmodal).find('.status-list ul').append('<li class="loading" style="padding-top:' + (height / 2 + 28) + 'px">' + setuppage.savingtext + '</li>');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal').removeClass('loading');
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal div:hasClass("row")').removeClass('hidden');
				$(setuppage.otherchannelmodal).find('.inner-other-channel-modal').css('height', 'auto');
				$(setuppage.otherchannelmodal).find('.status-list ul li').remove();
				$(setuppage.otherchannelmodal).find('.status-list ul').append('<li class="error"><em>' + textStatus + '</em></li>');
				$(setuppage.otherchannelmodal).find('.row').removeClass('hide');
			},
			success: function (data) {
				if (!data) {
					$(setuppage.otherchannelmodal).find('.status-list ul li').remove();
					$(setuppage.otherchannelmodal).find('.status-list ul').append('<li class="error"><em>' + l('Oops, something went wrong. Please contact support@inbox2.com') + '</em></li>');
					$(setuppage.otherchannelmodal).find('.row').removeClass('hide');
				}
				else {
					// TODO: $('#channellist').find('[relid="' + channelid + '"]').parent().remove();
					$(setuppage.otherchannelmodal).jqmHide();
					setuppage.resetOtherChannelPopup();
				}
			}
		});
	},
	removeChannel: function (channel) {
		if ($('#noinvite').length == 0) {
			var attr = $(channel).attr('rel');
			var relid = $(channel).attr('relid');

			$.post('/services/removechannel', { 'channelid': relid }, function (data) {

				$('#channellist').find('[rel="' + attr + '"]').parent().remove();

				if ($('#channellist').children('.channelname').length == 0) {
					$('.start-button-container').hide();
					$('.channel-list-message').hide();
				}
			}, 'json');
		}
	},
	closeBalloon: function () {
		$('.bln').hide('slow');
		$('#sdpassword').val('');
		$('#sdpassword').trigger('blur');
		$('#channellist').children('#new').remove();

		setuppage.selectedChannel = null;

		$(document).trigger('CHANNEL_LIST_UPDATED');
		$('#add-channel-error-box').hide();

	},
	resolveHostname: function () {
		var domain = setuppage.selectedChannel.defaultDomain;

		var username = jQuery.trim($('#sdusername').val());

		if (domain == '') {
			return;
		}
		else if (username == '') {
			return;
		}

		if (isValidEmail(username)) {
			return;
		}
		else if (username.indexOf('@') > -1) {
			return;
		}

		$('#sdusername').val(username + '@' + domain);
	},
	finishSetup: function () {
		analytics.track_funnel('A4');

		window.location = '/inbox?finishSetup=true';
	},
	selectChannel: function (displayName) {
		// Find channel config for given channel
		for (var i in setuppage.channels) {
			if (displayName == setuppage.channels[i].displayName)
				setuppage.selectedChannel = setuppage.channels[i];
		}
	},
	updatefields: function () {

		$('#channel-login-box').show();
		$('#fb-login-box').hide();

		$('#click-on-login-label').hide();
		
		$('.hostnametf').hide();
		$('.usernametf').show();
		$('.passwordtf').show();		
		$('.viralcb').hide();
		$('.pintf').hide();
		
		$('#check-button').show();
		$('#redirect-button').hide();
		$('#fbconnect-button').hide();

		// Text field values
		$('#sdhostname').val(l('hostname')).focus(unval);
		$('#sdusername').val(l('username')).focus(unval);
		$('#sdpassword').val(l('password')).focus(unval);

		// Channel logo and displayname
		$('#login-to-image')
			.attr('src', document.contentbase + '/i/c/logo_' + setuppage.selectedChannel.displayName.toLowerCase() + '_inline.png')
			.attr('alt', setuppage.selectedChannel.displayName);

		$('.login-to-channel').text(setuppage.selectedChannel.displayName);
		$('.abthelp').attr('href', helpUrlBase + setuppage.selectedChannel.displayName.toLowerCase());

		// Enable viral checkbox
        if (setuppage.selectedChannel.displayName == 'Facebook' ||
            setuppage.selectedChannel.displayName == 'Twitter') {
            $('#sbviral').attr('checked', true);
            $('.viralcb').show();
        }
		
		if (setuppage.selectedChannel.displayStyle == 'FbConnect') {
			$('.usernametf').hide();
			$('.passwordtf').hide();
			$('#check-button').hide();
			$('#fbconnect-button').show();
		}
		else if (setuppage.selectedChannel.displayStyle == 'Advanced') {
			$('.hostnametf').show();
		}
		else if (setuppage.selectedChannel.displayStyle == 'Redirect') {
			$('#click-on-login-label').show();
			$('.usernametf').hide();
			$('.passwordtf').hide();
			$('#redirect-button').show();
			$('#redirect-button').removeClass('hidden');
			$('#check-button').hide();
			setuppage.buildRedirect();
		}
		else if (setuppage.selectedChannel.displayStyle == 'RedirectWithPin') {
			$('#click-on-login-label').show();
			$('.usernametf').hide();
			$('.passwordtf').hide();
			$('#redirect-button').show();
			$('#redirect-button').removeClass('hidden');
			$('#check-button').hide();
			setuppage.buildRedirect();
		}
	},
	reset: function () {
		var count = $('#channellist').children('.channelname').length;

		if (count == 0) {
			$('.start-button-container').hide();
			$('.channel-list-message').hide();
		} else {
			$('.start-button-container').show();
			$('.channel-list-message').show();
		}
	},
	resetOtherChannelPopup: function () {
		$(setuppage.otherchannelmodal).find('input[type="text"]').val('');
		$(setuppage.otherchannelmodal).find('input[type="password"]').val('');
		$(setuppage.otherchannelmodal).find('input[type="checkbox"]').attr('checked', false);
		$(setuppage.otherchannelmodal).find('input[type="radio"]').attr('selected', false);
		$(setuppage.otherchannelmodal).find('input[type="radio"]:first').attr('checked', 'checked');
	},
	buildRedirect: function () {
		$('#sderror, #sdloading').addClass('hide');

		$.ajax({
			type: "POST",
			url: '/services/validatechannel',
			data:
				{
					'displayName': setuppage.selectedChannel.displayName,
					'hostname': $('#sdhostname').val(),
					'username': $('#sdusername').val(),
					'password': $('#sdpassword').val(),
					'pincode': $('#sdpin').val(),
					'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
				},
			dataType: 'json',
			beforeSend: function (XMLHttpRequest) {
				$('#sderror').addClass('hide');
				$('#sdloading').removeClass('hide');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#sderror').removeClass('hide');
				$('#sdloading').addClass('hide');
			},
			success: function (data, textStatus) {
				$('#sderror').addClass('hide');
				$('#sdloading').addClass('hide');

				if (data.result == 'RedirectWithPin') {
					$('#sdhostname').val('');
					$('#sdusername').val('');
					$('#sdpassword').val('');

					$('#redirect-button').attr('href', "javascript:window.open('" + data.uri + "', 'Login', 'height=650,width=1000');setuppage.switchToLogin();");
				}
				else if (data.result == 'Redirect') {
					$('#sdhostname').val('');
					$('#sdusername').val('');
					$('#sdpassword').val('');

					$('#redirect-button').attr('href', data.uri);
				}
				else {
					$('#channel-in-error').html(setuppage.selectedChannel.displayName);

					if (jQuery.trim(data.message).length > 0) {
						// Show detailed message if there is one
						$('#channel-error-custom-text').replaceWith('<li id="channel-error-custom-text">' + data.message + '</li>');
						$('#channel-error-custom-text').show();
					}
					else {
						$('#channel-error-custom-text').hide();
					}

					// AuthFailure, etc. Show generic error message
					$('#channel-error-modal').jqmShow();
				}
			}
		});
	},
	switchToLogin: function () {
		$('#click-on-login-label').hide();
		$('.pintf').show();
		$('#sdpin').val(l('Please enter pincode')).focus(unval);
		$('#redirect-button').hide();
		$('#check-button').show();
	}
}