// Copyright 2008-2011 South Side Health.org
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*************************
 NOTE:
 Carts are now called baskets in the UI.
 *************************/

var cartUtil = window.cartUtil = {
    showThrobber: function() {
        $('shopping-cart-pencil').hide();
        $('shopping-cart-pencil-minus').hide();
        $('shopping-cart-throbber').show();       
    },
    
    isEditMode: function() {
        $('shopping-cart-pencil-minus').visible();
    },
    
    addCart: function() {
        var cartName = $('cart_name').getValue();
        var isServiceView = $('is_service_view') ? true : false;
        
        $j.post('/carts/create', {
        	'data[cart_name]': cartName,
        	'data[isServiceView]': isServiceView
        	}, function(data) {
        		$j("#shopping-cart").html(data);	
        		
        		// If we're on a search results page
        		if ($j('#is_search_results').length) {
        		    // Make new basket a choice in "Add to Basket" popup
                    setTimeout(function() {
                        // Grab new basket's name and ID out of hidden form
                        // fields that were rendered with the AJAX-updated cart
                        // element. We use the timeout to wait a couple of browser
                        // ticks to ensure that the new elements are visible in the
                        // DOM.
                        newCartName = $j('#newCartName').attr('value');
                        newCartID = $j('#newCartID').attr('value');
                        
                        var newOption = $j('option', '#dest_cart').get(0);
                        newOption = $j(newOption).attr('value', newCartID);
                        newOption = newOption.text(newCartName);
                        newOption.appendTo('#dest_cart');
                    }, 30);
        		}
        	});
        
        cartUtil.showThrobber();
    },
    
    currentRequest: ""
};

/* Sends AJAX requests to expand/collapse basket */
cartUtil.sendRequest = function(id, expanded) {
        if (cartUtil.currentRequest != "") {
            cartUtil.currentRequest.abort();
        }
        cartUtil.currentRequest =
            $j.post('/carts/toggle/' + id,
                {'data[expanded]':expanded},
                function(data) { cartUtil.currentRequest = ""; });
};
/* Add a service to a cart */
cartUtil.addToCart = function(cartID, serviceID) {
        var isServiceView = ($j('#is_service_view').length > 0) ? true : false;
    
        new Ajax.Updater('shopping-cart', '/carts/add/'+serviceID, {
                method: 'post',
                parameters: {'data[cartID]': cartID,
                'data[isServiceView]': isServiceView } 
        });
        cartUtil.showThrobber();
}

/*****************************************************
 * All of the keypress events for the shopping cart
 ****************************************************/
/* New basket text field submits on 'Enter' keypress */
document.observe('keypress', function(event) {
        if (el = event.findElement('#cart_name')) {
               if (event.keyCode == Event.KEY_RETURN) {
                   cartUtil.addCart();
               }
        }
});


/************************************************
 * All of the click events for the shopping cart
 ***********************************************/
document.observe('click', function(event) {
        
    /* NOTE the wonky C-like syntax in the conditionals below.
     * It is correct. If findElement doesn't find anything,
     * it returns "undefined", which is false. Otherwise, we
     * save its result in the variable el & go into the if block.
     */
    
    /* Cart contents plus/minus toggle */
    if (el = event.findElement('.cart_header .plus_minus')) {
                // get cart name from span ID
                // <span id="toggle_{cartname}" class="plus_minus" />
                var cartID = (el.identify()).slice(7);
                
                if (el.hasClassName('minus')) {
                    // minus --> plus: slide up
                    el.removeClassName('minus');
                    el.addClassName('plus');
                    $$('div#cart_' + cartID).each(function(e) {
                        e.visualEffect('slide_up',
                        {duration:0.5}) });
                    // send signal to store collapse
                    cartUtil.sendRequest(cartID, 'false');
                } else {
                    // plus --> minus: slide down
                    el.removeClassName('plus');
                    el.addClassName('minus');
                    $$('div#cart_' + cartID).each(function(e) {
                        e.visualEffect('slide_down',
                        {duration:0.5}) });
                    // send signal to store expansion
                    cartUtil.sendRequest(cartID, 'true');
                }
    }
    
    /* Cart management mode */
    if (el = event.findElement('#edit_carts_icon')) {
        // Toggle edit mode UI
        var $$new_cart_form = $('new_cart_form');
        
        if (el.hasClassName('not_editing')) {
            
            // view mode --> edit mode
            el.removeClassName('not_editing');
            el.addClassName('editing');
            //     * place focus on new cart text box so user can start
            //       typing right away
            setTimeout(function(){ $('cart_name').focus(); }, 60);
            $$new_cart_form.visualEffect('slide_down',
                {duration: 0.5});
            $$('.delete_cart').each(function(el) {
                    
                    el.visualEffect('appear',
                        {duration: 0.5, from: 0.0, to: 1.0});
            });
            
        } else if (el.hasClassName('editing')) {
            // edit mode --> view mode
            el.removeClassName('editing');
            el.addClassName('not_editing');
            $$new_cart_form.visualEffect('slide_up',
                {duration: 0.3});
            $$('.delete_cart').each(function(el) {
                    el.visualEffect('fade',
                        {duration: 0.3, from: 1.0, to: 0.0});
            });
        }
    }
    
    /* Create cart */
    if (el = event.findElement('#new_cart_submit')) {
        cartUtil.addCart();
    }
    
    /* Delete cart */
    if (el = event.findElement('.delete_cart')) {
                    
        var cartName = el.readAttribute('cart_name');
        var msg = 'Are you sure you want to delete "' + cartName.trim() + '"?'; 
       
        var isServiceView = $('is_service_view') ? true : false;

        if (confirm(msg)) {
            // delete the cart
            
            // get cart name from ID
            var cartID = (el.identify()).slice(12);
            
            new Ajax.Updater('shopping-cart', '/carts/delete/'+cartID, {
                    method: 'post',
                    parameters: {'data[isServiceView]': isServiceView}
            });
            cartUtil.showThrobber();
            
        }
    }
    
    /* Add service to cart */
    if (el = event.findElement('.add_to_cart')) {
        
        if (!$('is_service_view')) { return; }

        var cartID = el.readAttribute('cart_id');
        var serviceID = $('is_service_view').readAttribute('value');
        var service = service = $j('#cart_' + cartID + '_service_' + serviceID);  // this will be empty unless the service is already in the basket
        
        // if service is already there, just flash its name so the user notices
        // otherwise, ajax call to the database etc.
        if (service.length) {
            currentColor = service.css('background-color');
            service.css('background-color', '#FFFF99');
            service.animate({backgroundColor: currentColor}, 1500);
        } else {
            cartUtil.addToCart(cartID, serviceID);
        }
    }
    
    /* Delete service from cart */
    if (el=event.findElement('.remove_from_cart')) {
        // TODO TODO TODO: confirm delete!!
        
        var serviceID = el.readAttribute('cart_has_service_id');        
        var isServiceView = $('is_service_view') ? true : false;
        
        new Ajax.Updater('shopping-cart', '/carts/remove/'+serviceID, {
                method: 'post',
                parameters: {'data[isServiceView]': isServiceView }
        });
        cartUtil.showThrobber();
    }
});


