if (typeof CCHQ == "undefined") {var CCHQ = {};}

CCHQ.SimpleSeo = {};
CCHQ.SimpleSeo.form = {};
CCHQ.SimpleSeo.metaDesc = {};
CCHQ.SimpleSeo.metaKey = {};
CCHQ.SimpleSeo.buttonText = {};
CCHQ.SimpleSeo.url = {};
CCHQ.SimpleSeo.callPlugin = {};

CCHQ.SimpleSeo.init = function(elementId, metaDescName, metaKeyName, buttonText, url, pluginFunction) {
    this.metaDesc = metaDescName;
    this.metaKey = metaKeyName;
    this.buttonText = buttonText;
    this.url = url;
    this.callPlugin = pluginFunction;
    YAHOO.util.Event.onAvailable(elementId, this.setSeoButton, this);
}

CCHQ.SimpleSeo.setSeoButton = function(that) {
    var elements = this.getElementsByTagName('input');
    for(var i=0;i<elements.length;i++) {
        if(elements[i].type.toUpperCase() == 'BUTTON') {
            elements[i].setAttribute('onclick', 'CCHQ.SimpleSeo.getMetaData();');
            elements[i].setAttribute('value', that.buttonText);
            elements[i].parentNode.innerHTML += '';
        }
    }
    that.form = this;
    while(that.form.tagName.toUpperCase() != 'FORM'){
        that.form = that.form.parentNode;
    }
}

CCHQ.SimpleSeo.getMetaData = function() {
    this.callPlugin();
    YAHOO.util.Connect.setForm(this.form);
    YAHOO.util.Connect.asyncRequest('POST', this.url, this.callback, this);
}

CCHQ.SimpleSeo.processRequest = function(o) {
    var context = eval( '(' + o.responseText + ')' );
    this.setMetaData(this.metaDesc, context.ResultSet.Result.join(' and '));
    this.setMetaData(this.metaKey, context.ResultSet.Result.join(', '));
}

CCHQ.SimpleSeo.processFailure = function(o) {
    alert('Simple SEO Error...');
}

CCHQ.SimpleSeo.setMetaKey = function(value) {
    this.setMetaData(this.metaKey, value);
}

CCHQ.SimpleSeo.setMetaData = function(name, value) {
    var elements = document.getElementsByName(name);
    for(var i=0;i<elements.length;i++) {
        elements[i].value = value;
    }
}

CCHQ.SimpleSeo.callback = {};
CCHQ.SimpleSeo.callback.scope = CCHQ.SimpleSeo;
CCHQ.SimpleSeo.callback.success = CCHQ.SimpleSeo.processRequest;
CCHQ.SimpleSeo.callback.failure = CCHQ.SimpleSeo.processFailure;
