/** Define a 'class' which will hold references to selected options */

/**
 * Constructor: this gets given a list of all filter options, so that it
 * knows when to user has specified the required options
 */
function OptionState (opt_keys) {
    /** A list of option keys, which map to odyssey content type field and the forms */
    this.option_keys = opt_keys;
    /** User selected (and validated) options live in here */
    this.stack = [];

    /** A callback function which the designers can use to run their code once an option changes */
    this.onSuccess = null;
    /** This is set to the instance_id of the last product which was selected */
    this.targetProduct = null;
}

OptionState.prototype.addOptionSelection = function (name, value) {
    if (this.stack) {
        for (var i = 0; i < this.stack.length; i++) {
            if (this.stack[i][0] == name) {
                if (value) {
                    this.stack[i][1] = value;
                }
                else {
                    this.stack.splice(i);
                }
                return;
            }
        }
        //Create this option
        if (value) {
            this.stack.push([name, value]);
        }
    }
    else if (value) {
        this.stack = [];
        this.stack.push([name, value]);
    }
}

/**
 * Get the currently selected option's value for the given group, field
 */
OptionState.prototype.getOptionValue = function(field) {
console.log(this.stack);
    var ret = false;
    if (this.stack) {
        for (var i = 0; i < this.stack.length; i++) {
            if (this.stack[i][0] == field) {
                return this.stack[i][1];
            }
        }
    }
    return ret;
}



OptionState.prototype.getURLQueryString = function(field, value) {
    var ret = "";
    if (this.stack) {
        for (var i = 0; i < this.stack.length; i++) {
            if (this.stack[i][0] == field) {
                continue;
            }
            ret += this.stack[i][0] + "=" + this.stack[i][1] + "&";
        }
    }
    return ret + field + "=" + escape(value);
}

/**
 * Checks whether the options on the given group are all set to something sensible.
 */
OptionState.prototype.checkAllOptionsSelected = function (form) {
    var ret = this.isReadyToPost();
    if (ret) {
        this.setProductFormField(form);
    }
    else {
        alert("Please select all of the options first!");
    }
    return ret;
}

/** Convenience: tell the caller if all my options are set yet. */
OptionState.prototype.isReadyToPost = function () {
    if (this.stack) {
        for (var i = 0; i < this.option_keys.length; i++) {
            found = false;
            for (var j = 0; j < this.stack.length; j++) {
                if (this.stack[j][0] == this.option_keys[i]) {
                    found = true;
                    break;
                }
            }
            if (! found) {
                return false;
            }
        }
    }
    else {
        return false;
    }
    return true;
}


/**
 * Adds a hidden instance_id form field to form prior to submitting.
 */
OptionState.prototype.setProductFormField = function (form) {
    var hf = document.createElement('input');
    hf.type = 'hidden';
    hf.name = 'instance_id';
    hf.value = this.targetProduct;
    form.appendChild(hf);
}

/**
 * Handler function for the drop-downs.
 */
OptionState.prototype.checkSelectedOptionCombination = function (node_url, fld, select) {
    var field_val = select.options[select.selectedIndex].value;
    if (! field_val) {
        this.addOptionSelection(fld, field_val);
        return;
    }
    //Sneaky closure!
    var SELF = this;
    ajr = new XHR({
        method : 'get',
        onRequest:function() {
            // DANNY: On request add the class to the ajax-loading div and empty the message.
            document.getElementById('ajx_status').className='ajax_working';
            document.getElementById('inl_msg').innerHTML="&nbsp;";
	    document.getElementById('inl_msg').className='';
	    document.getElementById('inl_msg').className='';

        },
        onFailure:function() {
            // DANNY: On failure remove the class to the ajax-loading div and empty the message.
            document.getElementById('ajx_status').className='';
            document.getElementById('inl_msg').innerHTML="Unable to check availability - Network Connected?";
	    	document.getElementById('inl_msg').className="m_error";

        },
        onSuccess : function () {
						
            // DANNY: On success remove the class to the ajax-loading div and empty the message.
            document.getElementById('ajx_status').className='';
            document.getElementById('inl_msg').innerHTML="&nbsp;";
			document.getElementById('inl_msg').className='';

	    if (this.response.xml.getElementsByTagName('result').length == 0) {
				result = false;
	    }
	    else {
        result = this.response.xml.getElementsByTagName('result').item(0).childNodes.item(0).nodeValue;
	    }

            if (result == 'false' || parseInt(result) == 'NaN') {

                document.getElementById('inl_msg').innerHTML="&nbsp;";
				document.getElementById('inl_msg').className="m_error";
		
                old_val = SELF.getOptionValue(fld);
                if (old_val == false) {
                    old_val = '';
                }
                for (var i = 0; i < select.options.length; i++) {
                    if (select.options.item(i).value == old_val) {
                        select.options.item(i).selected = true;
                        return;
                    }
                }
            }
            else {

		document.getElementById('inl_msg').innerHTML="&nbsp;";
		document.getElementById('inl_msg').className="m_ok";

                SELF.addOptionSelection(fld, field_val);
                
                SELF.targetProduct = this.response.xml.getElementsByTagName('instance_id').item(0).childNodes.item(0).nodeValue;
                
                if (SELF.onSuccess != null) {
                    SELF.onSuccess(this.response.xml);
                }
            }
        }
    });
    ajr.send(node_url, this.getURLQueryString(fld, field_val));
}
