jQuery.extend({
    fcAjax: function(url) {
        var settings = {};
                
        if (arguments.length == 2) {
            settings.type = 'POST';            
            settings.data = arguments[1];
        } else if (arguments.length == 3) {
            settings = arguments[2];
            settings.type = 'POST';            
            settings.data = arguments[1];
        } else {
            settings.type = 'GET';            
        }
        
        settings.url = url;
        settings.timeout = 60000;
        settings.cache = false;        
        
        if (settings.success == undefined) {
            settings.success = function(content) {
                $('div#first-choice-frame').html(content);
            };
        }
        
        settings.complete = function(jqXHR, textStatus) {
            jQuery('html').css('cursor', 'default');
            
            switch (textStatus) {
            case 'error':
            case 'timeout':
                fcAjaxRepeat();
                break;
            }
        };
        
        var fcAjaxRepeat = function() {
            jQuery('html').css('cursor', 'wait');        
            jQuery.ajax(settings);    
        }
        
        fcAjaxRepeat();
    }
});

$('div#first-choice-frame').ready(function() {
    $.fcAjax('/v/vspfiles/firstchoice-alt/products_available.asp');
});

var fcSetup = function(page) {
    var pagePath;
    switch (page) {
    case 'login':
        pagePath = 'div#first-choice-login';
        $(pagePath).ready(function() {
            $(pagePath + ' button#login').click(function(event) {
                var data = {team_id: $(pagePath + ' select#team_id').val(), password: $(pagePath + ' input#password').val()};
                
            	window.scrollTo(0, 0);
                $.fcAjax('/v/vspfiles/firstchoice-alt/login_action.asp', data);
            });
        });
        break;
    case 'rules':
        pagePath = 'div#first-choice-rules';
        $(pagePath).ready(function() {
            $(pagePath + ' button#accept').click(function(event) {
                $.fcAjax('/v/vspfiles/firstchoice-alt/rules_action.asp');
            	window.scrollTo(0, 0);
            });
            $(pagePath + ' button#decline').click(function(event) {
                jAlert("You must accept the terms in order to use the FIRST Choice Ordering system.");
                $.fcAjax('/v/vspfiles/firstchoice-alt/index.asp');
            });
        });
        break;
    case 'products':
        pagePath = 'div#first-choice-products';
        $(pagePath).ready(function() {
            // Basic functions for use.
            var setTotalCost = function() {
                $.fcAjax('/v/vspfiles/firstchoice-alt/get_session_info.asp', {}, {success: function(info_serialized) {
                    var info_array = info_serialized.split(";") 
                    var totalPrice = 0;
                    totalPrice = parseInt(info_array[2]);
                    
                    totalPrice += getTotalCost();
                    $(pagePath + ' label#total_cost').html(totalPrice);
                    var team_funds_now = $(pagePath + ' label#team_funds').html();
                    var finalPoints = parseInt(team_funds_now) - parseInt(totalPrice);
					
					if ( finalPoints <= 0 ) {
						$(pagePath + ' label#remaining_points').html(finalPoints).removeClass("remaining").addClass("remaining0");
					} else {
						$(pagePath + ' label#remaining_points').html(finalPoints).removeClass("remaining0").addClass("remaining");
					}
                }});
            };
    
            // get the total cost of the current user's choice of items
            var getTotalCost = function() {
                var total_price = 0;
                $(pagePath + ' tr.product').each(function() {
                    var product_code = $(this).find('div#product_code').html();
                    var quantity = $(pagePath + ' input#text' + product_code).val();
                    var price = $(pagePath + ' label#price' + product_code).html();
                    total_price += (quantity * price);
                });
                
                return parseInt(total_price);
            };

            // reset the form
            var resetQuantities = function() {
                $(pagePath + ' tr.product').each(function() {
                    var product_code = $(this).find('div#product_code').html();
                    var quantity = $(pagePath + ' input#text' + product_code).val(0);
                });
                $(pagePath + 'tr#totalCostDisplay > td#points > label').html(0);
            };
			
            var SoftAddItem = function(ProductCode, Qty, Post) {
                var ProductCodes = [];
                ProductCodes[0] = { ProductCode: ProductCode, Qty: Qty };
                
                // If it doesn't exist, create it.
                if (!displayCartPopup) {
                    displayCartPopup = new DisplayCartPopup();
                }

                // If the codes don't exist...
                var codeInterval = setInterval(function() {
                    if (displayCartPopup.AsyncAddCodes) { return; }
                    
                    clearInterval(codeInterval);
                    
                    displayCartPopup.AsyncAddCodes = Array();
                    
                    displayCartPopup.AsyncAddCodes.push(ProductCodes);
                    
                    if (Post) {
                        displayCartPopup.AsyncAddSingleItem(ProductCode, Post);
                    } else {
                        displayCartPopup.AsyncAddBegin();
                    }
                },
                2000);
                
                return false;
            };
            
            // continue checkout button mouse click event
            $(pagePath + ' button#checkout').click(function(event) {
                var total_price = 0;
                var current_points = $(pagePath + ' div label#team_funds').html();
                var continue_checkout = true;
				cartArray = Array();
				cartIndex = 0;

                // get the cost of items already in the cart
                $.fcAjax('/v/vspfiles/firstchoice-alt/get_session_info.asp', {}, {success: function(info_serialized) {
                        var info_array = info_serialized.split(';');
                        total_price = parseInt(info_array[2]);
                        
                        // get the cost of the items that the user wants to add to the cart
                        $(pagePath + ' tr.product').each(function() {
                            var product_code = $(this).find('div#product_code').html();
                            var quantity = $(pagePath + ' input#text' + product_code).val();
                            var price = $(pagePath + ' label#price' + product_code).html();
                            total_price += (quantity * price);
                        });

                        if (total_price > parseInt(current_points)) {
                            jAlert('The total Credits of your items is greater than your teams current FIRST Choice Credit balance. Please remove some items and try again.');
                            continue_checkout = false;
                            return;
                        }

                        if (total_price == 0) {
                            jAlert('The total Credits of items in your cart is zero. Please add a quantity to an item and try again.');
                            continue_checkout = false;
                            return;
                        }

						var cartArray = Array();
						var cartIndex = 0;
						
                        $(pagePath + ' tr.product').each(function() {
							var tempProductArray = Array();
                            var product_code = $(this).find('div#product_code').html();
                            var quantity = $(pagePath + ' input#text' + product_code).val();
                            var stock_status = $(pagePath + ' label#stock' + product_code).html();
                            var max_qty = $(pagePath + ' input#max_qty' + product_code).val();
                            var product_name = $(pagePath + ' u#name' + product_code).html();
                            quantity = parseInt(quantity);
                            if (quantity > 0) {
                                // check if we have enough in stock of that product
                                if (quantity > parseInt(stock_status) || parseInt(stock_status) <= 0) {
                                    jAlert("We don't have enough or we just ran out of product: " + product_code + ".  Please make sure the quantity desired is less than the amount we have in stock!");
                                    continue_checkout = false;
                                    //return;
                                }

                                if (quantity > parseInt(max_qty)) {
                                	jAlert("You have already reached the Max Available Selections for '" + product_name + "' this season.  Please reduce the quantity of this item from your order.");
                                    continue_checkout = false;
                                    //return;
                                }
                                
								//var post = 'QTY.' + product_code + '=' + quantity + '&ReplaceCartID=&ProductCode=' + product_code + '&e=&ReturnTo=&btnaddtocart.x=5&btnaddtocart.y=5';
								//SoftAddItem(product_code, quantity, post);
								
                                tempProductArray = { 'quantity' : parseInt(quantity),
													'stock_status' : parseInt(stock_status),
													'max_qty' : parseInt(max_qty),
													'product_name' : product_name,
													'product_code' : product_code
													};
													
								cartArray[cartIndex++] = tempProductArray; 
                            }
                        });

						if (!continue_checkout) {
                            return;
                        }
						
						for ( var i=0 ; i<cartIndex ; i++ ) {
							
							var temp_product = cartArray[i];
							
							if ( temp_product['max_qty'] > 0 ) {
								$(pagePath + ' label#purchases_left' + temp_product['product_code']).html(temp_product['max_qty']-temp_product['quantity']);
							}

							var post = 'QTY.' + temp_product['product_code'] + '=' + temp_product['quantity'] + '&ReplaceCartID=&ProductCode=' + temp_product['product_code'] + '&e=&ReturnTo=&btnaddtocart.x=5&btnaddtocart.y=5';
							SoftAddItem(temp_product['product_code'], temp_product['quantity'], post);
							
							
						}
						
						resetQuantities();

                        var data = {total_cost_fc: total_price};

                        $.fcAjax('/v/vspfiles/firstchoice-alt/set_session_cost.asp', data, {success: function() { ; }});
					}
                });
            });

            // Show the total amount of points used when a user adds a product
            $(pagePath + ' input.quantity').keypress(function(event) {
                setTotalCost();
            });

            // logout button mouse click event
            $(pagePath + ' button#logout').click(function() {
                $.fcAjax('/v/vspfiles/firstchoice-alt/logout_action.asp');
            	window.scrollTo(0, 0);
            });
            
            $(pagePath + ' button#view-cart').click(function() {
                window.open('/shoppingcart.asp', '_top');
            });
            
            // make sure the total reflects what is actually shown
            setTotalCost();
        });
        break;
    }
};

