/*
 * Connect affiliate network wizard
 */

(function ($) {

$(function () {
	var PreventExitPop = false;
	var PreventOptinForm = false;
	
	// bind tour video to be opend in lightview
	$('.video-tour-btn').click(function () {
		Lightview.show({
			href: '/tour',
			rel: 'iframe',
			options: {
				width: 560,
				height: 365,
				topclose: true
			}
		});
		
		return false;
	});
	
	// clear fields on focus
	$('form#optin-form input[type="text"]').bind('focus', function () {
		if (this.value == this.defaultValue) {
			this.value = '';
		}
	});
	// reset field to default value on blur if empty
	$('form#optin-form input[type="text"]').bind('blur', function () {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});
	
	// bind `connect` button handler
	$('#checkout-dialog-btn').click(function () {
		PreventExitPop = true;
		
		var isValid = true;
		var $form = $('form#optin-form');
		var userName = $form.find('#realname')[0];
		var userEmail = $form.find('#email')[0];
		// validate form
		if (userName.value == '' || userName.value == userName.defaultValue) {
			isValid = false;
		}
		if (userEmail.value == '' || userEmail.value == userEmail.defaultValue) {
			isValid = false;
		}
		var params = '';
		if (isValid) {
			if ( ! PreventOptinForm) {
				PreventOptinForm = true;
				setTimeout(function () {
					// create hidden iframe
					var ioId = 'optinFormIO' + (new Date().getTime());
			        var $io = $('<iframe id="' + ioId + '" name="' + ioId + '" src="about:blank" />');
			        var io = $io[0];
		        	$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
		        	$io.appendTo(document.body);
		        	$form.attr('target', ioId);
		        	$form[0].submit();
				}, 10); // seperate thread
			}
			params = $.param({name: userName.value, from: userEmail.value}).replace(/\+/g, '%20');
		}
		aj.checkoutDialog(params);
	});
	
	// bind do-not-leave offer popup
	if ($('#ExitDive').length) {
		// bind special offer
		$('a').live('click', function() {
			PreventExitPop = true;
		});
		$(window).bind('keydown', function (e) {
			if (e.which == 116) { // F5
				PreventExitPop = true;
			}
		});
		window.onbeforeunload = function () {
			if( ! PreventExitPop) {
				PreventExitPop = true;
				var donotleave = $('#ExitDive').clone(true).css('display', '');
				$(document.body).empty().append(donotleave);
				scroll(0, 0);
				return "*****************************************************\n\nWAIT --  Before You Go, Please Click The\nCANCEL Button To Download Our FREE\nA Report CPA Profits Revealed Now!\n\n Just Click CANCEL Now To Learn More!\n\n*****************************************************";
			}
		};
	}
});
	
})(jQuery);