/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	When the page is ready...
*/
$jq(document).ready( function() {

	//set the BG imgs
	$jq('DIV#page').css('background',"url('/landing/dugoutwisdom/img/page-bg.gif') repeat-y 50% 0");

	//	start with the United STATES
	states( usa );

	//	make sure the New Customer box (if there) is clicked
	if( !$jq('INPUT#fNewAcct').attr('checked') ) {
		$jq('INPUT#fNewAcct').attr('checked',true);
	}
	inspectNewAcctBox();

	//	Rock n Roll Safari
	if( $jq.browser.safari ) {
		$jq("DIV#right DIV.block INPUT.button").css('padding','0.5em');
		$jq("DIV#right DIV.block INPUT[type='button']").css('padding','0.5em');
	}
	
});

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Determine group of states or provinces to show
*/
function states( nation ) {
	menu = document.getElementById('fState');
	menu.options.length = 0;

	for(i=0; i<nation.length; i++) {
		menu.options[menu.options.length] = new Option(nation[i][0], nation[i][1]);
	}
};

//	change states set with country selection
$jq("SELECT[name='fCountry']").change( function() {
	var stArray = null;
	if( $jq(this).val()=='United States') { stArray = usa; }
	else if( $jq(this).val()=='Canada') { stArray = canada; }

	if( stArray ) { states( stArray ); }
	else { return false; }
});

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Show/hide password confirmation field based on checkbox
*/
$jq("INPUT#fNewAcct").click( function() {
	inspectNewAcctBox();
});

function inspectNewAcctBox() {
	//	i am a new user
	if( $jq("INPUT#fNewAcct").attr('checked') ) {
	
		$jq('TD#unameCell').html('Create username');
		$jq('TD#pw1Cell').html('Create password');

		$jq("FORM#customDetails TR#pw2Row").css('visibility','visible');
		$jq("INPUT[name='fPassword2']").addClass('req');
		$jq("INPUT[name='fUsername']").addClass('req');
		$jq("TR#unameRow").css('display','table-row');

	//	i am a returning user
	} else {
		$jq('TD#unameCell').html('Username');
		$jq('TD#pw1Cell').html('Password');

		$jq("INPUT[name='fPassword']").focus();

		$jq("FORM#customDetails TR#pw2Row").css('visibility','hidden');
		$jq("INPUT[name='fPassword2']").removeClass('req');
		$jq("INPUT[name='fUsername']").removeClass('req');

		$jq("TR#unameRow").css('display','none');
	}

	if( $jq('FORM#customDetails').height() > 1 ) {

		if( $jq("INPUT[name='fUsername']").val() ) {
			$jq("INPUT[name='fUsername']").select();
		} else {
			$jq("INPUT[name='fUsername']").focus();
		}
	}
}

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Show custom cover details form
*/
$jq("INPUT[name='customize']").click( function() {
	$jq(this).css('display','none');
	
	//	IE: explicit block grow
	if( $jq.browser.msie ) {
		$jq('DIV#custom').css('height','100%');
	}
	
	//	Safari, IE: explicit "main" grow
	if( $jq.browser.msie || $jq.browser.safari ) {
		$jq('DIV#main').css('height','100%');
	}

	$jq('FORM#customDetails').animate( { height:'100%' }, 'fast' );

	setTimeout("postCustomExpand();",250);
});

function postCustomExpand() {
	$jq.scrollTo('FORM#customDetails', 999 );
	$jq("INPUT[name='fLine1']").focus();

	//	IE: explicit bottom curve reposition
	if( $jq.browser.msie ) {
		$jq('DIV#custom IMG.bottom').css('bottom','-1px');
		
		/*	IE 7: even dumber */
		if( $jq.browser.version > 6.9 ) {
			setTimeout("$jq('FORM#customDetails LABEL').css('width','250px');",999);
		}
	}
}

/*	show customization details form via "make it special" images */
$jq('DIV#header IMG#special1').click( function() {
	$jq("INPUT[name='customize']").click(); });

$jq('DIV#header IMG#special2').click( function() {
	$jq("INPUT[name='customize']").click(); });

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	States by country
*/
var usa = new Array(
	['Alabama','AL'],
	['Alaska','AK'],
	['Arizona','AZ'],
	['Arkansas','AR'],
	['Armed Forces Africa','AE'],
	['Armed Forces Americas','AA'],
	['Armed Forces Canada','AE'],
	['Armed Forces Europe','AE'],
	['Armed Forces Middle East','AE'],
	['Armed Forces Pacific','AP'],
	['California','CA'],
	['Colorado','CO'],
	['Connecticut','CT'],
	['Delaware','DE'],
	['District of Columbia','DC'],
	['Florida','FL'],
	['Georgia','GA'],
	['Hawaii','HI'],
	['Idaho','ID'],
	['Illinois','IL'],
	['Indiana','IN'],
	['Iowa','IA'],
	['Kansas','KS'],
	['Kentucky','KY'],
	['Louisiana','LA'],
	['Maine','ME'],
	['Maryland','MD'],
	['Massachusetts','MA'],
	['Michigan','MI'],
	['Minnesota','MN'],
	['Mississippi','MS'],
	['Missouri','MO'],
	['Montana','MT'],
	['Nebraska','NE'],
	['Nevada','NV'],
	['New Hampshire','NH'],
	['New Jersey','NJ'],
	['New Mexico','NM'],
	['New York','NY'],
	['North Carolina','NC'],
	['North Dakota','ND'],
	['Ohio','OH'],
	['Oklahoma','OK'],
	['Oregon','OR'],
	['Pennsylvania','PA'],
	['Rhode Island','RI'],
	['South Carolina','SC'],
	['South Dakota','SD'],
	['Tennessee','TN'],
	['Texas','TX'],
	['Utah','UT'],
	['Vermont','VT'],
	['Virginia','VA'],
	['Washington','WA'],
	['West Virginia','WV'],
	['Wisconsin','WI'],
	['Wyoming','WY']
	);

var canada = new Array(
	['Alberta','AB'],
	['British Columbia','BC'],
	['Manitoba','MB'],
	['New Brunswick','NB'],
	['Newfoundland','NF'],
	['Northwest Territories','NT'],
	['Nova Scotia','NS'],
	['Nunavut','NU'],
	['Ontario','ON'],
	['Prince Edward Island','PE'],
	['Quebec','QC'],
	['Saskatchewan','SK'],
	['Yukon Territory','YT']
	);

/*	-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
	Form handling (Registration or signup process)
*/
/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Sign-in button
*/
$jq('DIV#switch #goSignin').click( function() {
	regFormName = 'signinForm';
	vars = getFormData( regFormName );
	if( vars ) { runAjax(); }
});

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	event binding for data submission
*/
var regFormName = 'customDetails';

$jq("FORM#"+regFormName+" INPUT[type='button']#go").bind('click',detailsSubmission);
$jq("FORM#"+regFormName).bind('submit',detailsSubmission);

//	-	-	-	-	-	-	-	-	capture the data
function detailsSubmission() {
	vars = getFormData( regFormName );
	if( vars ) { runAjax(); }
}

//	-	-	-	-	-	-	-	-	send the data
function runAjax() {
	//showMsg('generalError', vars); return false;
	disableForm( regFormName );
	interstitial();
	var sender = ajaxObj(regFormName, vars);
	sender.request();
}

var ajaxErrorString = 'There was an error processing your registration.\nPlease try again or email Lulu at \n\n dugoutwisdom@lulu.com';

function handleResponse( html ) {
	//alert( html ); //return false;
	results = html.split("|");
	interstitial('hide');

	if( results[1]=="success" ) {
        // report a registration to Omniture, if it is enabled
        try {
            if ( results[2]=="New user added" ) {
                // note implicit dependency on omniture_s_code.js for s_gi and s_account
                var s2 = s_gi(s_account);
                s2.linkTrackVars = 'events,eVar21';
                s2.linkTrackEvents = 'event31';
                s2.events = 'event31';
                // Dugout Wisdom registration is always for Author account
                s2.eVar21 = 'Author';
                // send to Omniture
                s2.tl(this,'o','AJAX User Registration');
                // allow a fraction of a second for the request to omniture to be received,
                //  since we are navigating away from the current page after this
                //  which would cut the request short and interfere with reporting
                setTimeout(function() { successfulResponseReceived(); }, 500);
            }
        } catch (e) {
            // make sure we do the other processing
            successfulResponseReceived();
        }
	} else if( results[1]=="error" ) {
		disableForm( regFormName, false );
		parseError( results[2] );

	} else {
		disableForm( regFormName, false );
		hideMsgs();
		if( html ) {
			/*var snitch = tattler( html );
			snitch.request();*/
			showMsg('formResult',html);
		}
		alert('Your registration may not have been processed.\n\nPlease try again.  We apologize for the inconvenience.' );
	}
}

function successfulResponseReceived() {
    hideMsgs();
    disableForm( regFormName );
    $jq('#'+regFormName).css('display','none');
    showMsg( regFormName+'Result', 'Thank you for submitting your cover information.');
    $jq('#serviceForm').submit();
}

function parseError( errorString ) {
	errors = errorString.split('&&');
	for( i=0; i<errors.length; i++ ) {
	
		data = errors[i].split('::');
		id = data[0];
		msg = data[1];

		if( msg ) {
			alert( id+' error:\n\n'+ msg );
		}

		showMsg( id+'Error', msg );
	}
}

function disableForm( formName, bool ) {
	if( bool==null ) { bool = true; }
	$jq("form[name='"+formName+"'] *").attr('disabled',bool);

	if( bool ) { $jq('DIV#loading').css('display','block'); }
	else { $jq('DIV#loading').css('display','none'); }
}

function interstitial( verb ) {
	if( verb=='hide' ) {
		$jq('DIV#interstitial').css('display','none');
	} else {
		customBlockH = $jq('#custom').height();
		$jq('DIV#interstitial').css('height', (2*customBlockH)/3 );
		$jq('DIV#interstitial').css('paddingTop', customBlockH/3 );
		$jq('DIV#interstitial').css('display','block');
	}
}

/*	- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
function tattler( html ) {

	this.request = function() {
		$jq.ajax({
			url:		"/landing/dugoutwisdom/alert.php",
			type:		'get',
			dataType:	'html',
			timeout:	60*1000,
			global:		false,
			data:		'error='+html
		});
	}
	return this;
}
