// global vars
var CURRENT_DIV = LOGGED_IN ? 'band_info' : 'login_info';
var MISSING = new Array();
var MESSAGE = new Array();

signupStateHandler = function(page, action) {
    //alert('page = ' + page + ', action = ' + action);
    switch (page) {
        case 'login':
        loginSetup(action);
        CURRENT_DIV = 'account_info';
        setCurrentStep('account_step');
        break;

        case 'account':
        accountSetup(action);
        break;

        case 'personal':
        personalSetup(action);
        break;

        case 'band':
		bandSetup(action);
        break;

        case 'confirmation':
        confirmationSetup(action);
        break;
    }
}

loginSetup = function(action) {
    initSteps(action);
    document.signup.signup_type.value = action;
    dojo.lfx.fofi('account_info', 'login_info');
}

accountSetup = function(action) {
    if (action == 'previous') {
        dojo.lfx.fadeWipeOut('step_tracker', 500, dojo.lfx.easeInOut).play()
        dojo.lfx.fofi('login_info', 'account_info');
    }
    else if (action == 'next') {
        validated = accountValidation(function(){ dojo.lfx.fofi('personal_info', 'account_info'); });
        if (validated) {
            CURRENT_DIV = 'personal_info';
            setCurrentStep('personal_step');
        }
    }
}

personalSetup = function(action) {
    if (action == 'previous') {
        CURRENT_DIV = 'account_info';
        setCurrentStep('account_step');
        dojo.lfx.fofi('account_info', 'personal_info');
    }
    else if (action == 'next') {
        if (document.signup.signup_type.value == 'fan') {
            // do fan submit
            document.signup.action.value = 'confirmation';
            // setup XHR params
            params = {
                url: MP3_BASE_URL + '/index.php',
                method: 'POST',
                form: 'signup',
                onSuccess: function(t, d) { confirmationResponse(d, 'personal_info'); }
            }
			// on validate show confirmation page, otherwise throw errors
			validateSuccess = function() { dojo.io.basicXHRTransport(params); };
			validated = personalValidation(validateSuccess);
			if (validated) {
			    CURRENT_DIV = 'confirmation';
                setCurrentStep('confirm_step');
			}
        }
        else {
			// on validate go to band, otherwise throw errors
			validateSuccess = function() { dojo.lfx.fofi('band_info', 'personal_info'); };
			validated = personalValidation(validateSuccess);
			if (validated) {
			    CURRENT_DIV = 'band_info';
                setCurrentStep('band_step');
			}
        }
    }
}

confirmationSetup = function(action) {
	if (action == 'previous') {
	    if (document.signup.signup_type.value == 'fan') {
	        CURRENT_DIV = 'personal_info';
	        setCurrentStep('personal_step');
		    dojo.lfx.fofi('personal_info', 'confirmation');
	    }
	    else if (document.signup.signup_type.value == 'band') {
	        CURRENT_DIV = 'band_info';
	        setCurrentStep('band_step');
		    dojo.lfx.fofi('band_info', 'confirmation');
	    }
	}
	else if (action == 'next') {
	    // hide the button so they can only click it once
	    dojo.byId('verify_button').style.display = 'none';
	    dojo.byId('verify_wait').style.display = 'inline';

		// do fan submit
		document.signup.action.value = 'verify';

		// setup our success
		verifySuccess = function(t, d) {
		    if (/!@error@!/.test(d)) {
		        d = d.replace(/!@error@!/, '');
		        if (LOGGED_IN) {
		            dojo.lfx.fofi('band_info', 'confirmation');
		        }
		        else {
		            dojo.lfx.fofi('account_info', 'confirmation');
		        }
		        dojo.style.setOpacity(dojo.byId('ui-dialog'), 0);
		        dojo.widget.byId('ui-dialog').displayHandler(d);
		        CURRENT_DIV = 'account_info';
		        setCurrentStep('account_step');
		    }
		    else {
		      CURRENT_DIV = 'verify_info';
                setCurrentStep('verify_step');
                dojo.byId('verify').innerHTML = d;
                dojo.lfx.fofi('verify', 'confirmation');
		    }
		}

		// setup XHR params
		params = {
			url: MP3_BASE_URL + '/index.php',
			method: 'POST',
			form: 'signup',
			onSuccess: verifySuccess
		}
		dojo.io.basicXHRTransport(params);
	}
}

confirmBandSignup = function() {
	text = '<div><div id="list" style="width:500px;margin:5px;"><b>Before continuing, we ask that you take a minute to read and observe the basic rules of the road:</b><ul class="bullets"><li>Only artists or their authorized representative may post content on an Artist Page.  We reserve the right to authenticate your identity before posting your content.</li><li>You must have full rights to any content you post and all music must be your own original content -- no cover songs and no samples!  Posting non-original music may result in termination of your access.</li><li>You may remove your content at any time.</li><li>We may remove your content at any time if we feel it violates the terms of use we have developed for our site or if we believe your content may result in legal liability or harm to our business reputation.</li><li>By posting or uploading content onto our site you are granting us a worldwide, non-exclusive, royalty-free license to host your material on our servers and make those materials available to users across CNET\'s family of Internet sites in a variety of ways including through streams, downloads, on mobile devices and through the aggregation and presentation of your content with content uploaded by other artists.</li><li>By uploading your music onto our site you agree to waive any copyright royalty or other fee to which you may be entitled, including but not limited to any music publishing, mechanical reproduction, performance, union or guild payments.  You also agree to take sole responsibility for any royalties, fees or other monies owned to any person by reason of any content you post on our site.</li><li>Our sites are advertising-supported.  As such, your content may appear or be promoted in sections or on pages that are sponsored by one or more advertisers.</li></ul><b>By clicking \'ok\' you are stating that you agree to the guidelines above.  For more details, please consult our <a target="_blank" href="' + MP3_BASE_URL + '/feature/uploads-faq/">User Uploads FAQ</a>.</b></div><div style="font-size:14px;text-align:right;margin:5px;"><a href="javascript:void(0);" onclick="validateBandSuccess();dojo.widget.byId(\'ui-dialog\').hide();">ok</a>&nbsp;|&nbsp;<a href="javascript:void(0);" onclick="dojo.widget.byId(\'ui-dialog\').hide();">cancel</a></div></div>';
	dojo.style.setOpacity(dojo.byId('ui-dialog'), 0);
	dojo.widget.byId('ui-dialog').displayHandler(text);
}

bandSetup = function(action) {
    if (action == 'previous') {
        dojo.lfx.fofi('personal_info', 'band_info');
        CURRENT_DIV = 'personal_info';
        setCurrentStep('personal_step');
    }
    else if (action == 'next') {
        document.signup.action.value = 'confirmation';

        // validate only on needed fields
        validated = bandValidation();

        if (validated) {
			confirmBandSignup();
        }
    }
}

validateBandSuccess = function() {
    // setup XHR params for successful validation
    params = {
        url: MP3_BASE_URL + '/index.php',
        method: 'POST',
        form: 'signup',
        onSuccess: function(t, d) { confirmationResponse(d, 'band_info'); }
    }
	dojo.io.basicXHRTransport(params);
	CURRENT_DIV = 'confirmation';
    setCurrentStep('confirm_step');
}

accountValidation = function(onSuccess) {
    missing = new Array();
    message = new Array();
    validated = false;

    // need to do some more checks
    if (!/^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/.test(document.signup.email.value))
    {
        i = missing.length;
        missing[i] = 'email';
        message[i] = 'Email is invalid.  Without a valid email address, you\'ll be unable to complete the signup process';
    }

    if (!/^[a-zA-Z0-9\-\_]{2,15}$/.test(document.signup.username.value)) {
        i = missing.length;
        missing[i] = 'username';
        message[i] = 'Username is invalid. Only numbers, letters, dashes and underscores are allowed.';
    }

	if (!/^[a-zA-Z0-9]{6,15}$/.test(document.signup.password.value)) {
        i = missing.length;
        missing[i] = 'password';
        message[i] = 'Password invalid.  Password must be between 6 and 15 characters and consist of letters and numbers only.';
    }

    if (document.signup.password.value != document.signup.password_conf.value) {
        i = missing.length;
        missing[i] = 'password_conf';
        message[i] = 'Password Confirmation does not match Password.';
    }

    if (!document.signup.agree.checked) {
        i = missing.length;
        missing[i] = 'agree';
        message[i] = 'Please check the I agree button to indicate that you have read and understand our privacy policy';
    }

    if (missing.length > 0) {
        validationFailure('required', missing, message);
        validated = false;
    }
    else {
        onSuccess();
        validated = true;
    }
    return validated;
}

personalValidation = function(onSuccess) {
	validated = false;
    dojo.validate.formHandler('signup', {required: ['first', 'last'], response: ['First Name is a required field.', 'Last Name is a required field.']},
    	function() {
    	    // check other inputs and add them to the message list
    	    missing = new Array();
    	    message = new Array();
    	    if (document.signup.country.value == '') {
    		    i = missing.length;
    		    missing[i] = 'country';
    			message[i] = 'Country is a required field';
    		}
    		else if ((document.signup.country.value == 'US') && !/^\d{5}$/.test(document.signup.zip_code.value)) {
    	        i = missing.length;
    		    missing[i] = 'zip_code';
    			message[i] = 'Please enter a valid US zip code.';
    	    }

    		if (document.signup.gender.value == '') {
    			i = missing.length;
    			missing[i] = 'gender';
    			message[i] = 'Gender is a required field';
    		}
    		if (!/^\d{4}$/.test(document.signup.birth_Year.value)) {
    			i = missing.length;
    			missing[i] = 'birth_Year';
    			message[i] = 'Date of Birth is a required field';
    		}

    		// do we have any missing?
    		if (missing.length > 0) {
    			validationFailure('required', missing, message);
    			validated = false;
    		}
    		else {
    			onSuccess();
    			validated = true;
    		}
    	},
    	function(type, missing, message) {
    		// check other inputs and add them to the message list
    		if (document.signup.country.value == '') {
    			i = missing.length;
    			missing[i] = 'country';
    			message[i] = 'Country is a required field.';
    		}
    		else if ((document.signup.country.value == 'US') && !/^\d{5}$/.test(document.signup.zip_code.value)) {
    	        i = missing.length;
    		    missing[i] = 'zip_code';
    			message[i] = 'Please enter a valid US zip code.';
    	    }

    		if (document.signup.gender.value == '') {
    			i = missing.length;
    			missing[i] = 'gender';
    			message[i] = 'Gender is a required field.';
    		}
    		if (!/^\d{4}$/.test(document.signup.birth_Year.value)) {
    			i = missing.length;
    			missing[i] = 'birth_Year';
    			message[i] = 'Date of Birth is a required field.';
    		}

    		validationFailure(type, missing, message);
    		validated = false;
    	}
	);
	return validated;
}

bandValidation = function() {
    missing = new Array();
    message = new Array();
    validated = false;

    country = LOGGED_IN ? document.signup.artist_country.value : document.signup.country.value;

    if (document.signup.artist_name.value == '') {
        i = missing.length;
        missing[i] = 'artist_name';
        message[i] = 'Your band have a name?  Make one up if you have to and use the "check availability" link below to make sure it\'s available!';
    }

	if (!/^\d{4}$/.test(document.signup.original_release_Year.value)) {
        i = missing.length;
        missing[i] = 'original_release_Year';
        message[i] = 'Date Formed is required.  If you don\'t know the exact month, just supply us with the year';
    }

    if (document.signup.genre_id.value == '') {
        i = missing.length;
        missing[i] = 'genre_id';
        message[i] = 'Genre is required.  Just try to pick one that best fits your band\'s style.';
    }

    if (country == '') {
		i = missing.length;
		missing[i] = 'artist_country';
		message[i] = 'Country is a required field.';
    }

    if ((country == 'US') && (document.signup.state.value == '')) {
		i = missing.length;
		missing[i] = 'state';
		message[i] = 'State is a required field.';
    }

    if (document.signup.artist_zip_code.value == '') {
        i = missing.length;
	    missing[i] = 'artist_zip_code';
		message[i] = 'Please enter a valid zip code.  This allows fans in your local area to easily find your music!';
    }

    if (document.signup.bio.value == '') {
        i = missing.length;
		missing[i] = 'bio';
		message[i] = 'Bio is a required field.  Please tell us a little something about your band (this will be displayed in your artist space).';
    }

    if (dojo.byId('signup_contest_agree')) {
        if (!document.signup.signup_contest_agree.checked) {
            i = missing.length;
            missing[i] = 'signup_contest_agree';
            message[i] = 'Please confirm you have read and agree to contest rules to continue.';
        }
    }

    if (missing.length > 0) {
        validationFailure('required', missing, message);
        validated = false;
    }
    else {
        validated = true;
    }

    return validated;
}

validationFailure = function(type, missing, message) {
    // setup response text
    text  = '<div style="width: 300px;">'
    text += '  <div class="mb-15" style="font-weight: bold;">Please fix the following problems before continuing:</div>';
    for (i = 0; i < missing.length; i++) {
        text += '<div class="mb-10" style="color:red;">&nbsp;&nbsp;--&nbsp;' + message[i] + '</div>';
    }
    text += '  <div style="text-align: right;">';
    text += '    <a href="javascript:void(0);" onclick="dojo.widget.byId(\'ui-dialog\').hide(); validationFailureDialogResponse();">close</a>'
    text += '  </div>';
    text += '</div>';

    MISSING = missing;
    MESSAGE = message;

    // throw dialog
    dojo.style.setOpacity(dojo.byId('ui-dialog'), 0);
    dojo.widget.byId('ui-dialog').displayHandler(text);
}

validationFailureDialogResponse = function() {
    for (i = 0; i < MISSING.length; i++) {
        node = dojo.byId('signup_' + MISSING[i]);
        if (node)
            dojo.lfx.html.highlight(node, [240, 240, 110], 1000).play(1500);
    }
    // reset globals
    MISSING = null;
    MESSAGE = null;
}

confirmationResponse = function(data, foName) {
	if (/!@error@!/.test(data)) {
		data = data.replace(/!@error@!/, '');
		dojo.lfx.fofi('account_info', foName);
		dojo.style.setOpacity(dojo.byId('ui-dialog'), 0);
		dojo.widget.byId('ui-dialog').displayHandler(data);
	}
	else {
	    dojo.byId('confirmation').innerHTML = data;
	    dojo.lfx.fofi('confirmation', foName);
	}
}

// throwing up colors
passwordConfirm = function(pwd, pwdConf) {
    match = pwd.value.indexOf(pwdConf.value);
    if (match == -1) {
        pwd.style.background = "#fa7d6e";
        pwdConf.style.background = "#fa7d6e";
    }
    else if ((pwd.value.length > 5) && (pwd.value.length == pwdConf.value.length)) {
        pwd.style.background = "#7dfa6e";
        pwdConf.style.background = "#7dfa6e";
    }
    else if (match == 0) {
        pwd.style.background = "#ffffff";
        pwdConf.style.background = "#ffffff";
    }
}

resetPasswordConfirm = function(pwd, pwdConf) {
    pwd.style.background = "#ffffff";
    pwdConf.style.background = "#ffffff";
    pwdConf.value = '';
}

initSteps = function(action) {
    if (!LOGGED_IN) {
        dojo.byId('account_step').style.display = 'inline';
        dojo.byId('personal_step').style.display = 'inline';
        // make sure band step is turned off
        dojo.byId('band_step').style.display = 'none';
    }

    if (action == 'band') {
        dojo.byId('band_step').style.display = 'inline';
    }

    dojo.byId('confirm_step').style.display = 'inline';
    dojo.byId('verify_step').style.display = 'inline';

    // show the tracker
    dojo.style.setOpacity(dojo.byId('step_tracker'), 0);
    dojo.lfx.fadeWipeIn('step_tracker', 500, dojo.lfx.easeInOut).play();
}

setCurrentStep = function(step) {
    // set all steps to regular
    dojo.byId('account_step').className = 'step';
    dojo.byId('personal_step').className = 'step';
    dojo.byId('band_step').className = 'step';
    dojo.byId('confirm_step').className = 'step';
    dojo.byId('verify_step').className = 'step';

    // now set the step we're currently on
    dojo.byId(step).className = "step on";
}

setupStepLink = function(step_link, step_div) {
    dojo.byId(step_link).onclick="dojo.lfx.fofi('" + CURRENT_DIV + "', '" + step_div + "');";
}

blockStep = function() {
    text = "Please complete all preceding steps first.";
    dojo.widget.byId('ui-dialog').displayHandler(dojo.lfx.basicDialogBox(text));
}
