goApp.addStrings({
	emailRequired: 'You forgot to enter your email address.',
	errorTitle: 'Oh dear',
	getUpdates: 'Get updates',
	invalidEmail: 'Entered email is not valid.',
	subscribed: 'We\'ll update you as we add new versions of Unison.',
	subscribeBody: 'A website visitor requested updates on Unison:\n'
		+ 'Email: %email%',
	subscribeSubject: '%email% requested updates',
	subscribeTitle: 'We shouldn\'t<br /> be long',
	subscribeFault: 'There was some kind of error and we didn\'t get your info. '
		+ 'Please submit again.',

	successTitle: 'Thanks!'
});

goApp.addErrorMessage(goApp.errors.ERR_DUPLICATION,
	'This email address was already used. Please try a different one.');
goApp.addErrorMessage(goApp.errors.ERR_EMAIL_NOT_SENT,
		'There was some kind of error and we didn\'t get your info. '
		+ 'Please submit again.');

/**
 * Init controls
 */
goApp.bgScalerInitialized = false;
goApp.activeItemIndex = -1;
$(function()
{

	goApp._initBgScale();

	// init cards toggling
	$('#cards-navigator li').click(function(oEvent){
		var oTarget = oEvent.target;

		var nIndexToShow = $(oTarget).index();
		if (nIndexToShow == goApp.activeItemIndex)
			return;

		$('#cards-navigator li:eq('+ goApp.activeItemIndex +')').removeClass('active');
		$(oTarget).addClass('active');
		$('#cards-survey .card:eq(' + goApp.activeItemIndex + ')').removeClass('active');
		$('#cards-survey .card:eq(' + nIndexToShow + ')').addClass('active');
		$('#cards-layers .card:eq(' + goApp.activeItemIndex + ')').removeClass('active');
		$('#cards-layers .card:eq(' + nIndexToShow + ')').addClass('active');

		goApp.activeItemIndex = nIndexToShow;
	});

	goApp.activeItemIndex = $('#cards-navigator li.active').index();

	goApp._initCssClasses();
	//goApp._initUrlListener();

	var fAddHover = function(JQueryItem) {$(this).addClass('hover')},
 		fRemoveHover = function(JQueryItem) {$(this).removeClass('hover')};

 	$('#subscribe-form').submit(function() {
		goApp.subscribeForUpdates();
		_gaq.push(['_trackPageview', '/getUpdates']);
		return false;
	});
	
	$('#subscribe-button').click(function() {
		goApp.subscribeForUpdates();
		_gaq.push(['_trackPageview', '/getUpdates']);
		return false;
	});
	
	$('#video-close-button')
		.hover(fAddHover, fRemoveHover)
		.click(function()
		{
			goApp.closeVideo();
		});

	$('#video-open-button, #video-start-button')
		.hover(fAddHover, fRemoveHover)
		.click(function(){goApp.playVideo();});
		
	$('#toggle-subscribe-form-link, .balloon-close-button')
		.hover(fAddHover, fRemoveHover)
		.click(function()
		{
			var oForm	= $('#subscribe-form');
			
			if (oForm.hasClass('ui-helper-hidden'))
			{
				oForm.removeClass('ui-helper-hidden');
			 	oForm.css('display','inline-block');
				//$('#subscribe-email').focus();
			}
			else
			{
				oForm.addClass('ui-helper-hidden');
			 	oForm.css('display','none');
			}
		});


    // init custom inputs
 /*
 	$('.text-field-wrap, .btn-wrap').hover(fAddHover, fRemoveHover);

 	$('.text-field-wrap input')
		.focusin(function(){
			  $(this).parent().addClass('focus');
			  $(this).val() == $(this).attr('placeholder') && ($(this).val(''));
		})
 		.focusout(function(){
			  $(this).parent().removeClass('focus');
			  $(this).val() == '' && ($(this).val($(this).attr('placeholder') || ''));

			 });

 	$('.text-field-wrap input').each(function(){
	  	var sPlaceholder = $(this).attr('placeholder');
	  	sPlaceholder && $(this).val(sPlaceholder);
	});
 */
    $('input.text-field').focusin(function(){
			  $(this).addClass('focus');
			  $(this).val() == $(this).attr('placeholder') && ($(this).val(''));
		})
 		.focusout(function(){
			  $(this).removeClass('focus');
			  $(this).val() == '' && ($(this).val($(this).attr('placeholder') || ''));

			 });
 	$('input.text-field').each(function(){
	  	var sPlaceholder = $(this).attr('placeholder');
	  	sPlaceholder && $(this).val(sPlaceholder);
	});
 	$('.btn').hover(fAddHover, fRemoveHover);

 	// init custom inputs handlers
 	$('#invitation-form').submit(function() {
		goApp.requestInvite();
		 _gaq.push(['_trackPageview', '/requestInvite']);
		return false;
	});

	$('#invitation-button').click(function() {
		goApp.requestInvite();
		_gaq.push(['_trackPageview', '/requestInvite']);
		return false;
	});
});

$(window).load(function(){
	goApp._initBgScale();
});

/**
 * Initializes background scale
 */
goApp._initBgScale = function()
{
	if (this.bgScalerInitialized)
		return;

	this.bgScalerInitialized = true;
	$('body').ezBgResize({
		img: '/images/home/jan31/page-bg.jpg'
	});
}


/**
 * Adds class names to the <body /> to be able to use
 * browser-specific css
 */
goApp._initCssClasses = function()
{
	var oBrowser = {};
	for (var sProp in $.browser)
		if ($.browser.hasOwnProperty(sProp) && sProp != 'version')
		 	oBrowser['browser'] = sProp;

	if (/chrome/i.test(navigator.userAgent))
		oBrowser.browser = 'chrome';
	else if (/safari/i.test(navigator.userAgent))
		oBrowser.browser = 'safari';
	else if (/opera/i.test(navigator.userAgent))
		oBrowser.browser = 'opera';

 	$('body')
		.addClass('is-' + oBrowser['browser'])
		.addClass('is-' + oBrowser['browser'] + parseInt($.browser.version));
};

goApp._handleDownloadAction = function()
{

	$('#screen-start').hide();
	$('#screen-download').show();

	$('#download-frame').attr('src', 'http://cn1.unison.com/download');
};

goApp._handleStartAction = function()
{

	$('#screen-download').hide();
	$('#screen-start').show();
}

goApp._initUrlListener = function()
{
	goApp._prevHashValue = null;
	goApp._urlListenInterval = setInterval(function(){
		goApp._checkUrlHash();
	}, 300);
}

// Stop playing and close video dialog
goApp.closeVideo = function()
{
	$('#video, #video-holder').hide();
	$('#video-holder iframe').remove();
}

goApp._getLocationHash = function()
{
	return document.location.hash;
}

goApp._checkUrlHash = function()
{
	if (this._prevHashValue != document.location.hash)
	{
		this._prevHashValue = document.location.hash;

		switch (document.location.hash)
		{
			case '#download':
				this._handleDownloadAction();
				break;
			default:
				this._handleStartAction();
				break;
		}
	}
}

/**
 * Plays video
 */
goApp.playVideo	= function()
{
	var oVideoRes = this._getVideoDimensions({top: parseInt($('#video-holder').css('top'))});

	$('#video, #video-holder').show();
	$('#video-holder').prepend(
		'<iframe id="test-frame" src="http://player.vimeo.com/video/35709159?title=0&amp;'
		+ 'byline=0&amp;portrait=0&amp;color=f89b1d&amp;autoplay=1" '
		+ 'width="' + oVideoRes.width
		+ '" height="' + oVideoRes.height + '" '
		+ 'frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>'
		+ '<input type="text" id="keyevent-proxy" style="position:absolute; left: -1000px; top: -1000px;'
		+ ' width: 1px; height: 1px; overflow: hidden"/>'
	);
	$('#video-holder')
		.css('width', oVideoRes.width)
		.css('height', oVideoRes.height)
		.css('margin-left', -Math.floor(oVideoRes.width/2));

	document.onkeydown = document.onkeydown || function(oEvent)
	{
		oEvent = oEvent || window.event;
		if (oEvent.keyCode == $.ui.keyCode.ESCAPE)
			goApp.closeVideo();
	};

	/*$('#video-holder').prepend('<iframe width="1280" height="720" '
		+ 'src="http://www.youtube.com/embed/xH8OEsp3E3U?hd=1&autoplay=1&rel=0" '
		+ 'frameborder="0" allowfullscreen></iframe>');*/
};

goApp._getVideoDimensions = function(oOffset)
{
	// normilize offset
	oOffset = oOffset || {};
	for (var sSide in {top:1, right:1, left:1, bottom:1})
		if (!oOffset.hasOwnProperty(sSide))
			oOffset[sSide] = 0;

	var oScreenRes = goApp._getScreenDimensions(),
		aRes = [
			{width: 356, height: 200},
			{width: 400, height: 225},
			{width: 853, height: 480},
			{width: 1280, height: 720}
		],
		nIndex = aRes.length - 1,
		nScrollbarOffset = 24,
		nOffsetWidth = nScrollbarOffset + oOffset.left + oOffset.right,
		nOffsetHeight = nScrollbarOffset + oOffset.top + oOffset.bottom,
		oCurrentRes;

	while (oCurrentRes = aRes[nIndex--])
		if ((oScreenRes.width - nOffsetWidth >= oCurrentRes.width)
			&&  (oScreenRes.height - nOffsetHeight >= oCurrentRes.height))
			return oCurrentRes;

	return aRes[0];
};

/**
 * Returns a screen dimensions
 * @return {Object} Object with keys 'width' and 'height'
 */
goApp._getScreenDimensions = function()
{
	var oDimensions = {};
	try {
		oDimensions.width = screen.availWidth;
		oDimensions.height = screen.availHeight;
	}
	catch (oError)
	{
		oDimensions.width = 800;
		oDimensions.height = 600;
	}
	return oDimensions;
};

/**
 * Return validator object
 * @param {String} sEmailId Id of email field to be validated
 */
goApp._getEmailValidator = function(sEmailId)
{
 	var oFieldDef = {};

	oFieldDef[sEmailId] = {
		regexp: goApp.strings.invalidEmail,
		required: goApp.strings.emailRequired
	};

 	return goApp.getValidator(
		[
			{
			   name: sEmailId,
			   type: 'string',
			   constraints: [
				   {
					   method: 'regexp',
					   data: '^[^@]+@([^@.]+\\.)+[^@.]+$'
				   }
			   ]
			}
		],
		oFieldDef
	);
}

/**
 * Checks subscribe form and sends request with e-mail
 */
goApp.subscribeForUpdates	= function()
{
	try
	{
		var
			oValidator	= goApp._getEmailValidator('subscribe-email'),
			sEmail	= oValidator.check('subscribe-email',
				$.trim($('#subscribe-email').val()), true);
	}
	catch (oException)
	{
		var oError	= oValidator.error;
		if (oError)
		{
			var oMsgBox	= new MessageBox('warning', oError.description)
				.open()
				.one('dialogclose', function() {
					$('#' + oError.field).focus().select();
				});

			oMsgBox.dialog('option', 'title', goApp.strings.errorTitle);
			goApp.showInsteadHint(oError.field);
		}
		else
		{
			new MessageBox('warning', oException.message)
				.open();
		}
		
		return false;
	}
	
	goApp.openWait();
	
	// send request
	var oRequest	= new Request('/json/feedback');
	oRequest.add({
		type: 'send',
		subject: goApp.strings.subscribeSubject
			.replace('%email%', sEmail),
		message: goApp.strings.subscribeBody
			.replace('%email%', sEmail),
		email: sEmail
	});
	oRequest.send(goApp.processSubscribeResponse, goApp.processOperationFault);
	
	return false;	
};

/**
 * Processes response to subscribe request
 * @param {Object} oResponse Response object
 */
goApp.processSubscribeResponse	= function(oResponse)
{
	goApp.closeWait();
	
	if (oResponse)
	{
		var oResult	= oResponse.commands[0];
		
		goApp.checkCommandType(oResult, 'send');
			
		if (oResult.errors)
		{
			var
				sMessage	= oResult.errors[0].code == goApp.errors.ERR_EMAIL_NOT_SENT
					? goApp.strings.subscribeFault
					: goApp.getErrorMessage(oResult.errors[0]),
				
				oAlert = new MessageBox('warning', sMessage)
					.open()
					.one('dialogclose', function()
					{
						$('#company').focus();
					});
			oAlert.dialog('option', 'title', goApp.strings.errorTitle);
		}
		else
		{
			$('#subscribe-form').addClass('ui-helper-hidden');
			$('#subscribe-email').val('');
			
			var oAlert = new MessageBox('no-icon',
					goApp.strings.subscribed).open();
			oAlert.dialog('option', 'title', goApp.strings.successTitle);
		}
	}
};

goApp.requestInvite = function()
{
	try
	{
		var
			oValidator	= this._getEmailValidator('invitation-email'),
			sEmail	= oValidator.check('invitation-email',
				$.trim($('#invitation-email').val()), true);
	}
	catch (oException)
	{
		var oError	= oValidator.error;
		if (oError)
		{
			var oMsgBox	= new MessageBox('warning', oError.description)
				.open()
				.one('dialogclose', function() {
					$('#' + oError.field).focus().select();
				});

			oMsgBox.dialog('option', 'title', this.strings.errorTitle);
			this.showInsteadHint(oError.field);
		}
		else
		{
			new MessageBox('warning', oException.message)
				.open();
		}

		return false;
	}

 	goApp.openWait();

 	// send request
	var oRequest	= new Request('/json/account/cn1');
	oRequest.add({
		type: 'request_invite',
		email: sEmail,
		os: navigator.platform
	});

 	// @todo use
 	//oRequest.completeHandler = fun()

	oRequest.send(this.processRequestInviteResponse, this.processOperationFault, this);

	return false;
};


/**
 * Processes response to subscribe request
 * @param {Object} oResponse Response object
 */
goApp.processRequestInviteResponse	= function(oResponse)
{
	goApp.closeWait();

	if (oResponse)
	{
		var oResult	= oResponse.commands[0];

		this.checkCommandType(oResult, 'request_invite');

		if (oResult.errors)
		{

				var oAlert = new MessageBox('warning', this.getErrorMessage(oResult.errors[0]))
					.open()
					.one('dialogclose', function()
					{
						$('#invitation-email').focus();
					});
			oAlert.dialog('option', 'title', 'Hmmm....');
		}
		else
		{
		 	$('#user-email').replaceWith($.trim($('#invitation-email').val()));
		 	$('#box-invitation').remove();
		 	$('#box-invitation-successfull').show();
		}
	}
};


