// see http://robertnyman.com/2008/05/13/how-to-hide-and-show-initial-content-depending-on-whether-javascript-support-is-available/
// for the purpose and description of this anonymous function
(function () {
    var head = document.getElementsByTagName("head")[0];
    if (head) {
        var scriptStyles = document.createElement("link");
        scriptStyles.rel = "stylesheet";
        scriptStyles.type = "text/css";
        scriptStyles.href = "http://" + window.location.hostname + "/css/script-styles.css";
        head.appendChild(scriptStyles);
    }
}());

var TheDrugCompanyUtil = Class.create(
{
    /**
     * Replaces a text element (via an Ajax call to /index/getprovincestates/) with a select element that contains
     * Canadian provinces -or- American states and vice versa
     *
     * @param section (string)
     * the name of the section (i.e. page) that is using this function
     * e.g. billing, signUp, shipping, etc.
     *
     * @return
     * the html fragment that is to be inserted. If province/states this will be a select element, otherwise it will
     * be an empty text element
     *
     * NOTE:
     * in order to use this function your html must contain the following attributes of the form:
     * text = <input type = "text" name = "^Section^ProvinceState" id = "^section^ProvinceState" ...>
     * select = <select name = "^Section^ProvinceState" id = "^section^ProvinceState" ...>
     */
    loadProvinceStates: function(section)
    {
        // name elements are capatalized, id elements are not
        // courtesy of: http://stackoverflow.com/questions/1026069/capitalize-first-letter-of-string-in-javascript
        var nameOfSection = section.substr(0, 1).toUpperCase() + section.substr(1);
        var idOfSection = section;

        var country = $(idOfSection + 'Country').value;

        var options = {
            parameters: { iso3 : country },
            method: 'post',
            onComplete: function(obj) {
                var html = '';

                var response = obj.responseText.evalJSON(true);
                var results = $H(response).get('results');
                var areStatesReturned = results != '';

                // if there's stuff that's returned rebuild the html select element for states with values
                // returned from our ajax call
                if (areStatesReturned)
                {
                    html = '<select name = "' + nameOfSection + 'ProvinceState" id = "' + idOfSection + 'ProvinceState" class="province ' + idOfSection + 'Element">';

                    var states = $H(results);
                    states.each(function(state) {
                        html += '<option value="' + state.key + '" label="' + state.value + '">' + state.value + '</option>';
                    }.bind(this));

                    html += '</select>';
                }

                // otherwise build an empty text box
                else
                    html = '<input type="text" name = "' + nameOfSection + 'ProvinceState" id = "' + idOfSection + 'ProvinceState" class="postalCode ' + idOfSection + 'Element" value = "">';

                // update the sucker...
                Element.update(idOfSection + 'ProvinceStateBlock', html);
            }.bind(this)
        };

        new Ajax.Request('/index/getprovincestates/', options);
    },


    /**
     * Removes a values from a select element
     *
     * @param id (string)
     * the id of the select element
     *
     * @param value (string)
     * the value to be removed from the select element
     */
    removeValueFromSelectElement: function(id, value)
    {
        var matchingElement = $(id).select('[value="' + value + '"]');

        if (matchingElement.length > 0)
            matchingElement[0].remove();
    }
});

var theDrugCompanyUtil = new TheDrugCompanyUtil();

document.observe('dom:loaded', function()
{
    // prevent 'double submit button clicking'
    $$("form").each(function(form) {
        form.observe(
            'submit',
            function() { $$("input[type='submit']").each(function(submitButton) {
                // * cart page has three submit buttons to the form
                // * the cart controller has to detect which one of the three buttons was submitted (by inspecting the
                // request params) and take the appropriate action
                // * however if the submit button is disabled it is not passed in with the request params, so disable
                // submit button iff submit button doesn't have the following names
                // * a 'cleaner' fix would be to remove those three submit buttons from the cart form but alas...
                if (submitButton.name !=='ContinueShopping' &&
                    submitButton.name !== 'UpdateCart' &&
                    submitButton.name !== 'ProceedToCheckout')
                    submitButton.disable();
            })}
        );
    }.bind(this));
});

