if (typeof(BCNTRY) == 'undefined') {BCNTRY = {};}

var f = 'cart_form';
var saved_shipmode;
var cookies = true;
var nocookiesmessage = false;

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


// update shipping totals when a new shipping method is chosen in the preview
function update_shipping_totals(shipmode) {
    var shipping;
    if($('cost_' + shipmode)) {
        shipping = $('cost_' + shipmode).value;
        saved_shipmode = shipmode;
    } else if(document.checkout && document.checkout.mv_shipmode && document.checkout.mv_shipmode.value && $('cost_' + document.checkout.mv_shipmode.value)) {
        shipping = $('cost_' + document.checkout.mv_shipmode.value).value;
        saved_shipmode = document.checkout.mv_shipmode.value;    
    } else if(document.cart_form && document.cart_form.mv_shipmode && document.cart_form.mv_shipmode.value) {
        shipping = $('cost_' + document.cart_form.mv_shipmode.value).value;
        saved_shipmode = document.cart_form.mv_shipmode.value;
    } else {
        if($('cost_GNDRES')) {
            shipping = $('cost_GNDRES').value;
            saved_shipmode = 'GNDRES';
        } else {
            shipping = '$0.00';
            saved_shipmode = '';
        }
    }
    if($('mv_shipmode_' + saved_shipmode)) {
        $('mv_shipmode_' + saved_shipmode).checked = true;
        $('mv_shipmode_' + saved_shipmode).setAttribute('checked','checked');                                               
    }
        
    $('totals_shipping_large').innerHTML = shipping;
    if($('totals_shipping_small')) {
        $('totals_shipping_small').innerHTML = shipping;
    }
    var subtotal = $('totals_subtotal_large').innerHTML;
    var tax = $('totals_tax_large').innerHTML;
    var total_cost;
    shipping = shipping.replace(',', '');
    subtotal = subtotal.replace(',', '');
    tax = tax.replace(',', '');
    if(shipping == 'FREE!') {
        total_cost = parseFloat(subtotal.replace('$', '')) + parseFloat(tax.replace('$', ''));
    } else {
        total_cost = parseFloat(shipping.replace('$', '')) + parseFloat(subtotal.replace('$', '')) + parseFloat(tax.replace('$', ''));
    }
    total_cost = total_cost.toFixed(2);
    if($('totals_payment_large')) {
        var payment = $('totals_payment_large').innerHTML;
        var due = '$0.00';
        if(total_cost > parseFloat(payment.replace('$', ''))) {
            due = total_cost - parseFloat(payment.replace('$', ''));
            due = '$' + due.toFixed(2);
        }
        $('totals_due_large').innerHTML = due;
        if($('totals_due_small')) {
            $('totals_due_small').innerHTML = due;
        }
    }
    if(total_cost > 999.99) {
        total_cost = addCommas(total_cost);
    }
    $('totals_total_large').innerHTML = '$' + total_cost;
    if($('totals_total_small')) {
        $('totals_total_small').innerHTML = '$' + total_cost;
    }
    if(f == 'checkout') {
        update_payment_method();
    }

    if (cookies) {
        _setCookie('shipping_selection',saved_shipmode, '', '/');
    }
    return;
}

function add_shipping_message(inStr) {
    if (/shipping_message/.exec(inStr)){
        return inStr;
    }

    var outStr = inStr;
    var results = />time:(.+)</.exec(outStr);
    if (results === null) {
        return outStr;
    }
    var date = new Date(results[1]);
    var year = ' ' + date.getFullYear() + ' ';
    var cutDate = new Date(Date.parse('7 Dec' + year + '00:00:00 MST'));
    // By listing the sites as a property list, rather than an array,
    // I can use "in" to check for a match cleaner than a normal array
    var retailSites = { 'backcountry.com':'', 'hucknroll.com':'', 'backcountryoutlet.com':'',
                        'departmentofgoods.com':'', 'dogfunk.com':'', 'explore64.com':'',
                        'realcyclist.com':'' }
    if (date > cutDate && hostname in retailSites) {
        var holiday_msg = '<br /><div class="shipping_message">Guaranteed by Christmas</div>';
        var check = [
            { string: '>Standard (5-7 days)', date:'17 Dec', time: '15:00:00 MST'},
            { string: '>3-Day Shipping', date:'21 Dec', time: '15:00:00 MST'},
            { string: '>2-Day Shipping', date:'22 Dec', time: '15:00:00 MST'},
            { string: '>Next Day Shipping', date:'23 Dec', time: '15:00:00 MST'},
            { string: '>Economy (7-14 days)', date:'14 Dec', time: '15:00:00 MST'},
            { string: '>USPS Priority Mail', date:'18 Dec', time: '15:00:00 MST'}
        ];

        for( var i = 0; i < check.length; i++){
            var currentDate = new Date(Date.parse(check[i].date + year + check[i].time));
            if (currentDate > date) {
                outStr = outStr.replace(check[i].string, check[i].string + holiday_msg);
            }
        }
    }
    return outStr;

}

/**
 * Resize the mask over the shipping editing controls
 */
BCNTRY.reSizeShipAddressMask = function () {
    if ($('ship_address_mask')) {
        yd.setStyle('ship_address_mask','display','block');
        // set sizes for mask over editing shipping address
        if ($('combined_shipping_field') && $('cs_s_nickname_editing') && $('cs_ship_address_links')) {
            yd.setStyle('ship_address_mask','height',yd.getRegion('cs_s_nickname_editing').bottom - yd.getRegion('cs_ship_address_links').top+'px');
            yd.setStyle('ship_address_mask','width',yd.getRegion('combined_shipping_field').right - yd.getRegion('combined_shipping_field').left+'px');
        }
    }
};

/**
 * Make sure that the Combined Shipping radio is the default
 */
BCNTRY.setup_combined_shipping = function () {
    if ($('using_combined_shipping') && $('using_combined_shipping').value) {
        if (BCNTRY.defaultToCombinedShipping && $('combined_shipping_radio')) {
            $('combined_shipping_radio').checked = 'checked';
            BCNTRY.reSizeShipAddressMask();
        }
    }
};

function update_shipping_options(country, state) {
    var args = '';
    document.body.style.cursor = 'wait';
    if ($("zip_progress") !== null) {
        $("zip_progress").style.visibility = "visible";
    }
    
    if(document.cart_form && document.cart_form.cart_zip) {
        args = 'page=cart&zip='+document.cart_form.cart_zip.value;
        ScUpdateZip();
    }
    else if(document.checkout) {
        if(document.checkout.same_bill_address_yes && document.checkout.same_bill_address_yes.checked) {
            args = 'page=checkout&zip='+document.checkout.b_zip.value;
        } else if (document.checkout.same_bill_address_no && document.checkout.same_bill_address_no.checked) {
            args = 'page=checkout&zip='+document.checkout.zip.value;
        } else if (document.checkout.zip) {
            args = 'page=checkout&zip='+document.checkout.zip.value;
        }
    }
    if(state) {
        args += '&state='+state;
    }
    if(country) {
        args += '&country='+country; 
    }
    var div = 'shipping_options';
    if($(div)) {
        yc.delayedAsyncRequest(
            'GET',
            '/'+catalog+'/cart/ajax/update_shipping_options.html?'+args,
            {
                cache: false,
                success: function(r) {
                    var shipping_selections = add_shipping_message(r.responseText);
                    $(div).innerHTML = shipping_selections;
                    
                    //$(div).innerHTML = r.responseText;
                    if (saved_shipmode) {
                        update_shipping_totals(saved_shipmode);
                    }
                    else {
                        update_shipping_totals(_readCookie('shipping_selection'));
                    }
                    document.body.style.cursor = 'default';
                    if ($("zip_progress") !== null) {
                        $("zip_progress").style.visibility = "hidden";
                    }

                    // Update the cart totals
                    var args = '',
                        shipmode,
                        shipmodecookie = _readCookie('shipping_selection');

                    if(document.cart_form && document.cart_form.mv_shipmode) {
                        shipmode = document.cart_form.mv_shipmode.value;
                    }
                    else if (document.checkout && document.checkout.mv_shipmode) {
                        shipmode = document.checkout.mv_shipmode.value;
                    }
                    if(shipmode) { args = 'mv_shipmode=' + shipmode; }
                    else if (shipmodecookie) { args = 'mv_shipmode=' + shipmodecookie; }
                    yc.delayedAsyncRequest(
                        'GET',
                        '/' + catalog + '/cart/ajax/cart_totals.html',
                        {
                            cache: false,
                            success: function(r) {
                                var result = r.responseText;
                                $('large_cart_totals').innerHTML = result;
                                if($('small_cart_totals')) {
                                    $('small_cart_totals').innerHTML = result.replace(/_large/g, '_small');
                                }
                                
                                // Setup if using combined shipping
                                BCNTRY.setup_combined_shipping();
                                
                                // Combined Shipping won't be updated automatically
                                if ($('combined_shipping_radio') && $('combined_shipping_radio').checked) {
                                    update_shipping_totals('combined_shipping');
                                }
                            },
                            failure: function(r) { }, // No error, the cart totals just won't be accurate (no other way of getting it)
                            timeout: ajax_timeout
                        }
                    );
                },
                failure: function(r) { 
                    document.body.style.cursor = 'default';
                    if ($("zip_progress") !== null) {
                        $("zip_progress").style.visibility = "hidden";
                    }
                    $(div).innerHTML = '<p class="error_message">There was a problem getting the shipping options.  Please re-enter your zip code and try again.</p>';
                },
                timeout: ajax_timeout
        }
    );
    }
    if ((! cookiesEnabled()) && (! nocookiesmessage)) {
        alert('You appear to have cookies disabled. To be able to use our site properly, you need to enable cookies.');
        cookies = false;
        nocookiesmessage = true;
    }
    document.body.style.cursor = 'default';
    return;
}

BCNTRY.cart_page_init = function() {
    // if the zip_button exists set event listener objects for shipping costs preview, ignore tab key
    if($('zip_button')){
        ye.addListener('zip_button', 'click', function() { update_shipping_options(); } );
        var cart_zip_listener = new YAHOO.util.KeyListener('cart_zip', {keys:13}, function() { update_shipping_options(); });
        cart_zip_listener.enable();

        ye.addListener(document, 'keypress', function(e) {
            if((ye.getCharCode(e) == 13) && (ye.getTarget(e).id != 'input_box')) {}
        });
    }

    //this is to counteract safari's refusal to get the current view from the server
    var location_result = window.location.href.match('cart');
    if ((location_result !== null) &&
        (location_result.length > 0) &&
        (YAHOO.env.ua.webkit > 1)) {
        yc.delayedAsyncRequest(
            'POST', '/' + catalog + '/cart/ajax/check_cart_reload_needed.html',
            {
                success: function(r) {
                    if (r.responseText.substring(0,4) == 'true'){
                        window.location.href = '/' + catalog + '/cart.html' +
                            '?param=' + Math.floor(Math.random()*9999);
                    }
                },
                failure: function(r) { },
                timeout: ajax_timeout
            }, 'param=' + Math.floor(Math.random()*9999)
        );
    }

    var res_div = catalog + '_cart';
    if ($(res_div)) {
        var resonance_result = $(res_div).innerHTML;
        if((catalog == 'store' || catalog == 'dogfunk' || catalog == 'mountainbike' || catalog == 'roadbike') && resonance_result.match('item') && !resonance_result.match('NaN')) {
             yd.setStyle('resonance_box', 'display', 'block');
        }
    }

    //make sure the christmas message is set for shipping methods
    if (document.getElementById('shipping_methods')) {
           document.getElementById('shipping_methods').innerHTML = add_shipping_message(document.getElementById('shipping_methods').innerHTML);
    }
       
    if ($('combined_shipping_radio') && $('shipping_radios')) {
        BCNTRY.setup_combined_shipping();
        ye.addListener('shipping_radios','click',function() {BCNTRY.combinedShippingRadioChanged($('combined_shipping_radio'));});
        if ($('combined_shipping_radio').checked) {
            update_shipping_totals('combined_shipping');
        }
    }
    
    if ($('combinedShippingPopup') && $('what_is_this')) {
        ye.addListener('what_is_this','click',function(){
            show_hint('combinedShippingPopup'); 
            BCNTRY.ScWhatIsThisClicked();
        });
    }
    if ($('find_out')) {
        ye.addListener('find_out','click', BCNTRY.ScFindOutClicked);
    }
 
}

// reload the cart item list via ajax
function redraw_cart_items() {
    
    var args = 'cart_editable=';
    if(f == 'cart_form') {
        args += '1';
    }
    else {
        args += '0';
    }
   
    if($('large_cart_items')) {
        yc.delayedAsyncRequest(
            'POST', 
            '/' + catalog + '/cart/ajax/large_cart_items.html',
            {
                success: function(r) {
                    if ( $('cart_items_container') ) {
                        $('cart_items_container').innerHTML = r.responseText;
                    }
                    else {
                        $('large_cart_items').innerHTML = r.responseText;
                    }
                    // Combined Shipping is not factored into the response
                    if ($('combined_shipping_cost') && $('cost_combined_shipping')) {
                        var num_items = BCNTRY.getNumItems();
                        BCNTRY.reCalcCombinedShipping();
                        if (num_items < 1) {
                            BCNTRY.removeCombinedShipping();
                        }
                    }
                },
                failure: function(r) { }, // Nothing required if it fails
                timeout: ajax_timeout
            },
            args
        );
        update_shipping_options(); 
    } else {
        if($('large_cart_body')) {
            yc.delayedAsyncRequest(
                'POST',
                '/' + catalog + '/checkout/ajax/large_cart_body.html',
                {
                    success: function(r) { $('large_cart_body').innerHTML = r.responseText; },
                    failure: function(r) { }, // Nothing required if it fails
                    timeout: ajax_timeout
                },
                args
            );
            update_shipping_options();
            update_billing_shipping_display(); 
        }
        if($('small_cart_body')) {
            yc.delayedAsyncRequest(
                'POST',
                '/' + catalog + '/checkout/ajax/small_cart_body.html',
                {
                    success: function(r) { $('small_cart_body').innerHTML = r.responseText; },
                    failure: function(r) { }, // Not much we can do if it fails
                    timeout: ajax_timeout
                },
                args
            );
        }
    }
    
	
    if($('header_nitems')){
    	 yc.delayedAsyncRequest(
    	            'POST', 
    	            '/' + catalog + '/cart/ajax/cart_total_items.html',
    	            {
    	                success: function(r) {
    	                    if ( $('header_nitems') ) {
				var text = r.responseText.replace(new RegExp("[\\s]+$", "g"), "");
				if(text != '0'){
    	                        	$('header_nitems').innerHTML = '('+ text +')';
    	                    	}else{
				
    	                        	$('header_nitems').innerHTML = '';
				}
			}	
    	                  
    	                },
    	                failure: function(r) {}, // Nothing required if it fails
    	                timeout: ajax_timeout
    	            },
    	            args
    	        );
    }
    
    
    return;
}

// recalc and draw cart item list, free ship qualify notice, shipping mode cost preview (+ cart totals)
function redraw_all() {
    redraw_cart_items();
    return;
}

/**
 * Gets the number of items in the cart
 * @returns The number of items
 */
BCNTRY.getNumItems = function () {
    //get all options from 'line_items'. Total up if selected
    var total_items = 0;
    yd.getElementsBy(
        function (el) {
            return (el.selected === true);
        },
        'option',$('line_items'),
        function (el) {
            total_items += parseInt(el.value,10);
        }
    );
    
    return total_items;
};

/** 
 * Removes the combined shipping radio from the fieldset
 */
BCNTRY.removeCombinedShipping = function () {
    if ($('combined_shipping_radio')) {
        $('combined_shipping_options').selected = false;
    }
    if ($('combined_shipping_options')) {
        yd.setStyle('combined_shipping_options','display','none');
    }
    update_shipping_options();
    update_shipping_totals();
};

/** 
 * Recalculates the cost of combined shipping.  Called when the number of items
 * changes
 */
BCNTRY.reCalcCombinedShipping = function () {
     if ($('combined_shipping_cost') && $('cost_combined_shipping')) {
        var combined_shipping_total;
        var num_items = BCNTRY.getNumItems();
        
        if (BCNTRY.combined_shipping_costper == 'item') {
            combined_shipping_total = num_items * BCNTRY.combined_shipping_rate;
        }
        else if (BCNTRY.combined_shipping_costper == 'purchase') {
            combined_shipping_total = BCNTRY.combined_shipping_rate;
        }
        else {
            return;
        }
        $('combined_shipping_cost').innerHTML = combined_shipping_total;
        $('cost_combined_shipping').value = '$'+combined_shipping_total;
    }
};

// remove an item from the cart
function remove_from_cart(item_id, subitem_id,item_sku) {
    var args = 'item_id='+item_id+'&subitem_id='+subitem_id;
    document.body.style.cursor = 'wait';
    
    yc.delayedAsyncRequest(
        'POST',
        '/' + catalog + '/cart/ajax/remove_row.html',
        {
            success: function(r) {
                redraw_all();
                document.body.style.cursor = 'default';
            },
            failure: function(r) { 
                document.body.style.cursor = 'default';
                ajax_error(r, 'This item could not be removed from the cart.  Please reload the page and try again');
            },
            timeout: ajax_timeout
        },
        args
    );
    ScRemoveCartItem(item_sku);
    return;
}

// recalculate item row, remove if qty = 0
function recalculate_item(item_id, subitem_id, row_qty, item_sku) {
    if($(row_qty).value == '') {
        return;
    }
    document.body.style.cursor = 'wait';
    BCNTRY.reCalcCombinedShipping();

    if($(row_qty).value > 0) {
        yc.delayedAsyncRequest(
            'POST',
            '/' + catalog + '/cart/ajax/recalculate_item.html',
                {
                    success: function(r) { 
                        redraw_all();
                        document.body.style.cursor = 'default';
                    },
                    failure: function(r) {
                        document.body.style.cursor = 'default';
                        ajax_error(r, 'We could not recalulate your carts item at this time.  Please reload the page and try again');
                    },
                    timeout: ajax_timeout
                },
            'item_id=' + item_id + '&row_qty=' + $(row_qty).value + '&subitem_id='+ subitem_id
        );
        ScUpdateCartItem(item_sku);
    }
    else {
        // remove if qty = 0
        remove_from_cart(item_id, subitem_id, item_sku);
    }
    return;
}



// add gift box to cart and redraw
function add_gift_box(cart_id) {
    $('addgiftbox_'+cart_id).disabled = true;
    document.body.style.cursor = 'wait';

    yc.delayedAsyncRequest(
        'POST',
        '/' + catalog + '/cart/ajax/add_gift_box.html',
        {
            success: function(r) {
                redraw_all();
                document.body.style.cursor = 'default';
                var gift_sku = r.responseText.split("-",1);
                ScAddGiftOnCart(gift_sku);
            },
            failure: function(r) {
                document.body.style.cursor = 'default';
                ajax_error(r, 'The gift box could not be added.  Please reload the page and try again.');
            },
            timeout: ajax_timeout
        },
        'add_gift_box=' + cart_id
    );
    return;
}


/**
 * Called when a radio button in the fieldset containing the 'Combined Shipping'
 * radio button is changed.  Masks and unmasks Shipping address and updates
 * totals accordingly
 * @param {Element} el The radio button showing 'Combined Shipping'
 */
BCNTRY.combinedShippingRadioChanged = function (el) {
    
    if (!el) {
        return;
    }
    
    // If the Combined Shipping radio is checked
    if (el.checked) {
        BCNTRY.defaultToCombinedShipping = true;
        update_shipping_totals('combined_shipping');
        if ($('combined_shipping_note')) {
            yd.setStyle('combined_shipping_note','display','block');
        }
        if ($('shipping_field')) {
            yd.setStyle('shipping_field','display','none');
        }
        if ($('combined_shipping_field')) {
            yd.setStyle('combined_shipping_field','display','block');
        }
        BCNTRY.reSizeShipAddressMask();
    }
    else {
        BCNTRY.defaultToCombinedShipping = false;
        if ($('combined_shipping_note')) {
            yd.setStyle('combined_shipping_note','display','none');
        }
        if ($('combined_shipping_field')) {
            yd.setStyle('combined_shipping_field','display','none');
        }
        if ($('shipping_field')) {
            yd.setStyle('shipping_field','display','block');
        }
        if ($('ship_address_mask')) {
            yd.setStyle('ship_address_mask','display','none');
        }
    }
};



ye.onDOMReady(function() {
    BCNTRY.cart_page_init();
});
