validate=true;  // every submit button needs to set this variable so validation code knows whether to validate or not

// precache larger images
var img = new Image();
img.src = "img/header.jpg";
img.src = "img/cs_layout.jpg";
img.src = "img/anim/cs_rotation.gif";

// coppied from JavaScript & DHTML Cookbook by Danny Goodman
function formatNumber( num, decplaces ) {
    // convert in case it arrives as a string value
    num = parseFloat(num);
    // make sure it passes conversion
    if(!isNaN(num) ) {
        // multiply value by 10 to the decplaces power;
        // round the result to the nearest integer;
        // convert the result to a string
        var str = "" + Math.round( eval(num) * Math.pow(10,decplaces) );
        // exponent means value is too big or small for this routine
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        // if needed for small values, pad zeros
        // to the left of the number
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        // calculate decimal point position
        var decpoint = str.length - decplaces;
        // assemble final result from: (a) the string up to the position of
        // the decimal point; (b) the decimal point; and (c) the balance
        // of the string. Return finished product.
        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}

function cartShipZoneChange( select ) {
    var shipping = 0;
    var tax = 0;
    var subtotal = parseInt(document.cart.subtotal.value);
    switch( select.value ) {
        case 'us': shipping = 650; break;
        case 'us_va': shipping = 650; tax = subtotal * 0.05; break;
        case 'ca':
        case 'mx': shipping = 1500; break;
        case 'other': shipping = 2000; break;
    }
    if( subtotal > 5000 && (select.value == 'us' || select.value == 'us_va') ) shipping = 0;
    var shippingSpanElt = document.getElementById( 'shipping' );
    var newText = document.createTextNode( shipping==0 ? 'free!' : formatNumber( shipping/100, 2 ) );
    shippingSpanElt.replaceChild( newText, shippingSpanElt.firstChild );

    var taxSpanElt = document.getElementById( 'tax' );
    newText = document.createTextNode( formatNumber( tax/100, 2 ) );
    taxSpanElt.replaceChild( newText, taxSpanElt.firstChild );
    
    var totalSpanElt = document.getElementById( 'total' );
    newText = document.createTextNode( formatNumber( (shipping + subtotal)/100, 2 ) );
    totalSpanElt.replaceChild( newText, totalSpanElt.firstChild );
}

function pmtMethodClick( pmtMethod ) {
    var ccFields = document.getElementById( 'cc-fields' );
    ccFields.style.visibility = pmtMethod=='pp' ? 'hidden' : 'visible';
    var radioGroup = document.payment['pmt-method'];
    for( var i=0; i<radioGroup.length; i++ ) {
        if( radioGroup[i].value == pmtMethod ) return radioGroup[i].checked=true;
    }
}

function processOnload() {
    location.href = "result";
}

function setLabel( label, valid ) {
    var elt = document.getElementById( label );
    if( valid ) {
        elt.style.color = "#000000";
        elt.style.fontWeight = "normal";
    } else {
        elt.style.color = "#CB351A";
        elt.style.fontWeight = "bold";
    }
    return valid ? 0 : 1;
}

function validEmail( str ) {
    var re = /^\s*[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}\s*$/;
    return( str.match( re ) != null );
}

// #20: if the shipping country is international, put an asterick next
// to phone to indicate that it's required
function shippingCountryChange( select ) {
	var phoneLbl = document.getElementById( 'shipping-phone-lbl' );
	if( select.value == 'US'  ) {
    	var newText = document.createTextNode( 'Phone' );
	} else {
    	var newText = document.createTextNode( 'Phone*' );
	}
    phoneLbl.replaceChild( newText, phoneLbl.firstChild );
}

function validateShipping( form ) {
    if( !validate ) return true;
    var errors = 0;
    
    // shipping fields
    errors += setLabel( 'shipping-fname-lbl', form['shipping-fname'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-lname-lbl', form['shipping-lname'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-address1-lbl', form['shipping-address1'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-city-lbl', form['shipping-city'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-st-lbl', form['shipping-st'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-zip-lbl', form['shipping-zip'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-country-lbl', form['shipping-country'].value.match( /^\s*$/ ) == null );
    errors += setLabel( 'shipping-email-lbl', validEmail( form['shipping-email'].value ) );
	// phone is only required on international orders, for freight manifest
	// (see ticket #20 for more details)
	if( form['shipping-country'].value != 'US' ) {
    	errors += setLabel( 'shipping-phone-lbl', form['shipping-phone'].value.match( /^\s*$/ ) == null );
	}
    
    // if ANY billing field has data in it, we assume they mean to enter a billing address and then it has to be complete!
    if( form['billing-fname'].value.match( /^\s*$/ ) == null ||
        form['billing-lname'].value.match( /^\s*$/ ) == null ||
        form['billing-address1'].value.match( /^\s*$/ ) == null ||
        form['billing-address2'].value.match( /^\s*$/ ) == null ||
        form['billing-city'].value.match( /^\s*$/ ) == null ||
        form['billing-st'].value != '' ||
        form['billing-zip'].value.match( /^\s*$/ ) == null ||
        form['billing-country'].value.match( /^\s*$/ ) == null ||
        form['billing-phone'].value.match( /^\s*$/ ) == null ||
        form['billing-email'].value.match( /^\s*$/ ) == null ) {
            // now we gots to validate that shit
            var errorsBefore = errors;
            errors += setLabel( 'billing-fname-lbl', form['billing-fname'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-lname-lbl', form['billing-lname'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-address1-lbl', form['billing-address1'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-city-lbl', form['billing-city'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-st-lbl', form['billing-st'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-zip-lbl', form['billing-zip'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-country-lbl', form['billing-country'].value.match( /^\s*$/ ) == null );
            errors += setLabel( 'billing-email-lbl', validEmail( form['billing-email'].value ) );
            if( errors - errorsBefore > 0 ) document.getElementById( 'invalidBilling' ).style.display = "block";
    }
    if( errors > 0 ) document.getElementById( 'invalidMsg' ).style.display = "block";
    return errors == 0;
}

function validatePayment( form ) {
    if( !validate ) return true;
    var radioGroup = form['pmt-method'];
    for( var i=0; i<radioGroup.length; i++ ) {
        if( radioGroup[i].value == 'pp' && radioGroup[i].checked ) return true;
    }
    
    var errors = 0;
    errors += setLabel( 'cc-number-lbl', form['cc-number'].value.match( /^\s*(\d+[\s-]?)+\s*$/ ) != null );
    errors += setLabel( 'cc-CVV2-lbl', form['cc-CVV2'].value.match( /^\s*\d+\s*$/ ) != null );
    errors += setLabel( 'cc-expDate-lbl', form['cc-expMonth'].value != '' && form['cc-expYear'].value != '' );
    
    if( errors > 0 ) document.getElementById( 'invalidMsg' ).style.display = "block";
    return errors == 0;
}

