Number.extend({
	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';

		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + '');
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	},
	formatMoney : function(c, d, t){
		var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
		return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
	}
});

function SelectAll(t) {
	for(var i=0;i<t.length;i++)
		t[i].checked = t[0].checked;
	//t[0].checked = 0
}

var Mayflex = {
    configure: function() {
        new SmoothScroll();

        var section = 0;
        var repsect = -1;

        if ($("products")) {
            $("products").getElements("ul").each(function(el, index) {
                if (el.hasClass("open")) {
                    section = index;
                }
            });
        }

        if ($("replist")) {
            $("replist").getElements("div").each(function(el, index) {
                if (el.hasClass("open")) {
                    repsect = index;
                }
            });
        }

        new Accordion($$("#products li span"), $$("#products li ul"), { "alwaysHide": true, "show": section });
        new Accordion($$("#faqlist li strong"), $$("#faqlist li div"));
        new Accordion($$("#serviceslist li strong"), $$("#serviceslist li div"));
        new Accordion($$("#accountpage li strong"), $$("#accountpage li div.memberentry"));
        new Accordion($$("#replist li strong"), $$("#replist li div"), { "alwaysHide": true, "show": repsect });
        new Accordion($$("#literaturelist div h2"), $$("#literaturelist div ul"));
        new Accordion($$(".addNote"), $$(".note"), { "alwaysHide": true, "show": -1 });

        $$(".volatile").each(function(el) {
            $(el).addEvent("focus", function() {
                if (this.getValue() == this.getProperty("title")) {
                    this.value = "";
                }
            });
        });

        $$("a[rel*='external']").each(function(a) {
            $(a).setProperty("target", "_blank");
        });

        $$("input.textfieldcolourpicker").each(function(el) {
            var v = el.getValue();
            if (v.length == 0) v = "#ffffff";
            el.value = v;
            new MooRainbow('sxColourPicker_' + el.id, {
                'id': 'moo' + el.id,
                'imgPath': '/_images/mooRainbow/',
                'startColor': new Color(v),
                'onChange': function(color) {
                    el.value = color.hex;
                    el.fireEvent("change");
                }
            });
        });

    },

    formCheckboxSelected: function(formID) {
        var returnVal = false;
        if ($(formID)) {
            $(formID).getElements("input[type=checkbox]").each(function(cb) {
                if (cb.getValue()) {
                    returnVal = true;
                }
            });
        }
        return returnVal;
    },

    getSelectedProductIDs: function(formID) {
        var productIDs = [];
        $(formID).getElements("input[type=checkbox]").each(function(cb) {
            var id = cb.getValue();
            if (id) {
                productIDs.push(id);
            }
        });
        return productIDs;
    },

    ProductOptionPricesLoader: {
        init: function() {
            url = '/_colony/product-directory/ajax-prices.asp';
            productid = $('options_purchase_form').getElements('table')[0].id;

            new Ajax(url, {
                "encoding": "ISO-8859-1",
                "data": Object.toQueryString({ ProductID: productid }),
                "onTimeout": function() {

                },
                "onFailure": function() {

                },
                "onComplete": function(response) {
                    var jsonObj = Json.evaluate(response);

                    jsonObj.productoptions.each(function(productoption) {
                        var productoptionrow = $(productoption.productoptionid);

                        if (productoptionrow) {
                            
                            Mayflex.ProductOptionPricesLoader.updatePrice(productoption, productoptionrow);
                            Mayflex.ProductOptionPricesLoader.updateInStock(productoption, productoptionrow);

                            if (!(productoptionrow.hasClass("displayonly"))) {
                            	Mayflex.ProductOptionPricesLoader.updateQty(productoption, productoptionrow);
                            	Mayflex.ProductOptionPricesLoader.updateSubTotal(productoption, productoptionrow);
                            	Mayflex.ProductOptionPricesLoader.updateSelect(productoption, productoptionrow);
                                Mayflex.ProductOptionPricesLoader.attachProductOptionEvents(productoption, productoptionrow);
                            }
                        }
                    });
                }
            }).request();
        },

        updatePrice: function(productoption, productoptionrow) {

            // Select cell element to update
            var cell = productoptionrow.getElement(".productoption_price");
            var currencyCell = productoptionrow.getElement(".productoption_currency");
            var priceCell = cell.getElement("input[type=hidden]");

            // Select cell loading icon element
            var cellLoading = cell.getElement(".loading");

            //Create new element to insert into cell
            var element = new Element('img', {
                'src': '/_images/buttons/telephone.gif',
                'alt': 'Call Us'
            });

            //Update cell element with new value
            if (productoption.price > 0) {
                cellLoading.remove();
                cell.appendText(currencyCell.getText() + parseFloat(productoption.price).formatMoney(2, ".", ","));
                priceCell.value = parseFloat(productoption.price)
            }
            else {
                cellLoading.replaceWith(element);
            }

        },
        updateQty: function(productoption, productoptionrow) {

            // Select cell element to update
            var cell = productoptionrow.getElement(".productoption_quantity");
            var currencyCell = productoptionrow.getElement(".productoption_currency");

            // Select cell loading icon element
            var cellLoading = cell.getElement(".loading");

            //Create new element to insert into cell
            var element = document.createElement("input");
            element.setAttribute("type", "text");
            element.setAttribute("value", "1");
            element.setAttribute("name", "ProductOptionQuantity_" + productoption.productoptionid);
            element.setAttribute("maxlength", "4");
            element.setAttribute("styles", "width:50px;");

            //Update cell element with new value
            if (productoption.price > 0) {
                cellLoading.replaceWith(element);
            }
            else {
                cellLoading.remove();
                cell.appendText('-');
            }

        },
        updateSubTotal: function(productoption, productoptionrow) {

            // Select cell element to update
            var cell = productoptionrow.getElement(".productoption_subtotal");
            var currencyCell = productoptionrow.getElement(".productoption_currency");

            // Select cell loading icon element
            var cellLoading = cell.getElement(".loading");

            //Update cell element with new value
            if (productoption.price > 0) {
                cellLoading.remove();
                cell.appendText(currencyCell.getText() + parseFloat(productoption.price).formatMoney(2, ".", ","));
            }
            else {
                cellLoading.remove();
                cell.appendText('-');
            }

        },
        updateInStock: function(productoption, productoptionrow) {

            // Select cell element to update
            var cell = productoptionrow.getElement(".productoption_stock");

            // Select cell loading icon element
            var cellLoading = cell.getElement(".loading");

            //Create new element to insert into cell
            var element = document.createElement("img");
            element.setAttribute("src", "/_images/icons/tick.gif");
            element.setAttribute("class", "tick");
            element.setAttribute("style", "display:inline;");
            
            var outOfStockElement = cell.getElement(".telephone");

            //Update cell element with new value
            if (productoption.stocklevel > 0) {
                cellLoading.replaceWith(element);
            }
            else {
                cellLoading.remove();
                outOfStockElement.setStyle('display', 'inline')
            }

        },
        updateSelect: function(productoption, productoptionrow) {

            // Select cell element to update
            var cell = productoptionrow.getElement(".productoption_select");

            // Select cell loading icon element
            var cellLoading = cell.getElement(".loading");

            //Create new element to insert into cell
            var element = document.createElement("input");
            element.setAttribute("type", "checkbox");
            element.setAttribute("value", productoption.productoptionid);
            element.setAttribute("name", "SelectedProductOptionIDs");

            //Update cell element with new value

            if (productoption.price > 0) {
                cellLoading.replaceWith(element);
            }
            else {
                cellLoading.remove();
                cell.appendText('-')
            }

        },
        attachProductOptionEvents: function(productoption, row) {
            var currency = row.getElement(".productoption_currency").getText();
            var price = productoption.price;
            var subTotal = row.getElement(".productoption_subtotal");
            var qtyEl = row.getElement("input[type=text]");

            var qtyStock = productoption.stocklevel;

            if (qtyEl) {
                qtyEl.addEvent("change", function() {
                    if (currency == "€")
                        subTotal.setHTML((this.getValue() * price).formatMoney(2, ",", ".") + currency);
                    else
                        subTotal.setHTML(currency + (this.getValue() * price).formatMoney(2));

                    var val = this.getValue().toInt();

                    if (isNaN(val) || val < 1) this.value = 1;

                    //alert(this.getValue());
                    //alert(qtyStock.getValue());
                    if (parseInt(this.getValue()) > parseInt(qtyStock)) {
                        row.getElement(".tick").setStyle("display", "none");
                        row.getElement(".telephone").setStyle("display", "inline");
                    } else {
                        row.getElement(".telephone").setStyle("display", "none");
                        row.getElement(".tick").setStyle("display", "inline");
                    }

                });
            }
        }

    }
};

window.addEvent("domready", function() {

    Mayflex.configure();

    if ($("planninglist_form")) {
        $("addtobasket_fromplanninglist").addEvent("click", function(e) {
            new Event(e).stop();

            if (Mayflex.formCheckboxSelected("planninglist_form")) {
                new Element("input", { "name": "AddToBasket", "type": "hidden", "value": "x=0,y=0" }).injectInside($("planninglist_form"));
                $("planninglist_form").submit();
            } else {
                alert("You must select at least one product before adding.");
            }
        });
    }

    if ($("basketform")) {
        if ($("SubmitOrder")) {
            $("SubmitOrder").addEvent("click", function(e) {
                $("SubmitOrder").setStyle("display", "none");
                $("SubmitOrderLoading").setStyle("display", "inline");
            });
        }
    }

    if ($("addtoplanning_frombasket")) {
        $("addtoplanning_frombasket").addEvent("click", function(e) {
            new Event(e).stop();

            if (Mayflex.formCheckboxSelected("basketform")) {
                $("basketform").action = "/planning-lists/addto/";
                $("basketform").submit();
            } else {
                alert("You must select at least one product before adding to the planning list.");
            }
        });
    }

    if ($("options_purchase_form")) {
        $("options_purchase_form").addEvent("submit", function(e) {
            if (!Mayflex.formCheckboxSelected("options_purchase_form")) {
                new Event(e).stop();
                alert("You must select at least one product before adding.");
            }
        });

        Mayflex.ProductOptionPricesLoader.init();
    }

    if ($("options_filter_form")) {
        new Element("input", {
            "type": "hidden",
            "name": "ajax_filter",
            "value": "true"
        }).injectInside("options_filter_form");

        $("option_filter_submit").setStyles({
            "display": "none",
            "visibility": "hidden"
        });

        $("options_filter_form").getElements("select").each(function(sb) {
            sb.addEvent("change", function() {
                new Ajax(window.location.href, {
                    "method": "post",
                    "data": $("options_filter_form"),
                    "update": $("options_purchase_form"),
                    "onComplete": function() {
                        //Mayflex.attachProductOptionEvents();
                        Mayflex.ProductOptionPricesLoader.init();
                    },
                    "onFailure": function() {
                        $("options_purchase_form").setHTML("<p>Unable to retrieve filtered results, please try again</p>");
                    }
                }).request();
            });
        });
    }

    Lightbox.init();

});

window.addEvent("load", function(){
	new Ticker($("ticker"), {interval: 5000});
});

