var kCartProcessingUrl = "/product/cart_add";

function setup_product_comparison_controls(root_element) {
	this.max_selection_count = 5;
	this.selections = new Array();
	this.checkboxes = null;
	this.buttons = null;
	
	this.add = function(id) {
	    // Don't add if it's already in our list
	    for (var i=0; i<this.selections.length; i++) {
	        if (this.selections[i] == id)
	            return;
	    }
	    
	    this.selections.push(id);
	};
	
	this.remove = function(id) {
	    var new_array = new Array();
	    for (var i=0; i<this.selections.length; i++) {
	        if (this.selections[i] == id)
	            continue;
	        
	        new_array.push(this.selections[i])
	    }
	    
	    this.selections = new_array;
	};
	
	// Setup the requested element
    if (root_element == null)
        return;
    
    var _this = this;
    
    var checkbox_onclick_callback = function() {
        if (this.checked) {
            // Check to make sure we haven't reached our limit of items that may be compared
            if (_this.selections.length >= _this.max_selection_count) {
                this.checked = false;
                alert("Only " + _this.max_selection_count + " products may be compared at a time.");
                return;
            }
            
            _this.add(this.value);
            
            if (_this.selections.length == _this.max_selection_count) {
                for (var i=0; i<_this.checkboxes.length; i++) {
                    if (_this.checkboxes[i].checked == false)
                        _this.checkboxes[i].disabled = true;
                }
            }
        } else {
            _this.remove(this.value);
            
            for (var i=0; i<_this.checkboxes.length; i++) {
                if (_this.checkboxes[i].checked == false)
                    _this.checkboxes[i].disabled = false;
            }
        }
        
        if (_this.selections.length <= 0)
            _this.buttons.addClass("disabled");
        else
            _this.buttons.removeClass("disabled");
    };
    
    // Get reference to this table's associated submit button
    this.buttons = root_element.getElements("a.product-table-compare");
    this.form = root_element.getElement("form");
    
    this.buttons.addEvent("click", function() {
    	// Don't do anything if this button is currently disabled
    	if ($(this).hasClass("disabled"))
    		return false;
    	
    	// Submit form
    	if (_this.form != null)
	    	_this.form.submit();
	    
    	return false;
    });
    
    // Default compare button to disabled, as no checkboxes will be selected when this function is called
    if (this.buttons.length > 0)
        this.buttons.addClass("disabled");
    
    // Get an array of all rows within the body section of "product-table" elements
    this.checkboxes = root_element.getElements("tbody tr td.no_click input");
    
    for (var i=0; i<this.checkboxes.length; i++) {
        // Disable this checkbox; Firefox retains values on refresh which may goof things up
        this.checkboxes[i].checked = false;
        this.checkboxes[i].disabled = false;
        
        // Add click event callback
	    this.checkboxes[i].addEvent("click", checkbox_onclick_callback);
    }
}

function setup_request_sample_links(root_element, database) {
    var links;
    
    if (root_element == null)
    	links = $$("td.samples_link a");
    else
    	links = root_element.getElements("td.samples_link a");
    
    var click_callback = function() {
        var link = this;
        
        // Remove focus on this link
        this.blur();
        
        // Get ID from the link's HREF
        var id = this.href.split("#");
        if (id.length != 2)
            return false;
        id = id[1];
        
        // Send id to processing page
        var req = new Request({
            method: "post",
            url: kCartProcessingUrl,
            data: {"id": id},
            onFailure: function(xhr) {
                alert("Could not add item to your shopping cart.  Please try again later.");
            },
            onSuccess: function(responseText, responseXML) {
                // Check to see if the page returned an error
                var ok = true;
                responseText = responseText.trim();
                var colonIndex = responseText.indexOf(":");
                if (colonIndex < 0)
                    ok = false;
                else
                    ok = responseText.substring(0, colonIndex) == "ok";
                
                responseText = responseText.substring(colonIndex + 1, responseText.length);
                
                if (ok) {
                    // Flag item as having been added to the shopping cart
                    if (database != null) {
	                    // Find the product in the database matching this product's part number
	                    for (var i=0; i<database.db.map.length; i++) {
	                    	var product = database.db.map[i];
	                    	if (id == database.db.db[database.part_number_index][product[database.part_number_index]]) {
	                    		database.db.in_cart[i] = 1;
	                    		break;
	                    	}
	                    }
                    }
                    
                    // Update the product link to reflect that it's now in the cart
                    var parent = $(link.parentNode);
                    
                    // Fade in white overlay over the existing cell contents
                    var parent_size = parent.getSize();
                    var overlay = new Element("div", {
                    	"styles": {
                    		"position": "absolute",
                    		"top": "0px",
                    		"left": "0px",
                    		"width": parent_size.x,
                    		"height": parent_size.y,
                    		"background-color": "white",
                    		"opacity": "0.0",
                    		"z-index": "9000"
                    	}
                    });
                    
                    parent.grab(overlay);
                    var overlay_fx = new Fx.Tween(overlay, {
                    	property: "opacity",
                    	duration: 200,
                    	onComplete: function() {
                    		if (overlay.getStyle("opacity") == 1) {
                    			// Remove the link
                    			$(link).dispose();
                    			
                    			// Add our "in cart" message
                    			var span = new Element("span", {
                    				"class": "in_cart_message"
                    			}).appendText("In Cart");
                    			parent.grab(span, "top");
                    			
                    			// Fade out the overlay
                    			overlay_fx.start("1.0", "0.0");
                    		} else {
                    			// The animation is finished - remove the overlay from the DOM
                    			overlay.dispose();
                    		}
                    	}
                    }).start("0.0", "1.0");
                    
                    //// Update cart link display in the header
                    //num_items_in_cart++;
                    //var cart_header = $("cart_header");
                    //cart_header.empty();
                    //var cart_link = new Element("a", {
                    //    href: "/sample-cart"
                    //});
                    //cart_link.appendText(num_items_in_cart + " item" + (num_items_in_cart == 1 ? "" : "s") + " in cart");
                    //cart_header.grab(cart_link);
                } else {
                    alert("Could not add item to your shopping cart. Error: " + responseText);
                }
            },
            onComplete: function(response) {
                // Hide progress indicator
                // ...
            }
        }).send();
        
        return false;
    };
    
    // Add event callback to all samples links
    links.addEvent("click", click_callback);
};

window.addEvent('domready', function() {
    var table_containers = $$(".product_table_container_interior");
    
    for (var i=0; i<table_containers.length; i++)
        new setup_product_comparison_controls(table_containers[i]);
});
