var loggedIn = false;
var currLogg = false;
var currPurchaseStep = 0;
var shippingOption = 1; // 1 - ground; 2 - express; 3 - next day
var creditCardType = 0; // 1 - mastercard; 2 - visa; 3 - discover; 4 - ae
var useShippingInformation = true;
var totalSum = 0;
var taxPrice=0;

var userFirstName = userMI = userLastName = userAddress1 = userAddress2 = userCity = '';
var userState = userZip = userCountry = '';

var ccnames = new Array( 'mastercard', 'visa', 'discover', 'americanexpress' );

var purchaseSlidingStep = 0;
var purchaseSlidingTimer = null;

function nextPurchaseStep()
{
    var nextPage;
    var login_result=false;
    var validationFunc = null;
    var prepareDataFunc = null;
	switch (currPurchaseStep) {
        case 0:
            nextPage = loggedIn ? 3 : 1;
            validationFunc = validateShoppingCart;
            break;
        case 1:
            if( loggedIn )
                {
                prepareDataFunc = fillShippingInformation;
                nextPage = 3;
                }
            else
                {
                nextPage = currPurchaseStep+1;
                hideElem('id_error');
                prepareDataFunc = fillCreateAnAccount;
                }
            break;
        case 2:
            validationFunc = validateCreateAnAccount;
            prepareDataFunc = fillShippingInformation;
            nextPage = 3;
            break;
        case 3:
            nextPage = 4;
            validationFunc = validateShippingInformation;
            prepareDataFunc = fillBillingInformation;
            break;
        case 4:
        	/*
        	if (parseFloat(taxPrice)==0.00) {
                        alert('Can\'t locate tax data.\nPlease review your shipping City/State/Zip Code.');
                        nextPage=3;
                        break;
                }
                */
		nextPage = 5;
            validationFunc = validateBillingInformation;
            prepareDataFunc = prepareSummaryPage;
            break;
        case 5:
		nextPage = 6;
            prepareDataFunc = preparePaymentPage;
            break;
        case 6:
            nextPage = 7;
            break;
        default:
            nextPage = currPurchaseStep+1;
            break;
        }
    if( validationFunc && !validationFunc() )
        return false;
    else
        if (currPurchaseStep==2)
            AddField();
        else 
        if(currPurchaseStep==3)
        {
            FLoadTax();
            
         }
    if( prepareDataFunc )
        prepareDataFunc();

    var pg1 = findObject( 'sc_cart_0'+(currPurchaseStep+1) );
    var pg2 = findObject( 'sc_cart_0'+(nextPage+1) );
    if( !pg1 || !pg2 )
        return false;

    pg1.style.left = 0;
    pg2.style.left = 582;
    showElem( 'sc_cart_0'+(nextPage+1) );
    //if (nextPage==6)
    //        showElem('navSelect');
    timerStr = 'slidePurchasePages( -1,'+(currPurchaseStep+1)+','+(nextPage+1)+');';
    purchaseSlidingTimer = setTimeout( timerStr, c_minimalDelay );
    return true;
}

function prevPurchaseStep()
{
    var nextPage;
    var validationFunc = null;
    var prepareDataFunc = null;
    switch (currPurchaseStep) {
        case 3:
            nextPage = 0;
            break;
        case 7:
            nextPage = 0;
            break;
        default:
            nextPage = currPurchaseStep-1;
            break;
        }

    var pg1 = findObject( 'sc_cart_0'+(currPurchaseStep+1) );
    var pg2 = findObject( 'sc_cart_0'+(nextPage+1) );
    if( !pg1 || !pg2 )
        return;

    pg1.style.left = 0;
    pg2.style.left = -582;
    showElem( 'sc_cart_0'+(nextPage+1) );
    timerStr = 'slidePurchasePages( 1,'+(currPurchaseStep+1)+','+(nextPage+1)+');';
    purchaseSlidingTimer = setTimeout( timerStr, c_minimalDelay );
}

function slidePurchasePages( direction, goAwayPage, comingPage )
{
    clearTimeout( purchaseSlidingTimer );
    var p1 = findObject( 'sc_cart_0'+goAwayPage );
    var p2 = findObject( 'sc_cart_0'+comingPage );
    if( !p1 || !p2 )
        return;
    x1 = p1.offsetLeft + direction*38;
    x2 = p2.offsetLeft + direction*38;
    p1.style.left = x1;
    p2.style.left = x2;

    var p3 = findObject( 'gm' );
    if( p3 )
        {
        if( (comingPage == 6) || (goAwayPage == 6) )
            {
            x3 = p3.offsetLeft - direction*20;
            p3.style.left = x3;
            }
        }

    purchaseSlidingStep++;
    if( purchaseSlidingStep >= 15 )
        {
        purchaseSlidingStep = 0;
        currPurchaseStep = comingPage-1;
        p2.style.left = 0;
        hideElem( 'sc_cart_0'+goAwayPage );
        }
    else
        purchaseSlidingTimer = setTimeout( 'slidePurchasePages('+direction+','+goAwayPage+','+comingPage+');', c_minimalDelay );
}

function validateCreateAnAccount()
{
    res = !isEmpty( 'email' );
    res &= !isEmpty( 'cemail' );
    res &= !isEmpty( 'npswd' );
    res &= !isEmpty( 'cnpswd' );
    res &= !isEmpty( 'fname' );
    res &= !isEmpty( 'lname' );
    res &= !isEmpty( 'address1' );
    res &= !isEmpty( 'city' );
    res &= validNumber( 'zip', 5, 0 );
    res &= !isEmpty( 'country' );
    var o1 = findObject( 'email' );
    var o2 = findObject( 'cemail' );
    if( o1 && o2 && (o1.value == o2.value) )
        o2.className = 'txtinput';
    else
        {
        o2.className = 'wrongdata';
        return false;
        }
    o1 = findObject( 'npswd' );
    o2 = findObject( 'cpswd' );
    if( o1 && o2 && (o1.value == o2.value) )
        o2.className = 'txtinput';
    else
        {
        o2.className = 'wrongdata';
        return false;
        }
    return res;
}

function fillCreateAnAccount()
{
    var o1 = findObject( 'email' );
    if( o1 )
        o1.value = getVal( 'semail' );
}

function toggleShippingOptions( which )
{
    var i1 = findObject( 'so_ground' );
    var i2 = findObject( 'so_express' );
    var i3 = findObject( 'so_nextday' );
    if( !i1 || !i2)
        return false;
    s1 = 'img/cb.gif'; s2 = s1; s3 = s1;
    sel = 'img/cbc.gif';
    switch( which ) {
        case 1:
            s1 = sel;
            break;
        case 2:
            s2 = sel;
            break;
        case 3:
            s3 = sel;
            break;
        }
    i1.src = s1; i2.src = s2; i3.src = s3;
    shippingOption = which;
    return false;
}

function selectCard( which )
{
    if( which == creditCardType )
        return false;
    var obj;
    creditCardType = which;
    return false;
}

function setSame( name1, name2 )
{
    var o1 = findObject( name1 );
    var o2 = findObject( name2 );
    if( o1 && o2 )
        o2.value = o1.value;
}

function toggleUseShippingInformation()
{
    var o = findObject( 'use_shipping' );
    if( !o )
        return false;
    useShippingInformation = !useShippingInformation;

    fillBillingInformation();

    if( useShippingInformation )
        o.src = 'img/cbc.gif';
    else
        o.src = 'img/cb.gif';
    return false;
}

function isEmpty( name )
{
    var o = findObject( name );
    if( !o )
        return false;
    if( o.value == '' )
        o.className = 'wrongdata';
    else
        o.className = 'txtinput';
    return ( o.value == '' );
}

function isComboEmpty( fieldName )
{
    var co = comboBox_getComboObj( fieldName );
    if( !co )
        return false;
    var ie = findObject( co.divID+'_ie' );
    if( !ie )
        return false;
    var cd = co.getData();
    if( cd == '' )
        ie.style.borderBottom = '1px solid #f00';
    else
        ie.style.borderBottom = '0px solid white';
    return ( cd == '' );
}

function validNumber( objName, minlen, len )
{
    var obj = findObject( objName );
    if( !obj )
        return false;
    if( obj.value.length < minlen )
        {
        obj.className = 'wrongdata';
        return false;
        }
    if( (len >0) && ( obj.value.length != len )  )
        {
        obj.className = 'wrongdata';
        return false;
        }
    for( i=0; i<obj.value.length; i++ )
        if( obj.value.charAt(i) < '0' || obj.value.charAt(i) > '9' )
            {
            obj.className = 'wrongdata';
            return false;
            }
    obj.className = 'txtinput';
    return true;
}

function validateShippingInformation()
{
    res = !isEmpty( 'sfname' );
    res &= !isEmpty( 'slname' );
    res &= !isEmpty( 'saddress1' );
    res &= !isEmpty( 'scity' );
    res &= !isComboEmpty( 'scountry' );
    	
	var country = getComboByIDVal('scountry_div');
	if (country == 'United States') {
       		if (isEmpty('sstate')) 
       	        return false;
       		res &= !isEmpty( 'szip' );
       	    if( !validNumber( 'szip', 5, 0 ) )
       	        return false;
    	}

    return res;
}

function fillBillingInformation()
{
    if( useShippingInformation )
        {
        setSame( 'sfname', 'bfname' );
        setSame( 'smi', 'bmi' );
        setSame( 'slname', 'blname' );
        setSame( 'saddress1', 'baddress1' );
        setSame( 'saddress2', 'baddress2' );
        setSame( 'scity', 'bcity' );
        setSame( 'sstate', 'bstate' );
        setSame( 'szip', 'bzip' );
        // setSame( 'scountry', 'bcountry' );
        setObjProp( 'bfname', 'disabled', 'true' );
        setObjProp( 'bmi', 'disabled', 'true' );
        setObjProp( 'blname', 'disabled', 'true' );
        setObjProp( 'baddress1', 'disabled', 'true' );
        setObjProp( 'baddress2', 'disabled', 'true' );
        setObjProp( 'bcity', 'disabled', 'true' );
        setObjProp( 'bstate', 'disabled', 'true' );
        setObjProp( 'bzip', 'disabled', 'true' );
        // setObjProp( 'bcountry', 'disabled', 'true' );
        var sc = getComboByID( 'scountry_div' );
        var bc = getComboByID( 'bcountry_div' );
        if( sc && bc )
            {
            bc.setData( sc.getData() );
            if( bc.droppedDown )
                {
                hideElem( bc.divID+'_ddc' );
                bc.droppedDown = true;
                }
            bc.enabled = false;
            }
        }
    else
        {
        setObjProp( 'bfname', 'disabled', 'false' );
        setObjProp( 'bmi', 'disabled', 'false' );
        setObjProp( 'blname', 'disabled', 'false' );
        setObjProp( 'baddress1', 'disabled', 'false' );
        setObjProp( 'baddress2', 'disabled', 'false' );
        setObjProp( 'bcity', 'disabled', 'false' );
        setObjProp( 'bstate', 'disabled', 'false' );
        setObjProp( 'bzip', 'disabled', 'false' );
        // setObjProp( 'bcountry', 'disabled', 'false' );
        var bc = getComboByID( 'bcountry_div' );
        if( bc )
            bc.enabled = true;
        }
}

function setObjProp( obj, prop, value )
{
    var o = findObject( obj );
    if( o )
        eval( 'o.'+prop+'='+value+';' );
}

function validateBillingInformation()
{
    res = !isEmpty( 'bfname' );
    res &= !isEmpty( 'blname' );
    res &= !isEmpty( 'baddress1' );
    res &= !isEmpty( 'bcity' );
    res &= !isComboEmpty( 'bcountry' );
    
	var country = getComboByIDVal('bcountry_div');
        if (country == 'United States') {
       		res &= !isEmpty( 'bzip' );
        		if (!validNumber( 'bzip', 5, 0 ))
        			return false;
        		if (isEmpty('bstate'))
                        return;
        }
	return res;
}


function makePayment()
{
    	var numLen = 16, civLen = 3; 
	
	if (creditCardType == 4) {
		numLen = 15;
		civLen = 4;
	} 
	res = creditCardType != 0;
	if( res ){
        	setObjProp( 'cctype_div', 'className', '"normaldata"' );
    	} else{
        	setObjProp( 'cctype_div', 'className', '"wrongdata_div"' );
    	}

	res &= !isEmpty( 'cardname' );
    	res &= !isEmpty( 'cardnumber' );
    	res &= !isEmpty( 'emonth' );
    	res &= !isEmpty( 'eyear' );
    	res &= !isEmpty( 'civ' );
    	res &= validNumber( 'cardnumber', numLen, numLen );
    	res &= validNumber( 'emonth', 2, 2 );
    	res &= validNumber( 'eyear', 2, 2 );
    	res &= validNumber( 'civ', civLen, civLen );
	if (res==1)
        	FPayment();
    	return res;
}

function signIn()
{
    FLogin();
}

function getVal( objName )
{
    var o = findObject( objName );
    if( o )
        return o.value;
    else
        return '';
}

function createAnAccount()
{
    loggedIn = true;
    userFirstName = getVal( 'fname' );
    userLastName = getVal( 'lname' );
    userMI = getVal( 'mi' );
    userAddress1 = getVal( 'address1' );
    userAddress2 = getVal( 'address2' );
    userCity = getVal( 'city' );
    userState = getVal( 'state' );
    userZip = getVal( 'zip' );
    userCountry = getVal( 'country' );
    nextPurchaseStep();
    //    AddField();
}

function fillShippingInformation()
{
    setObjProp( 'sfname', 'value', '"'+userFirstName+'"' );
    setObjProp( 'slname', 'value', '"'+userLastName+'"' );
    setObjProp( 'smi', 'value', '"'+userMI+'"' );
    setObjProp( 'saddress1', 'value', '"'+userAddress1+'"' );
    setObjProp( 'saddress2', 'value', '"'+userAddress2+'"' );
    setObjProp( 'scity', 'value', '"'+userCity+'"' );
    setObjProp( 'sstate', 'value', '"'+userState+'"' );
    setObjProp( 'szip', 'value', '"'+userZip+'"' );
    var cc = getComboByID( 'scountry_div' );
    if( cc )
        {
        cc.setData( userCountry );
        if( cc.selectedItem == -1 )
            hideElem( 'shipping_options' );
        }
    shippingPrice = 0; totalItems=0;
    old_shippingOption = shippingOption;
    for( i=0; i<scart.length; i++ )
        {
            totalItems += scart[i].quantity;
        }
    shippingOption=1;
    shippingPrice = calculateShippingPrice_Prev( totalItems );
    obj = findObject( 'shipp_ground' );
    if( obj )
        obj.innerHTML = showMoney( shippingPrice );
    shippingOption=2;
    shippingPrice = calculateShippingPrice_Prev( totalItems );
    obj = findObject( 'shipp_express' );
    if( obj )
        obj.innerHTML = showMoney( shippingPrice );
    shippingOption=3;
    shippingPrice = calculateShippingPrice_Prev( totalItems );
    obj = findObject( 'shipp_next' );
    if( obj )
        obj.innerHTML = showMoney( shippingPrice );
    shippingOption=old_shippingOption;
}

function calculateShippingPrice( itemsCount )
{
    var cb = comboBox_getComboObj( 'scountry' );
    var maxCount=4;
    if( !cb )
        return 0;
    baseRate = 0; perEach = 0;
    if( cb.getData() == 'United States' )
        {
        baseRate = usaShippingCosts[ shippingOption - 1 ].baseRate;
        perEach = usaShippingCosts[ shippingOption - 1 ].perEachRate;
        }
    else
        {
            if (cb.selectedItem!=-1)
                baseRate = shippingCosts[ cb.selectedItem ].baseRate;
        perEach = 0;//shippingCosts[ cb.selectedItem ].perEachRate;
        }
    if (itemsCount<5)
        maxCount=itemsCount-1;
    
	return baseRate + maxCount*perEach;
}


function calculateShippingPrice_Prev( itemsCount )
{
    var maxCount=4;
    baseRate = 0; perEach = 0;
    baseRate = usaShippingCosts[ shippingOption - 1 ].baseRate;
    perEach = usaShippingCosts[ shippingOption - 1 ].perEachRate;
    if (itemsCount<5)
        maxCount=itemsCount-1;
    
	return baseRate + maxCount*perEach;
}

function prepareSummaryPage()
{
    var sc = '<table class=sci width=460 cellpadding=0 cellspacing=0 border=0>';
    subtotalPrice = 0; shippingPrice = 0; totalItems = 0;
	var n_items;
	for( n_items=0; n_items<scart.length; n_items++ )
        {
        sc += '<tr><td width=20%>' + scart[n_items].model + '</td>';
        sc += '<td width=35%><img src=' + scart[n_items].image + ' width=100 height=60 border=0></td>';
        sc += '<td width=15%>' + scart[n_items].color + '</td>';
        sc += '<td width=15%>' + scart[n_items].quantity + '</td>';
        sc += '<td width=15%>' + showMoney( scart[n_items].price ) +'</td></tr>';
        subtotalPrice += scart[n_items].quantity*scart[n_items].price;
        //taxPrice += scart[n_items].quantity*0;
        totalItems += scart[n_items].quantity;
        }
    sc += '</table>';

    var obj = findObject( 'subtp' );
    if( obj )
        obj.innerHTML = showMoney( subtotalPrice );
    obj = findObject( 'taxp' );
    if( obj )
        obj.innerHTML = showMoney( taxPrice );

    shippingPrice = calculateShippingPrice( totalItems );
	shipp_cost = shippingPrice;
    obj = findObject( 'shipp' );
    if( obj )
        obj.innerHTML = showMoney( shippingPrice );

	totalSum = parseFloat(subtotalPrice) + 
		parseFloat(taxPrice) + parseFloat(shippingPrice);
    obj = findObject( 'ftp' );
    if( obj )
        obj.innerHTML = showMoney( totalSum );

    shipToStr = getVal('sfname')+' '+getVal('smi')+' '+getVal('slname')+'<br>';
    shipToStr += getVal('saddress1')+'<br>';
    a2 = getVal('saddress2');
    if( a2 != '' )
        shipToStr += a2+'<br>';
    shipToStr += getVal('scity')+' '+getVal('sstate')+' '+getVal('szip')+'<br>';
    shipToStr += getComboByIDVal('scountry_div');
    obj = findObject( 'shipto' );
    if( obj )
        obj.innerHTML = shipToStr;
    billToStr = getVal('bfname')+' '+getVal('bmi')+' '+getVal('blname')+'<br>';
    billToStr += getVal('baddress1')+'<br>';
    a2 = getVal('baddress2');
    if( a2 != '' )
        billToStr += a2+'<br>';
    billToStr += getVal('bcity')+' '+getVal('bstate')+' '+getVal('bzip')+'<br>';
    billToStr += getComboByIDVal('bcountry_div');
    obj = findObject( 'billto' );
    if( obj )
        obj.innerHTML = billToStr;

    obj = findObject( 'scs_slider' );
    if( obj )
        {
        obj.innerHTML = sc;
        obj.style.top = 0;
        }

    obj = findObject( 'scs_container' );
    if( !obj )
        return;

    if( n_items*63 > obj.offsetHeight )
        {
        var scrl = findObject( 'scsup' );
        if( scrl )
            {
            scrl.style.left = obj.offsetWidth-15;
            scrl.style.top = 25;
            }
        scrl = findObject( 'scsdn' );
        if( scrl )
            {
            scrl.style.left = obj.offsetWidth-15;
            scrl.style.top = obj.offsetHeight;
            }
        showElem( 'scsup' );
        showElem( 'scsdn' );
        }
    else
        {
        hideElem( 'scsup' );
        hideElem( 'scsdn' );
        }
}

function preparePaymentPage()
{
    var obj = findObject( 'paysum' );
    if( obj )
        obj.innerHTML = showMoney( totalSum );
}

function get_totalSum()
{
    return (totalSum);
}
function validateShoppingCart()
{
    return scart.length > 0;
}

function fmtTax(value) {
	var result = Math.floor(value) + ".";
	var cents = 100 * (value - Math.floor(value)) + .5;
	result += Math.floor(cents / 10);
	result += Math.floor(cents % 10);
	return result;
}
