// Unify Register Script

var v = 0;

$(function(){
		   
	binder();
	
	$('#unifyFirstname, #unifyDomain').focus();
	
});

binder = function () {

	$('.video').bind('click', function () 
		{ 
			openVid($(this).attr('rel')); 
			
			// Add a "page" to GA that is '/video/videoTitle'
			pageTracker._trackPageview( '/video/' + $( this ).attr( 'rel' ) );
		}
	);
	
	$('#unifyLogin input').bind('change', function () { logValid(this); });
	$('#loginBtn').bind('click', loginForm);
	
	$('#unifyRegister input').bind('change', function () { valid(this); });
	$('#regSubmit').bind('click', submitForm);
	
	$('#unifyPassword').bind('keyup', function() { runPassword(this); });
	
	$('#unifyDomains').bind('keyup', function() { domAddUp($(this).val()); });
	
	$('#forgot').bind('click', forgot);
	
	if (!$('#promoCheck').attr('checked')) $('#promoCode').css('display', 'none');
	
	$('#promoCheck').bind('click', function () {
	
		if($(this).attr('checked')) $('#promoCode').css('display', 'inline').focus();
		else $('#promoCode').css('display', 'none');
	
	});
	
	// Bind to all outgoing links for GA tracking
	$( 'a.outgoing' ).click( function ()
		{
			// Add a "page" to GA that is '/outgoing/targetURL'
			pageTracker._trackPageview( '/outgoing/' + $( this ).attr( 'href' ) );	
		}
	);

}

submitForm = function () {
	
	$.ajax({
		   
	   type: "POST",
	   url: "functions/site/checkdomains.php",
	   data: "doms=" + $('#unifyDomains').val(),
	   dataType: "json",
	   success: function(msg){
			
			if( msg.regerror != '' || msg.regactive != '') {
				
				valid();
				
				$('#domSubError').removeClass('active');
				
				var text;
				
				if (msg.regerror != '') text = msg.regerror;
				else if (msg.regactive != '') {
					text = msg.regactive;
					$('#regSubmit').unbind('click').bind('click', actSubmit);
					$('#domSubError').addClass('active');
				}
				
				$('#domSubError').css('display', 'block').find('span.error').html( text );
				
			} 
		 	else {
				
				$('#domSubError').css('display', 'none').find('span.error').html( '' );
				
				if (valid()) {
					
					// Add a page to GA that is '/outgoing/purchase' for tracking purposes
					pageTracker._trackPageview( '/outgoing/purchase' );
					
					$('#unifyRegister')[0].submit();
				
				}
			
			}
		 
	   }
	   
	 });
	
	return false;

}

actSubmit = function () {
	
	$.ajax({
		   
	   type: "POST",
	   url: "functions/site/checkdomains.php",
	   data: "doms=" + $('#unifyDomains').val(),
	   dataType: "json",
	   success: function(msg){
			
			if( msg.regerror ) {
				
				valid();
				
				var text = msg.regerror;
				
				$('#domSubError').css('display', 'block').find('span.error').html( text );
				
			} 
		 	else {
				
				$('#domSubError').css('display', 'none').find('span.error').html( '' );
				
				if (valid()) {
					
					// Add a page to GA that is '/outgoing/purchase' for tracking purposes
					pageTracker._trackPageview( '/outgoing/purchase' );
					
					$('#unifyRegister')[0].submit();
				
				}
			
			}
		 
	   }
	   
	 });
	
	return false;

}

loginForm = function () {
	
	if (logValid()) {
	
		$.ajax({
			   
		   type: "POST",
		   url: "functions/site/unifylogin.php",
		   data: "username=" + $('#unifyUser').val() + "&password=" + $('#unifyPass').val() + "&domain=" + $('#unifyDomain').val(),
		   dataType: "json",
		   success: function(msg){
				
				if(msg != 'correct') $('#submitArea').addClass('error').find('span.error').html(msg);
				else window.location.href = 'confirmation.php';
						 
		   }
		   
		 });
	
	}
	
	return false;

}


domAddUp = function (v) {
	
	if (v != '' && valid($('#unifyDomains'))) {
	
		var doms = new RegExp(/[^,\s]+\.{1,}[^,\s]{2,},*\s*/g), domnum = null, price = null;
		
		if (v.match(doms)) domnum = v.match(doms).length;
		
		price = (domnum != 0 ) ? '$' + (domnum * 16) + '.00' : '$0.00';
		
		$('#cost').html(price);
		
	}
	else $('#cost').html('$0.00');
		
}

logValid = function (f) {
	
	if (f) {
		if(validCheck(f)) return true;		
	}
	else {
		
		v = 0,
		fields = $('#unifyLogin input').not('#loginBtn');
		
		$(fields).each( function () {
			
			logValidCheck(this);
		
		});
		
		if (v == $(fields).length) return true;
		
	}
	
}

logValidCheck = function (f) {

	var c = false;

	$(f).parents('li').removeClass('error');
			
	var tval = $(f).val();
	
	if (f.id == 'unifyDomain') {
		if (tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	else if (f.id == 'unifyPass') {
		if (tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	else if (f.id == 'unifyUser') {
		if (tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	
	if (c) {
		v++;
		return true;
	}

}

valid = function (f) {
	
	if (f) {
		if(validCheck(f)) return true;		
	}
	else {
		
		v = 0,
		fields = $('#unifyRegister input, #unifyRegister textarea, #unifyLogin input').not('#regSubmit, #shady, #logBtn, .off, #promoCode, #promoCheck');
		
		$(fields).each( function () {
			
			validCheck(this);
		
		});
		
		if (v == $(fields).length) return true;
		
	}
	
}

validCheck = function (f) {

	var emailreg = /^[a-zA-Z0-9,!#\$%&'\*\+\/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+\/=\?\^_`\{\|}~-]+)*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
	protoreg = /:\/\//,
	domreg = /^([^\.]+)$|(,\s*[^\.,]+\s*,*)$|(,\s*[^\.,]+\s*,)/,
	charreg = /^[a-zA-Z0-9\.\-,\s]+$/,
	commareg = /([^,]\s|[^\s\.,]+\.[^\s\.,]+\.[^\s\.,]{5,})/,
	domnum = new RegExp(/[^,\s]+\.{1,}[^,\s]{2,},*\s*/g),
	c = false;

	$(f).parents('li').removeClass('error');
			
	var tval = $(f).val();
	
	if (f.id == 'unifyEmail') {
		if (emailreg.test(tval) == true && tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	else if (f.id == 'unifyPassword') {
		if ($('#pwStrength').attr('class').match(/strong/) && tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	else if (f.id == 'unifyPassword-c') {
		if (tval == $('#unifyPassword').val()) c = true;
		else $(f).parent().addClass('error');
	}
	else if (f.id == 'unifyDomains') {	
		if (!tval.match(protoreg) && !tval.match(commareg) && !tval.match(domreg) && tval.match(charreg) && tval != '' && (tval.match(domnum).length <= 10)) c = true;
		else {
			
			if (tval.match(protoreg)) $('#domError').html('Please remove any protocalls. For example, no <em>http://</em>');
			else if (tval.match(commareg)) $('#domError').html('Please separate domains by a comma.');
			else if (tval.match(domreg)) $('#domError').html('All domains must have a top level domain, ex: example<em>.com</em>');
			else if (!tval.match(charreg)) $('#domError').html('Only valid domain name characters (numbers, letters, or hyphens) are allowed.');
			else $('#domError').html('Please enter at least one valid domain.');
			
			if (tval.match(domnum) && tval.match(domnum).length > 10) $('#domError').html('Please submit only 10 domains or less at a time.');
			
			$(f).parent().addClass('error');
		}		
	}
	else if (f.id == 'unifyLicense') {
		if ($('#unifyLicense:checked').length) c = true;
		else $(f).parents('li').addClass('error');
	}
	else { 
		if (tval != '') c = true;
		else $(f).parent().addClass('error');
	}
	
	if (c) {
		v++;
		return true;
	}

}

forgot = function () {
	
	$('#pass').addClass('exp').html( '<p>Please just submit your domain and username, and we will email a new password to the admin&rsquo;s email.</p><p><strong>Please Note:</strong> This will reset the <em>Unify app</em> password for this username on <em>your install</em> of Unify as well.</p>' );
	
	$('#loginBtn').val('submit').unbind('click').bind('click', forgotSubmit);
	
	setTimeout( function () { $('#forgot').attr('id', 'return').html('Back to Login').unbind('click').bind('click', returnLogin); }, 0 );
	
}

forgotSubmit = function () {

	if (logValid()) {
		$.ajax({
			   
		   type: "POST",
		   url: "functions/site/forgotpass.php",
		   data: "username=" + $('#unifyUser').val() + '&domain=' + $('#unifyDomain').val(),
		   dataType: "json",
		   success: function(msg){
				
				if( msg.match('successfully') ) $('#submitArea').addClass('error').find('span.error').css({ color: '#82ac40', display: 'block' }).html(msg);
			 	else $('#submitArea').addClass('error').find('span.error').css({ color: '#f00', display: 'block' }).html(msg);
			 
		   }
		   
		 });
	}
	
	return false;

}

returnLogin = function () {
	
	$('#pass').removeClass('exp').html( '<label>Unify Password</label><input id="unifyPass" name="password" type="password" /><span class="error">Your password is required.</span>' );
	
	$('#loginBtn').val('login').unbind('click').bind('click', loginForm);
	
	$('#submitArea').removeClass('error').find('span.error').removeAttr('style').html('Incorrect username or password.');
	
	setTimeout( function () { $('#return').attr('id', 'forgot').html('Forgot Password?').unbind('click').bind('click', forgot); }, 0 );
	
}

// controls reformatting of tweets
formatTweet = function ( txt ) {
	// formatting 'http://www.site.com' to '<a href="http://www.site.com">http://www.site.com</a>'
	var urls = txt.match( /http[^\s]+/gi );
	
	if ( urls ) for( var i = 0; i < urls.length; i++ ) txt = txt.replace( urls[i], '<a href="' + urls[i] + '">' + urls[i] + '</a>');

	// formatting '@username' to '<a href="http://twitter.com/username">@username</a>'
	var users = txt.match( /^@[^\s]+|\s@[^\s]+\b/gi );
	
	if ( users ) {
		for( var i = 0; i < users.length; i++ ) {
			users[i] = users[i].replace( ' ', '' );
			users[i] = users[i].replace( ':', '' );
			var user = users[i].replace( /@/, '' );
			
			txt = txt.replace( users[i], '<a href="http://twitter.com/' + user + '">' + users[i] + '</a>');
		}
	}
	
	return txt;
};

twitterFeed = function ( data ) {
	var tweets = '', counter = 0;
	
	$( data ).each(function ( i ) {
							  
			var txt = this.text;
			
			if ( txt.match( /#unify/gi ) ) {
				counter++;
				tweets += '<li>'  + formatTweet( txt ) + '</li>';

				if ( counter == 5 || i == data.length - 1 ) {
					
					$( '#twitter_update_list' ).html( tweets );
					return false;
					
				}
			}
	});
	
};

// capcode shamelessly adapted from Paul Irish's Konami Code script: http://paulirish.com/2009/cornify-easter-egg-with-jquery/

capcode = function () {
	var ckeys = [], capcom = "72,65,68,79,85,75,69,78";
	
	$(document).keydown(function(e) { 
				
	  ckeys.push( e.keyCode ); 
	  
	  if ( ckeys.toString().indexOf( capcom ) >= 0 ){ 
	    $(document).unbind('keydown',arguments.callee); 
	   	
	   	openVid('hadouken');
	   	           
	  }
	  
	});
}

openVid = function (vid) {
	
	var title, embed,
	scroll = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
	
	if (vid == 'hadouken') { title = 'Hyper-Super Turbo Edition'; embed = '<object width="700" height="393"><param name="movie" value="http://www.youtube.com/v/lByvs8C2rRE&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/lByvs8C2rRE&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="393"></embed></object>'; }
	else if (vid == 'promo') { title = 'An Introduction'; embed = '<object width="700" height="393"><param name="movie" value="http://www.youtube.com/v/_KzdIp2BSEs&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/_KzdIp2BSEs&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="393"></embed></object>'; }
	else if (vid == 'using') { title = 'Using Unify'; embed = '<object width="700" height="393"><param name="movie" value="http://www.youtube.com/v/VfFlQZJPaGc&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/VfFlQZJPaGc&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="393"></embed></object>'; }
	else if (vid == 'install') { title = 'Installation'; embed = '<object width="700" height="393"><param name="movie" value="http://www.youtube.com/v/xRln89F33g8&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/xRln89F33g8&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="393"></embed></object>'; }
	else if (vid == 'dash') { title = 'Dashboard'; embed = '<object width="700" height="393"><param name="movie" value="http://www.youtube.com/v/qYsI9IukBQY&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/qYsI9IukBQY&hl=en&fs=1&showinfo=0&rel=0&autoplay=1&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="393"></embed></object>'; }
	   	
   	if(!$.browser.msie) {
   		
   		$('body').append('<div id="vidwrap"><div id="vid"><h1><a id="close">close</a>Unify<em> &nbsp;&middot;&nbsp; '+title+'</em></h1>'+embed+'</div></div><div id="overlay"></div>');
   		
   		$('#overlay').css({ opacity: 0, display: 'block' }).height( $('body').height() ).fadeTo('300', 1.0, function () { 
   			
			if (scroll > 100) {
				var s = parseInt($('#vid').css('top')) + scroll;
				$('#vid').css( 'top', s );
			}
   			
   			$('#vidwrap').css({ display: 'block' });
   			$('#close, #vidwrap').bind('click', closer);
   			
   		});
   	}
   	else {
   		
   		var pop = $('<div/>').html('<div id="vidwrap"><div id="vid"><h1><a id="close">close</a>Unify<em> &nbsp;&middot;&nbsp; '+title+'</em></h1>'+embed+'</div></div><div id="overlay"></div>');
   		
   		$('body')[0].innerHTML = $('body').html() + pop.html();
   		
		if (scroll > 100) {
			var s = parseInt($('#vid').css('top')) + scroll;
			$('#vid').css( 'top', s );
		}
   		
   		$('#vidwrap').css({ display: 'block' });
   		$('#close, #vidwrap').bind('click', closer); 
   		
   		setTimeout( function () { $('#overlay').css({ display: 'block' }).height( $('body').height() );}, 0);
   	}

}

closer = function () {
	
	$('#overlay, #vidwrap').remove();
	
	if ($('body.main').length) capcode();
	
}