

var SPLASH = {

    username : "",
    email : true,
    
    init : function () {
       $(document).ready(function (){
        displaySignUpForm();
        $('.formoverlay').dialog();
 //       $('#thankyou').dialog();
        });
 //      	SPLASH.initBetaThanks();
    
        $( "#signinbutton" ).hover(
            function () { $(this).attr( 'src', '/corp/images/splash-signin-on.png' ); },
            function () { $(this).attr( 'src', '/corp/images/splash-signin-off.png' ); }
        ).click( function () {
            var username =  $( "#signinname" ).val(); 
            var password = $( "#signinpass" ).val();
            // Regular expression used to validate emails
            var emailRe = new RegExp( "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$", "g" );
            
            var result = username.match( emailRe );
            result = ( result != null );

            if ( !result ) {
            	alert("Invalid Email Address");
            	return;
            }
            var request = { email:username, pass:password };
		$.ajax( {
			type: "POST",
			url: "/account/signin",
			data: request,
			dataType: "text",
			success: function( result ) {

			/* To decode returned JSON data for parseInt() function */
			var resultAsVar = "var resultMap = " + result;
			eval( resultAsVar );
			var message = resultMap.statuscode;
			/* extract statuscode from returned JSON string,valid user == 1
			 and direct him to his application profile page */
			if ( parseInt( message ) == 1) {
				
				window.location.href = "/application/index";
				
				/*$("a.signoutlink").click(function() {
				    $.get("/account/signout", function() {
				        alert('Successfully logged out');
				    });
				    return false; // so the page does not refresh
				});*/
            } 
			else if ( parseInt( message ) == 0 ){
				alert( resultMap.LoginError );	/* Invalid Login Credentials */
            }
			},
			error: function() {
				alert( "Please try again." );
			}
    	} );
        } );
        
        $( "#signoutbutton" ).hover(
                function () { $(this).attr( 'src', '/corp/images/splash-signout-on.png' ); },
                function () { $(this).attr( 'src', '/corp/images/splash-signout-off.png' ); }
            ).click( function () {
                var request = {};
    		$.ajax( {
    			type: "POST",
    			url: "/account/signout",
    			data: request,
    			dataType: "text",
    			success: function( result ) {

    			/* To decode returned JSON data for parseInt() function */
    			var resultAsVar = "var resultMap = " + result;
    			eval( resultAsVar );
    			var message = resultMap.statuscode;
    			/* extract statuscode from returned JSON string,valid user == 1
    			 and direct him to his application profile page */
    			if ( parseInt( message ) == 1) {
    				window.location.href = "/application/index";
    				
    				/*$("a.signoutlink").click(function() {
    				    $.get("/account/signout", function() {
    				        alert('Successfully logged out');
    				    });
    				    return false; // so the page does not refresh
    				});*/
                } 
    			else if ( parseInt( message ) == 0 ){
    				alert( resultMap.LoginError );	/* Invalid Login Credentials */
                }
    			},
    			error: function() {
    				alert( "Please try again." );
    			}
        	} );
            } );
        
        $( "#signinpass" ).val( '' ).change(
            function () {
                if ( $(this).val().length == 0 ) {
                    $(this).css( 'display', 'none' );
                    $( "#signinpasstype" ).css( 'display', 'inline' ).val( 'Password' );
                }
            }
        ).keyup( function () {
                if ( $(this).val().length == 0 ) {
                    $(this).css( 'display', 'none' );
                    $( "#signinpasstype" ).css( 'display', 'inline' ).val( 'Password' );
                }
            }
            
        );
        
        $( "#signinpasstype" ).val( 'Password' ).focus( function () {
            $(this).css( 'display', 'none' );
            $( "#signinpass" ).css( 'display', 'inline' );
            setTimeout( function () { $( "#signinpass" ).val( '' ).focus(); }, 100 );
        } ).blur( function () {
            //alert( "leaving" );
            if ( $(this).val().length == 0 ) {
                $(this).css( 'display', 'none' );
                $( "#signinpass" ).css( 'display', 'inline' ).css( 'color', '#888888' ).val( 'Password' );
                
            }
        } );
        
        $( "#signinname" ).val( 'Email' ).change(
            function () {
                if ( $(this).val().length == 0 ) {
                    SPLASH.email = true;
                    $(this).css( 'color', '#888888' ).val( 'Email' ).blur();
                } else {
                    SPLASH.username = $(this).val();
                }
            }
        ).keyup( function () {
                if ( $(this).val().length == 0 ) {
                    //SPLASH.email = true;
                    //$(this).css( 'color', '#888888' ).val( 'Email' ).blur();
                } else {
                    SPLASH.username = $(this).val();
                }
            }            
        ).focus( function () {
            $(this).css( 'color', '#000000' );
            if ( SPLASH.email ) {
                SPLASH.email = false;
                $(this).val( '' );
            }
        } ).blur( function () {
            SPLASH.username = $(this).val();
            $(this).val( SPLASH.username );            
            if ( SPLASH.username.length == 0 ) {
                SPLASH.email = true;
                $(this).val( 'Email' ).css( 'color', '#888888' );
            }
        } );
        
        $( "#signupnow" ).hover(
            function () { $(this).attr( 'src', '/corp/images/splash-signupnow-on.png' ); },
            function () { $(this).attr( 'src', '/corp/images/splash-signupnow-off.png' ); }            
        ).click( function () {
 //       	$('#betaregstuff').dialog('open'); 
        	//$( "#thankyoudialog").dialog( 'open' );
//	        	var first = $("#firstName");
				var email = $("#email");
				var referral = $("#referrer");
//				var last = $("#lastName");
				allFields = $([]).add(email);	//.add(first).add(last);
				var bValid = true;
				var emailValid = true;
//				var firstNameValid = true;
//				var lastNameValid = true;
				allFields.removeClass('ui-state-error');
				//tips[ 'email' ].text( "Email" );
				//tips[ 'first' ].text( "First Name" );
				//tips[ 'last' ].text( "Last Name" );
				// Check validaty of Email
				emailValid = checkLength( $("#email"),"email",1,255, "Email", "an email address." );
    			//emailValid = emailValid && checkRegexp( $( "#email" ),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"email","Email*", "This is not a properly formatted email address");
				//emailValid = emailValid && checkRegexp( $( "#email" ),/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,"email","Email*", "This is not a properly formatted email address");
				emailValid = emailValid && validEmail();

//				firstNameValid = checkLength( $( "#firstName" ), "first", 1, 32, "First Name", "a first name." );
//				firstNameValid = firstNameValid && checkRegexp($( "#firstName" ),/^[a-z]([0-9a-z_])*$/i, "first", "First Name", "name, Must begin with a letter.");

//				lastNameValid = checkLength( $( "#lastName" ), "last", 1, 32, "Last Name", "a last name." );
//				lastNameValid = lastNameValid && checkRegexp( $( "#lastName" ),/^[a-z]([0-9a-z_])*$/i, "last", "Last Name", "name, Must begin with a letter.");
//				alert(emailValid);
				if ( emailValid  ) //&& firstNameValid && lastNameValid
				{	
					
					var args = { 
		            		'email' : email.val(), 
		            		'referral' : referral.val()
		            		}; 
//					alert("here we go");
					 $.ajax( {
				        	type: "POST",
				        	url: "/account/prereg",
				        	data: args,
				        	dataType: "text",
				        	success: function( response )
				            {
//				        	alert(response);
					        	try {
									var resultAsVar = "var resultMap = " + response;
									eval( resultAsVar );
													
								} catch( excep ) {
									alert( "unable to process signup");					
								};
//								alert(resultMap);
								if ( resultMap[ 'ok' ] == 1 )
								{
									if (resultMap['type'] == 'beta')
									{
										SPLASH.initBetaThanks();
										$("#thankyoudialog").dialog('open');
										
										
										
									}
									else
									{
										alert("email sent");
										window.location.href = "/application/index";
										
									}
								}
				            }
					 });
				}
        } );
        $( "#promorollover" ).hover(
            function () { $(this).attr( 'src', '/corp/images/banner-vator-on.png' ); },
            function () { $(this).attr( 'src', '/corp/images/banner-vator-off.png' ); }                        
        );
        $( "#followtwitter" ).hover(
            function () { $(this).attr( 'src', '/corp/images/footer-twitter-on.png' ); },
            function () { $(this).attr( 'src', '/corp/images/footer-twitter-off.png' ); }                        
        ).click( function () {
        	window.open("http://www.twitter.com/nthsocial","_blank");
          } );
        $( "#followfacebook" ).hover(
            function () { $(this).attr( 'src', '/corp/images/footer-facebook-on.png' ); },
            function () { $(this).attr( 'src', '/corp/images/footer-facebook-off.png' ); }                        
        ).click( function () {
        	 window.open("http://www.facebook.com/Nthsocial","_blank");
        } );
    }, // end of init
    
    initBetaThanks : function ()
    {
    	
    	$( "#thankyoudialog").dialog({
    		bgiframe: true,
    		autoOpen: false,
    		height: 200,
    		width: 300,
    		modal: true,
    		open: function() {
    				//setNameAndEmail( subname, subemail );
    				
    				$("#email_thanks").text($("#email").val());
    				$( "#thankyoudialog" ).css( "visibility", "visible" );
    				
    			},
    		buttons: {
    			'Close': function() {
    				$(this).dialog( 'close' );
                    //window.location.href = "/corporate/home";
    			}
    		}
    	});
    	
    },
    
	signUpClick : function ( event ) {
		$('.formoverlay').dialog('open');
    }
};


function displaySignUpForm() 
{
	var tips = $("#validateTips");
	function updateTips(t) {
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp(o,regexp,n) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}

	function checkifpasswordsmatch(pass, rPassword, message){
		if(pass == rPassword){
			return true;
		}
		else{
			rPassword.addClass('ui-state-error');
			updateTips(message);
			return false;
		}
	}
	
	var email = $("#email");
	var password = $("#password");
	var	repeatPassword = $("#repeatPassword");
	var allFields = $([]).add(email).add(password).add(repeatPassword);
	
	//var tips = { email:$("#mail"), password:$("#pass"), repeatPassword:$("#rpass") };
	
	$( "#thankyou").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 200,
		width: 300,
		modal: true,
		open: function() {
				//setNameAndEmail( subname, subemail );
				$( "#thankyou" ).css( "visibility", "visible" );
				
			},
		buttons: {
			'Close': function() {
				$(this).dialog( 'close' );
                //window.location.href = "/corporate/home";
			}
		}
	});
	
	$(".formoverlay").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 400,
		width:340,
		modal: true,
		title:'NthSocial new user registration',
		buttons: {
			'Create an account': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(email,"email",6,30);
				bValid = bValid && checkLength(password,"password",5,16);
				
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Invalid Email Format ex: abc@xyz.com");				
				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allows : a-zA-Z0-9");
				bValid = bValid && checkRegexp(repeatPassword,/^([0-9a-zA-Z])+$/,"Password field only allows : a-zA-Z0-9");
				
				//bValid = bValid && checkifpasswordsmatch(password, repeatPassword, "Passwords don't match");
				
				if (bValid) {
					$(".formoverlay").dialog('close');
					$("#thankyou").dialog('open');
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
}

