/**********************************************
 **
 ** Various utility functions
 **
 **********************************************/

var Utility = new Object();

Utility.ReplaceData = function (xml, context) {
    if( xml == null )
	return;

    var xmlRoot = xml.documentElement;
    var data    = xmlRoot.getElementsByTagName( 'data' );
    
    for( var idx = 0; idx < data.length; idx++ ) {
	var key      = data[idx].getAttribute( 'key' );
	var val      = '';
	var children = data[idx].childNodes;
	
	for( var childIdx = 0; childIdx < children.length; childIdx++ )
	{
	    val += children[childIdx].data;
	}
	
	var element = $( '.' + key, context );
	if( element.length > 0 )
	    element.html( val );
    }

} // ReplaceData

Utility.PrepopulateForm = function (json, context) {
    $.each( json, function (key, val) {
	$( '#' + key, context  ).val( val );
    } ); // each
} // PrepopulateForm

Utility.ReplaceDropdownOptions = function (xml) {
    var xmlRoot = xml.documentElement;
    var selects = xmlRoot.getElementsByTagName( 'select' );

    for( var idx = 0; idx < selects.length; idx++ ) {
	var select = $( '#' + selects[idx].getAttribute( 'id' ) )[0];
	
	if( !select )
	    continue;
	
	while( select.options.length > 0 )
	    select.remove( select.options.length -1 );
	
	var opts = selects[idx].getElementsByTagName( 'option' )
	$.each( opts, function (i, opt) {
	    var optIdx = select.options.length;
	    select.options[optIdx] = new Option();
	    select.options[optIdx].text = opt.getAttribute( 'text' );
	    select.options[optIdx].value = opt.getAttribute( 'value' );
	} );
    }
} // ReplaceDropdownOptoins

Utility.ShowNavigation = function () {
    var showHtmlCssNavigation = Cookies.get( 'rgshcn' );

    if( showHtmlCssNavigation ) {
	$( '#nav' ).show();
    }
    else {
	$( '#flash-nav' ).show();
	Cookies.set( 'rgshcn', 1, 300 );
    }
} // ShowNavigation

Utility.ShowCarouselControls = function (jc, btn, enabledFlag) {
    if( enabledFlag )
	$( btn ).css( 'display', 'block' );
    else
	$( btn ).css( 'display', 'none' );

    return;
} // Utility.ShowCarouselControls

Utility.ShowErrors = function (xml, container) {
    var errors = xml.getElementsByTagName( 'error' );
    for( var idx = 0; idx < errors.length; idx++ ) {
	var err = errors[idx];
	    
	var id  = err.getAttribute( 'key' );
	var msg = err.getAttribute( 'msg' );
	    
	$( '#' + id + '-error', container ).html( msg ).show();
    }
}

Utility.Bind = function (funcName, obj) {
    var method 
	= typeof funcName == "function" ? funcName
	:                                 obj[funcName]
        ;
    
    return function() {
	return method.apply( obj, arguments );
    };
} // Bind

Utility.TriggerTracking = function (url) {
    if( url != null && typeof pageTracker != "undefined" ) {
		pageTracker._trackPageview( url ); // defined at bottom of page in analytics.comp
	}
} // TriggerTracking

/**********************************************
 **
 ** Function for various mini-forms on the site
 **
 **********************************************/

var SignIn       = new Object();
SignIn.OnSuccess = function (xml) {

    Utility.ReplaceData( xml, $( '#loggedInStatus' ) );

    $( '#loggedOutStatus' ).hide(
	'slow',
	function () {
	    $( '#loggedInStatus' ).show( 'slow' )
	}
    ); // hide
} // SignIn.onSuccess

SignIn.Logout = function( options ) {
    
    var doError = function () {
	alert( 'There was a problem logging you out.  Please try again in a few minutes.' );
    };

    var doSuccess = function () {
	$( '#loggedInStatus' ).hide( 'slow',
				     function () {
					 $( '#loggedOutStatus' )
					 .show( 'slow' )
				     } );
	if( options.success ) {
	    options.success();
	}
    };

    $.ajax( {
	type    : "POST",
	url     : "/services/account/logout.xml",
	success : doSuccess,
	error   : doError
    } );

    return false;
} // SignIn.Logout

var ForgotPassword = new Object();

ForgotPassword.OnSuccess = function (xml, confirmId) {
    
    if( !confirmId )
	confirmId = 'forgotPasswordConfirm';

    var conf = $( '#' + confirmId );

    Utility.ReplaceData( xml, conf );

    $( '#forgotPassword' ).slideUp( 
	'normal',
	function () {
	    conf.slideDown( 'normal' )
	}
    ); // slideUp
} // ForgotPassword.onSuccess

var NewsletterSignup = new Object();

NewsletterSignup.SetupMiniForm = function() {

    var nlInlineForm = $( '#newsletterForm' );
    var nlErrorsForm = $( '#newsletterError' );
    
    $( 'form.inline', nlInlineForm ).bind(
	'submit',
	function (nlForm) {
	    $( '#newsletter2' ).val( $( "#newsletter" ).val() );
	    $( 'form', nlErrorsForm ).submit();
	    
	    return false;
	}
    ); // bind(submit)
    
    new MiniForm(
	nlErrorsForm,
	{
	    pleaseWait : false,
	    success : NewsletterSignup.OnSuccess,
	    error   : NewsletterSignup.OnErrors
	}
    ); // MiniForm

    $( '#newsletter' ).bind( 
	'focus',
	function () { 
	    if( !this.previousValue
		|| this.value == this.previousValue )
	    {
		this.previousValue = this.value;
		this.value         = '';
	    }
	}
    ); // bind(focus)

    $( '#newsletter' ).bind( 
	'blur',
	function () { 
	    if( this.value == '' ) 
		this.value = this.previousValue;
	}
    ); // bind(blur)
} // NewsletterSignup.SetupMiniForm

NewsletterSignup.OnSuccess = function(xml) {

    var conf = $( '#newsletterConfirm' );
    Utility.ReplaceData( xml, conf );

    $( '#newsletterError' ).slideUp(
	'normal',
	function () {
	    conf.slideDown( 'normal' )
	}
    ); // slideUp
} // NewsletterSignup.OnSuccess

NewsletterSignup.OnErrors = function() {
    $( '#newsletterError' ).slideDown();
} // NewsletterSignup.OnErrors

var TellAFriend = new Object();

TellAFriend.OnSuccess = function (xml) {

    var confirmDiv = $( '#tellFriendConfirm' );
    Utility.ReplaceData( xml, confirmDiv );
    
    $( '#tellFriendForm' ).slideUp( 
	'normal',
	function () {
	    confirmDiv.slideDown();
	}
    ); //slideUp
} // TellAFriend.OnSuccess

var WishList = new Object();

WishList.AddItem = function (itemId) {
    var onSuccess = function (xml) {
	WishList.HandleAddItemResponse( xml, itemId );
    };

    $.ajax( {
	type     : "POST",
	url      : "/services/account/add-to-wishlist.xml",
	data     : { 'item_id' : itemId },
	success  : onSuccess,
	dataType : 'xml'
    } );
} // WishList.AddItem

WishList.HandleAddItemResponse = function (xml, itemId) {
    var xmlRoot = xml.documentElement;
    var success = xmlRoot.getAttribute( 'code' );

    if( success == 1 )
    {
	// Auto setup close link
	var wlConfirm = $( '#wishlistConfirm' );
	if( !wlConfirm.closeLinkSetup ) {
	    $( '.cancel', wlConfirm ).bind( 
		'click',
		function () {
		    wlConfirm.slideUp( 
			'normal',
			function () {
			    $( '#wishlistBtn' ).hide(
				'fast',
				function () {
				    $( '#wishlistAddedBtn' ).show( 'fast' )
				}
			    ); // hide
			}
		    ); // slideUp
		    return false;
		}
	    ); // bind
	    wlConfirm.closeLinkSetup = true;
	}

	$( '#tellFriendForm' ).slideUp();
	wlConfirm.slideDown();
    }
    else if( success == -1 )
    {
	var onSignInSuccess = function (successXml) {
	    SignIn.OnSuccess(successXml);
	    WishList.AddItem(itemId);
	};
	
	var wlSignin   = $( '#wishlistSignin' );
	var wlMiniForm = wlSignin[0].miniForm;

	if( !wlMiniForm  ) {
            wlMiniForm = new MiniForm( wlSignin, { pleaseWait : false } );
	}
	
	wlMiniForm.options['success'] = onSignInSuccess;

	var wlForgotPassword = $( '#wishlistForgotPassword' );
	if( !wlForgotPassword[0].miniForm )
	{
	    var onForgotPassSuccess = function (successXML) {
		return ForgotPassword.OnSuccess( successXML, 'wishlistForgotPasswordConfirm' );
	    };

	    new MiniForm( 
		wlForgotPassword,
		{
		    pleaseWait : false,
		    success : onForgotPassSuccess
		}
	    );
	}

	$( '#wishlistSignin' ).slideDown();
    }
}// WishList.HandleAddItemResponse

WishList.RemoveItem = function (itemId) {
    var removeItemFormElem = $( '#remove-item-form' )[0];
    
    try {
	removeItemFormElem['item_id'].value = itemId;
	removeItemFormElem.submit();
    } catch (e) {
//	alert( 'Error: ' + e ); // TODO: Don't alert out error!
    }

    return false;
} // WishList.RemoveItem

/**********************************************
 **
 ** CHECKOUT FUNCTIONS
 **   (depends on jquery)
 **
 **********************************************/

/* BEGIN: CHECKOUT */

var Checkout = new Object();

Checkout.Initialize = function ()
{
    // Setup handlers for quantity changes
    var jqQtyChgList = $( '.change-qty' );
    for( var idx = 0; idx < jqQtyChgList.length; idx++ ) {
	var jqQtyChg       = jqQtyChgList.eq( idx );
	var qtyChgFormElem = $( 'form', jqQtyChg )[0];
	var qtyInputElem   = qtyChgFormElem['quantity'];

	qtyInputElem.previous_value = qtyInputElem.value;
	
	$( 'input', jqQtyChg ).bind( 
	    'focus',
	    { form_element : qtyChgFormElem },
	    Checkout.ShowUpdateQuantityLink
	);

	$( 'input', jqQtyChg ).bind( 
	    'blur',
	    { form_element : qtyChgFormElem },
	    Checkout.UpdateItemQuantity
	);
	$( 'form', jqQtyChg ).bind( 
	    'submit',
	    { form_element : qtyChgFormElem },
	    Checkout.UpdateItemQuantity
	);
	$( '.remove', jqQtyChg ).bind( 
	    'click',
	    { form_element : qtyChgFormElem },
	    Checkout.RemoveItem
	);
    } // foreach chg qty 

    // Setup a "state" for each bucket
    // Possible states:
    //   pending - Step not reached yet
    //    insert - Step currently active for first time (form showing)
    //  complete - Step has been completed, info is showing
    //    update - User clicked the edit link for this step (form showing)
    var jqBucketList = $( '.bucket' );
    for( var idx = 0; idx < jqBucketList.length; idx++ ) {
	var jqBucket   = jqBucketList.eq( idx );
	var bucketElem = jqBucket[0];
	
	if( jqBucket.hasClass( 'static' ) ) {
	    bucketElem.checkoutState = 'complete';
	} 
	else if( jqBucket.hasClass( 'edit' ) ) {
	    bucketElem.checkoutState = 'insert';
	    Checkout.PrepopulateInputForm( jqBucket );
	}
	else {
	    bucketElem.checkoutState = 'pending';
	}
	
	bucketElem.checkoutIndex = idx;
    } // for each bucket

    // Setup mini-form for top-right signin link
    new MiniForm( 
	$( '#signInForm' ),
	{
	    success  : Checkout.PostSignIn
	}
    );

    // Setup mini-forms foreach bucket
    new MiniForm( 
	$( '#signin-bucket form' ),
	{
	    beforeSubmit : function () { $( '#no_account' ).val( 0 ) },

	    success  : Checkout.PostSignIn,
	    error    : Checkout.PostNoAccount,
	    failure  : Checkout.HandleUnknownError,
	    hideForm : null
	}
    ); // signin

    new MiniForm( 
	$( '#shipping-bucket form' ),
	{
	    success     : Checkout.PostShippingInfo,
	    failure     : Checkout.HandleUnknownError,
	    hideForm    : null,
	    resetOnSave : false
	}
    ); //shipping info

    new MiniForm( 
	$( '#shipping-method-bucket form' ),
	{
	    success     : Checkout.PostShippingMethod,
	    failure     : Checkout.HandleUnknownError,
	    hideForm    : null,
	    resetOnSave : false
	}
    ); //shipping method

    new MiniForm( 
	$( '#payment-info-bucket form' ),
	{
	    success     : Checkout.PostPaymentInfo,
	    failure     : Checkout.HandleUnknownError,
	    hideForm    : null,
	    resetOnSave : false
	}
    ); //payment info

    new MiniForm( 
	$( '#save-info-bucket form' ),
	{
	    success     : Checkout.PostSaveInfo,
	    failure     : Checkout.HandleUnknownError,
	    hideForm    : null,
	    resetOnSave : false
	}
    ); //save info

    new MiniForm( 
	$( '#review-bucket form' ),
	{
	    success     : Checkout.PostPlaceOrder,
	    error       : Checkout.PostPlaceOrder,
	    failure     : Checkout.HandleUnknownError,
	    hideForm    : null,
	    resetOnSave : false
	}
    ); //review

    // Setup edit links
    $( '.bucket a.edit' ).click( 
	function () {
	    // Get bucket that this link is in
	    var link   = $( this );
	    var bucket = link.parents( '.bucket' );

	    // Show input form
	    Checkout.ShowInputForm( bucket );
	    
	    return false;
	}
    ); // edit links

    // Setup other functionality
    $( '#signin-bucket a.logout' ).click( Checkout.Logout );
    $( '#logout-link' ).click( Checkout.Logout );
    $( '#signin-bucket a.no-account' ).click( Checkout.NoAccount );
    $( '#save-info-bucket a.skip' ).click( function () {
	Checkout.PostSaveInfo( null );
	return false;
    } );
    $( '#payment-info-bucket .cvv-help' )
        .mouseover( Checkout.ShowCVVHelp )
        .mouseout( Checkout.HideCVVHelp )
        .click( function () { return false; } )
        ;
    $( '#payment-info-bucket #ship_to_is_billing_flag-set input' )
        .click( Checkout.UseShippingForBilling )
        ;

} // Initialize

Checkout.ShowUpdateQuantityLink = function (evt, showLink)
{
    if( showLink == null )
	showLink = false;

    var delay = 2000;

    var formElem = evt.data.form_element;
    var qtyElem  = formElem['quantity'];
    var prevQty  = qtyElem.previous_value;
    var currQty  = qtyElem.value;

    formElem.timeoutID = null;
    
    if( prevQty != currQty ) {
	if( showLink ) {
	    $( qtyElem ).after( '<a href="#" onclick="return false;" class="next">Update Quantity</a>' );
	}
	else {
	    formElem.timeoutID = window.setTimeout( 
		function() { Checkout.ShowUpdateQuantityLink( evt, true ) },
		1000
	    );
	}
    }
    else {
	formElem.timeoutID = window.setTimeout( 
	    function() { Checkout.ShowUpdateQuantityLink( evt ) },
	    delay
	);
    }
} // ShowUpdateQuantityLink

Checkout.UpdateItemQuantity = function (evt, newQty)
{
    $( '.error', $( '#mybag' ) ).hide().html( '' );
    $( '.quantity-error' ).hide().html( '' );

    var formElem = evt.data.form_element;

    if( formElem.timeoutID != null ) {
	window.clearTimeout( formElem.timeoutID );
    }

    var jqUpdateQtyLink = $( formElem['quantity'] ).next( '.next' );
    if( jqUpdateQtyLink.length > 0 )
	jqUpdateQtyLink.remove();

    var prevQty  = formElem['quantity'].previous_value;
    if( newQty == null )
	newQty = formElem['quantity'].value;

    if( newQty != prevQty ) {
	var updatingMsg = new PleaseWait( 
	    $( formElem['quantity'] ),
	    {
		doHide : false,
		text   : 'UPDATING'
	    }
	);

	formElem['quantity'].previous_value = newQty;

	//alert( '(' + evt.type + ') Updating quantity to ' + newQty + ' ...' );
	var prodId      = formElem['pid'].value;
	var jqContainer = $( formElem ).parents( ".item-container" );
	
	var onSuccess = function (xml) {
	    updatingMsg.stop();
	    Checkout.PostItemQuantityUpdate( xml, jqContainer );
	};

	$.ajax( {
	    url      : formElem.getAttribute( 'action' ),
	    type     : formElem.getAttribute( 'method' ),
	    data     : { pid : prodId, quantity : newQty },
	    dataType : 'xml',
	    error    : function (req, stat, msg) { 
		Checkout.HandleUnknownError( 'qty' );
		updatingMsg.stop();
		//alert( 'Failure: ' + req.responseText ) 
	    }, // TODO: Implement
	    success  : onSuccess
	} ); // ajax
    }

    return false;
} // UpdateItemQuantity

Checkout.RemoveItem = function (evt)
{
    Checkout.UpdateItemQuantity( evt, 0 );

    return false;
} // RemoveItem

Checkout.HandleUnknownError = function ( mode )
{
    var descErr  = 'An unknown error has occurred.  ROBOTGALAXY has been '
	         + 'alerted to this error.  Please wait a few minutes and '
	         + 'then try again.  We apologize for any inconvenience.'
	         ;

    if( mode == 'qty' )
    {
	var titleErr = 'An error occurred while updating an item\'s quantity.';
    }
    else
    {
	var titleErr = 'An error occurred while processing your information.';
    }

    $( '#title-error' ).html( titleErr ).show();
    $( '#description-error' ).html( descErr ).show();

    location.href = '#top';
    
    return;
}

Checkout.ProceedToNextStep = function (thisStep, xml, infoIdx, trackingURL)
{
    var buckets      = $( '.bucket' );
    var currJQBucket = buckets.eq( thisStep );

    var nextStep, nextJQBucket;
    for( var idx = thisStep+1; idx < buckets.length; idx++ ) {
	var jqBucket = buckets.eq( idx );
	if( jqBucket[0].checkoutState == 'pending' ) {
	    nextJQBucket = jqBucket;
	    nextStep     = idx;
	    break;
	}
	else if( jqBucket[0].checkoutState == 'complete' ) {
	    ddaccordion.expandone( 'hdr', jqBucket[0].checkoutIndex );
	}
    }

    var infoSelector = infoIdx != null ? '.info:eq(' + infoIdx + ')'
                     :                   '.info'
	             ;

    // After success, insert some data from server into page
    Utility.ReplaceData( xml, $( infoSelector, currJQBucket ) );

    // Change the state of this of this step and the next step
    currJQBucket[0].checkoutState = 'complete';
    if( nextJQBucket )
	nextJQBucket[0].checkoutState = 'insert';

    // Then hide the current form
    $( '.input-form', currJQBucket ).hide(
	'normal',
	function () { 
	    // Then show the "info" box for this bucket
	    Utility.TriggerTracking( trackingURL );
	    $( infoSelector, currJQBucket ).show(
		'normal',
		function () {
		    // And try to prepopulate the next bucket
		    if( nextJQBucket )
			Checkout.PrepopulateInputForm( nextJQBucket );
		}
	    ) // show(
	}
    ); // hide(
} // ProceedToNextStep

Checkout.PrepopulateInputForm = function (jqBucket, json, proceed) {

    if( proceed == null )
	proceed = false;
    
    // If this is first call
    if( !json && !proceed) {
	var stepName = jqBucket[0].id;

	stepName     
	    = stepName.substr( 0, stepName.length - "-bucket".length );

	var onSuccess = function (json) {
	    Checkout.PrepopulateInputForm( jqBucket, json );
	};

	var onError = function () {
	    Checkout.PrepopulateInputForm( jqBucket, null, true );
	};

	// Then use ajax to try and retrieve data
	$.ajax( {
	    url      : '/services/checkout/get_data.json',
	    type     : 'post',
	    data     : { step : stepName },
	    dataType : 'json',
	    error    : onError,
	    success  : onSuccess
	} ); // ajax
    }
    else {
	// Prepopulate the form
	if( json != null )
	    Utility.PrepopulateForm( json, jqBucket );

	// Then expand next bucket
	$( '.no-access', jqBucket ).hide();
	$( '.input-form', jqBucket ).show();
			    
	ddaccordion.expandone( 'hdr', jqBucket[0].checkoutIndex );
    }
} // PrepopulateInputForm

Checkout.ShowInputForm = function (jqBucket)
{
    // Hide any other input forms before continuing
    $( '.bucket' ).each( function (idx, bucketElem) {

	// Do nothing for the bucket we are showing the form for
	if( bucketElem.checkoutIndex == jqBucket[0].checkoutIndex )
	    return true;
	
	// If this bucket's form is showing (for the first time)
	if( bucketElem.checkoutState == 'insert' ) {
	    // Then hide the form, show "no-access" and collapse this step
	    $( '.input-form', bucketElem ).hide();
	    $( '.no-access', bucketElem ).show();
	    ddaccordion.collapseone( 'hdr', idx );
	    
	    bucketElem.checkoutState = 'pending';
	} // insert

	// If this bucket's form is showing (but not the first time)
	if( bucketElem.checkoutState == 'update' ) {
	    // Then hide the form, show "info"
	    $( '.input-form', bucketElem ).hide();
	    $( '.info', bucketElem ).show();
	    
	    bucketElem.checkoutState = 'complete';
	    
	} // update
    } ); // each

    // Change the state of this bucket
    jqBucket[0].checkoutState = 'update';

    // Hide the info box, show the input form
    $( '.info', jqBucket ).hide(
	'normal',
	function () {
	    $( '.input-form', jqBucket ).show( 'normal' )
	}
    );

    return false;
} // ShowInputForm

Checkout.Logout = function() {
    
    var numStepsCompleted = 0;
    $( '.bucket:gt(1)' ).each( function (idx, bucketElem) {
	if( bucketElem.checkoutState == 'complete'
	    || bucketElem.checkoutState == 'update' )
	    numStepsCompleted++;
    } );

    var proceedWithLogout = true;

    if( numStepsCompleted > 0
	&& !confirm( 'By logging out, all of you checkout information will '
		     + 'be lost.  Are you sure you want to continue?' ) )
    {
	proceedWithLogout = false;
    }

    if( proceedWithLogout )
    {
	// On logout success
	var onSuccess = function () {
	    // Iterate through all buckets
	    $( '.bucket' ).each( function( idx, bucketElem ) {
		// Reset its state, form input and collapse it
		bucketElem.checkoutState = 'pending';
		
		var form     = $( 'form', bucketElem )[0];
		var miniForm = form ? form.miniForm : null;
		if( miniForm )
		    miniForm.resetMiniForm();
		
		if( idx >= 2 )
		    ddaccordion.collapseone( 'hdr', idx );
	    } );

	    // Hide all info and input form boxes
	    $( '.bucket .info' ).hide();
	    $( '.bucket .input-form' ).hide();
	    
	    // Show all no access boxes
	    $( '.bucket .no-access' ).show();

	    // Show the signin form
	    $( '#signin-bucket .input-form' ).show();
	} // onSuccess
	
	SignIn.Logout( { success : onSuccess } );
    }

    return false;
} // Checkout.Logout

Checkout.HandleNewShipmentMethods = function (xml) 
{
    Utility.ReplaceDropdownOptions( xml );
	
    var handled                = false;
    var newShipmentOptionsFlag = false;
    
    var selects = xml.getElementsByTagName( 'select' );
    for( var idx = 0; idx < selects.length; idx++ ) {
	var select   = selects[idx];
	var selectId = select.getAttribute( 'id' );
	if( selectId == 'shipment_method_fk' ) {
	    newShipmentOptionsFlag = true;
	} // if shipment method options
    } // for each select 

    if( newShipmentOptionsFlag ) {
	var methodBucketElem = $( '#shipping-method-bucket' )[0];
	
	if( methodBucketElem
	    && methodBucketElem.checkoutState == 'complete' ) {
	    $( '#shipping-method-bucket .step-error' ).html( 
		'Available shipping methods may have changed.  Please choose a '
		    + 'new shipping method.' ).show();
	    Checkout.ShowInputForm( $( '#shipping-method-bucket' ) );
	    window.location.href = '#shipping-method-anchor';
	    handled = true;
	} // if method bucket was already completed by user
    } // if new shipment options

    return handled;
} // HandleNewShipmentMethods

Checkout.PostItemQuantityUpdate = function (xml, jqItemContainer)
{
    var xmlRoot = xml.documentElement;
    var code    = xmlRoot.getAttribute( 'code' );

    if( code == -1 ) {
	jqItemContainer.remove();
    }

    if( code == 1 || code == -1 ) {
	Utility.ReplaceData( xml );

	var itemCount = $( '.item-container' ).length;
	if( itemCount == 0 ) {

	    $( '#mycart' ).hide();
	    $( '.bucket:gt(0)' ).hide();
	    $( '.empty-msg' ).show();

	}
	else { // ( itemCount > 0 )
	    
	    Checkout.HandleNewShipmentMethods( xml );
	    
	}
    } // if success
    else { // ( code == 0 ) 
	var errors = xml.getElementsByTagName( 'error' );
	for( var idx = 0; idx < errors.length; idx++ ) {
	    var err = errors[idx];
	    
	    var id  = err.getAttribute( 'key' );
	    var msg = err.getAttribute( 'msg' );
	    
	    $( '.' + id + '-error', jqItemContainer ).html( msg ).show();
	}
    }  // if failure
} // PostItemQuantityUpdate

Checkout.PostSignIn = function (xml) 
{
    SignIn.OnSuccess( xml );
    Checkout.ProceedToNextStep( 1, xml, 0, '/shop/cart/shipping.html' );

    var saveInfoJQBucket = $( '#save-info-bucket' );
    Utility.ReplaceData( xml, saveInfoJQBucket );
    saveInfoJQBucket.addClass( 'static' );
    saveInfoJQBucket[0].checkoutState = 'complete';
    
} // PostSignIn

Checkout.NoAccount = function() {

    $( '#no_account' ).val( '1' );
    $( '#signin-bucket form' ).submit();
    
    return false;
} // NoAccount

Checkout.PostNoAccount = function (xml)
{
    var xmlRoot = xml.documentElement;
    var code    = xmlRoot.getAttribute( 'code' );

    if( code == -1 )
        Checkout.ProceedToNextStep( 1, xml, 1, '/shop/cart/shipping.html' );
} // PostNoAccount

Checkout.PostShippingInfo = function (xml)
{
    var handled = Checkout.HandleNewShipmentMethods( xml );

    if( !handled )
	Checkout.ProceedToNextStep( 2, xml, null, '/shop/cart/shipping-method.html' );
} // PostShippingInfo

Checkout.PostShippingMethod = function (xml)
{
    Utility.ReplaceData( xml, $( '#review-bucket' ) );

    Checkout.ProceedToNextStep( 3, xml, null, '/shop/cart/billing.html' );
} // PostShippingMethod

Checkout.PostPaymentInfo = function (xml)
{
    Utility.ReplaceData( xml, $( '#review-bucket' ) );

    Checkout.ProceedToNextStep( 4, xml, null, '/shop/cart/save-info.html'  );
} // PostPaymentInfo

Checkout.PostSaveInfo = function (xml)
{
    if( xml != null )
	SignIn.OnSuccess( xml );

    Checkout.ProceedToNextStep( 5, xml, null, '/shop/cart/checkout.html' );
} // PostSaveInfo

Checkout.PostPlaceOrder = function (xml)
{
    var xmlRoot = xml.documentElement;
    var code    = xmlRoot.getAttribute( 'code' );

    if( code == 1 ) { // SUCCESS !
	Utility.TriggerTracking( '/shop/cart/receipt.html' );

	$( '.my-cart' ).slideUp( 
	    'normal',
	    function () {
		Utility.ReplaceData( xml );
		$( '.my-cart' ).slideDown( 'normal' );
	    }
	);
    }
    else if( code == -1 ) { // Payment error 
	var msg = 'There was a problem processing your payment information.  '
	        + 'Please review your information and try again.'
	        ;
	
	var jqPaymentBucket = $( '#payment-info-bucket' );
	
	$( '.step-error', jqPaymentBucket ).html( msg ).show();

	($( 'form', jqPaymentBucket ))[0].miniForm.showErrors( xmlRoot );

	Utility.TriggerTracking( '/shop/cart/billing.html' );

	Checkout.ShowInputForm( jqPaymentBucket );
    }
    else if( code == -2        // Inventory error
	     || code == -3 ) { // Misc error
	Utility.ShowErrors( xmlRoot, $( '#mybag' ) );
	location.href = '#top';
    }
} // PostPlaceOrder

Checkout.ShowCVVHelp = function (evt)
{
    if( !evt ) 
	evt = event;
    
    var help = $( '#cvv_info' );
    
    if( evt.clientY < 200 )
	help.css( "top", (evt.clientY + 10) + 'px' );
    else
	help.css( "top", (evt.clientY - 150) + 'px' );

    help.css( "left", (evt.clientX - 300)  + 'px' );

    help.show();
    
    return false;
} // ShowCVVHelp

Checkout.HideCVVHelp = function (evt)
{
    $( '#cvv_info' ).hide();

    return false;
} // HideCVVHelp

Checkout.UseShippingForBilling = function (evt) 
{
    var isChecked = evt.target.checked;

    var fields = [ 
	'address_line_1',
	'address_line_2',
	'city',
	'state',
	'zip',
	'phone'
    ];

    for( var idx = 0; idx < fields.length; idx++ ) {
	var billToKey = '#bill_to_' + fields[idx];
	var shipToKey = '#ship_to_' + fields[idx];

	if( isChecked )
	    $( billToKey ).val( $( shipToKey ).val() );
	else
	    $( billToKey ).val( [] );
    } // for

    return;
} // UseShippingForBilling


/* END: CHECKOUT */

/**********************************************
 **
 ** Ajax Mini Form Object
 **   (depends on jquery)
 **
 **********************************************/

/* BEGIN: MiniForm */

function MiniForm( container, options )
{
    var tag = container[0].tagName.toUpperCase();

    this.container = container;
    this.form      = tag == "FORM" ? container : $( 'form', container );
    this.options   = options || {};

    if( typeof this.options.hideForm == "undefined" )
	this.options.hideForm = 'slide';
    
    if( typeof this.options.resetOnSave == "undefined" )
	this.options.resetOnSave = true; 

    if( typeof this.options.pleaseWait == "undefined" )
	this.options.pleaseWait = true; 

    if( typeof this.options.alertResponse == "undefined" )
	this.options.alertResponse = false; 

    if( $( '.submit', container ) )
	$( '.submit', container ).click( 
	    Utility.Bind( 'submitMiniForm', this )
	);

    if( $( '.cancel', container ) )
	$( '.cancel', container ).click(
	    Utility.Bind( 'cancelMiniForm', this )
	);

    this.form.ajaxForm( this.getAjaxFormOptions() ); 

    container[0].miniForm = this;
    
    return;
}

MiniForm.prototype = {

    submitMiniForm : function () {
	
	if( this.options.pleaseWait )
	    this.pleaseWait = new PleaseWait( $( '.submit', this.container ) );

	if( this.options.beforeSubmit )
	    this.options.beforeSubmit();
	this.form.submit();
	return false;
    } // submitMiniForm

    ,

    cancelMiniForm : function () {
	if( this.options.hideForm == 'slide' )
	{
	    this.container.slideUp( 'normal', 
				    Utility.Bind( 'resetMiniForm', this ) );
	}
	else
	{
	    this.resetMiniForm();
	}
	return false;
    } // cancelMiniForm

    ,

    resetMiniForm : function () {
	this.clearErrors();
	this.clearInput();
	return false;
    } // resetMiniForm
    
    ,

    getAjaxFormOptions : function () {
	var afOpts = {
	    beforeSubmit : Utility.Bind( 'clearErrors', this ),
	    success      : Utility.Bind( 'onSubmitSuccess', this ),
            error        : Utility.Bind( 'onSubmitFailure', this ),
	    dataType     : 'xml'
	};

	if( this.options.alertResponse ) {
	    afOpts.complete = function (resp) {
		alert( resp.responseText );
		return false;
	    }
	}

	return afOpts;
    } // getAjaxFormOptions
    
    ,

    clearErrors : function () {
	$( '.error', this.container ).html( '' ).hide();
    } // clearErrors

    ,

    clearInput : function () {
	$( "input[type!='hidden']", this.container ).val( [] );
	$( 'select', this.container ).val( '' );
	$( 'textarea', this.container ).val( '' );
    } // clearInput

    ,

    onSubmitSuccess : function (xml) {

	xmlRoot     = xml.documentElement;
	var success = xmlRoot.getAttribute( 'code' );

	if( this.options.pleaseWait && this.pleaseWait ) {
	    this.pleaseWait.stop();
	    this.pleaseWait = null;
	}
    
	if( success == 1 ) {
	    var afterSlideUp = function () { this.resetMiniForm() };

	    if( this.options.success ) {
		afterSlideUp = function () {
		    if( this.options.resetOnSave )
			this.resetMiniForm();

		    this.options.success( xml );
		}
	    }
	    
	    if( this.options.hideForm == 'slide' )
	    {
		this.container.slideUp( 'normal', 
					Utility.Bind( afterSlideUp, this ) );
	    }
	    else
	    {
		afterSlideUp.call( this );
	    }
	}
	else {
	    this.showErrors( xmlRoot );
	    if( this.options.error ) {
		this.options.error(xml);
	    }
	}
    } // onSubmitSuccess
    
    ,

    onSubmitFailure : function (xml) {
	if( this.options.pleaseWait && this.pleaseWait ) {
	    this.pleaseWait.stop();
	    this.pleaseWait = null;
	}
	if( this.options.failure ) {
	    this.options.failure(xml);
	}
    } // onSubmitFailure

    ,

    showErrors : function (xml) {
	Utility.ShowErrors( xml, this.container );
    } // showErrors

} // MiniForm.prototype

/* END: MiniForm */

/* BEGIN: PleaseWait */

function PleaseWait( jqSibling, params )
{
    this.options = params || {};

    if( this.options.doHide == null ) 
	this.options.doHide = true;

    if( this.options.text == null )
	this.options.text = 'PLEASE WAIT';
    
    if( this.options.doHide )
	jqSibling.hide();

    this.dots = '.';
    
    jqSibling.after( '<p class="next">'
		     + this.options.text + ' '
		     + '<span class="dots">' + this.dots + '</span>'
		     + '</p>' );

    this.jqSibling    = jqSibling;
    this.jqPleaseWait = jqSibling.next();
    this.jqDots       = $( '.dots', this.jqPleaseWait );
    this.delay        = 700;
    this.dotCount     = 5;

    this.animate();
    
    return;
} // PleaseWait

PleaseWait.prototype = {

    animate : function () {

	if( this.dots.length == this.dotCount ) {
	    this.dots  = '.';
	} else {
	    this.dots += '.';
	}
	
	var dotsHTML = this.dots;

	if( this.dots.length < this.dotCount ) {
	    dotsHTML += '<span style="visibility: hidden">';
	    for( var idx = this.dots.length; idx < this.dotCount; idx++ ) {
		dotsHTML += '.';
	    }
	    dotsHTML += '</span>';
	}

	this.jqDots.html( dotsHTML );

	this.timeoutID = window.setTimeout( 
	    Utility.Bind( 'animate', this ), this.delay
	);
    } // animate

    ,
    
    stop : function () {

	window.clearTimeout( this.timeoutID );
	
	this.jqPleaseWait.remove();

	if( this.options.doHide )
	    this.jqSibling.show();
    } // stop

} // PleaseWait.prototype

/* END: PleaseWait */

/* BEGIN: Play Side Flash */

function openNewWindow(url, name, args) 
{ 
    newWindow = window.open(url, name, args);
}
			
function goEnvironment()
{
    openNewWindow( 
	"/playside/check.html",
	"RG",
	"width=1024,height=668,toolbar=no,scrollbars=no,"
	+ "menubar=no,status=no,titlebar=no,toolbar=no"
    );
}


/* END: Play Side Flash */
