var WIDGETBOX = WIDGETBOX || {};

WIDGETBOX.CustomSettings = {
    onloadFn : null,
    syncFn : null,
    origForm : null,
    currentSessionId: "",

    getWidget: function() {
        detailsPageGetWidget();
    },
    getAppInstId : function() {
        var idField = document.getElementById("appInstance.appInstanceId");
        return (idField) ? idField.value : null;
    },
    getAppName : function() {
        var nameField = document.getElementById("appInstance.instanceName");
        return (nameField) ? nameField.value : 0;
    },
    setAppName : function(val) {
        var nameField = document.getElementById("appInstance.instanceName");
        if (nameField) nameField.value = val;
    },
    getAppWidth : function() {
        var widthField = document.getElementById("appInstance.width");
        return (widthField) ? widthField.value : 0;
    },
    setAppWidth : function(val) {
        var widthField = document.getElementById("appInstance.width");
        if (widthField) widthField.value = val;
    },
    getAppHeight : function() {
        var heightField = document.getElementById("appInstance.height");
        return (heightField) ? heightField.value : 0;
    },
    setAppHeight : function(val) {
        var heightField = document.getElementById("appInstance.height");
        if (heightField) heightField.value = val;
    },

    getParamValue : function(paramName) {
        var fieldId = "configValues['" + paramName + "']";
        return WIDGETBOX.CustomSettings.utils.getParamValueById(fieldId);
    },
    setParamValue : function(paramName, paramValue) {
        var fieldId = "configValues['" + paramName + "']";
        WIDGETBOX.CustomSettings.utils.setParamValueById(fieldId, paramValue);
    },

    refreshPreview : function() {
        // calls out to a different js obj that should already be defined
        if (widgetConfig) widgetConfig.reloadInfoAndRender();
    },
    submitConfigForm : function() {
        // to do: click the get widget button
    },
    init : function() {
        WIDGETBOX.CustomSettings.origForm = document.getElementById("widgetConfigForm");
        if (WIDGETBOX.CustomSettings.onloadFn != null) WIDGETBOX.CustomSettings.onloadFn();
    },
    sync : function(noRefresh) {
        if (WIDGETBOX.CustomSettings.syncFn != null) WIDGETBOX.CustomSettings.syncFn();
        if (!noRefresh) WIDGETBOX.CustomSettings.refreshPreview();
    },
    delayedSyncTimeout: null,
    delayedSync : function(noRefresh) {
        if (this.delayedSyncTimeout != null) {
            clearTimeout(this.delayedSyncTimeout);
        }
        this.delayedSyncTimeout = setTimeout(function() { WIDGETBOX.CustomSettings.sync(noRefresh)}, 1000);
    },
    colorPicker: {
        setColorFn: null,
        colorPickerField: null,
        hideColorPicker: function() {
            var cp = document.getElementById("colorpicker");
            if (cp.style.visibility != "hidden") cp.style.visibility = "hidden";
        },
        toggleColorPicker: function(colorFieldId, callback) {
            var cp = document.getElementById("colorpicker");
            if (cp.style.visibility == "hidden"){
                var colorField = document.getElementById(colorFieldId);
                WIDGETBOX.CustomSettings.colorPicker.presetColorPicker(colorField.value);
                WIDGETBOX.CustomSettings.colorPicker.setColorFn = callback;
                WIDGETBOX.CustomSettings.colorPicker.colorFieldId = colorFieldId;
                cp.style.visibility = "";
            } else {
                cp.style.visibility = "hidden";
            }
        },
        presetColorPicker: function (colorVal) {
            if (colorVal.indexOf("#") == 0) {
                var rgb = YAHOO.util.Color.hex2rgb(colorVal.substr(1,6));
                picker.setValue([rgb[0], rgb[1], rgb[2]], false);
            } else {
                picker.setValue([0, 0, 0], false);
            }
            picker.on("rgbChange", WIDGETBOX.CustomSettings.colorPicker.onColorPickerChange);  // picker is declared in the head of page
        },
        onColorPickerChange: function(o) {
            var r = o.newValue[0];
            var g = o.newValue[1];
            var b = o.newValue[2];
            var hex = "#" + YAHOO.util.Color.rgb2hex(r, g, b);
            if (WIDGETBOX.CustomSettings.colorPicker.colorFieldId != null) {
                document.getElementById(WIDGETBOX.CustomSettings.colorPicker.colorFieldId).value = hex;
            }
            if (WIDGETBOX.CustomSettings.colorPicker.setColorFn != null) {
                // callback
                WIDGETBOX.CustomSettings.colorPicker.setColorFn(hex);
            }
        }
    },

    imageWizard: {
        currentFieldId: null,
        widthFieldId: null,
        heightFieldId: null,
        currentImage: null,
        container:null,
        wizardWidth: 96,
        wizardHeight: 96,
        callbackFn: null,
        init: function() {
            // YUI container lightbox
            var imageWiz = document.getElementById("pro-image-wizard");
            imageWiz.style.display = "";
            WIDGETBOX.CustomSettings.imageWizard.container = new YAHOO.widget.Dialog(imageWiz,{
                width:"700px",
                //height:"600px",
                fixedcenter : false,
                constraintoviewport : true,
                effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50},
                draggable: true,
                visible:false,
                modal:true
            });
            WIDGETBOX.CustomSettings.imageWizard.container.showEvent.subscribe(function() {
                var widgetPreviewCanvas = document.getElementById("preview-canvas");
                if (widgetPreviewCanvas) widgetPreviewCanvas.style.overflow = "hidden";
            });
            WIDGETBOX.CustomSettings.imageWizard.container.hideEvent.subscribe(function() {
                var imageWizContent = document.getElementById("pro-image-wizard-content");
                imageWizContent.innerHTML = "";
                var widgetPreview = document.getElementById("preview-div");
                if (widgetPreview) widgetPreview.style.visibility = "visible";
                var widgetPreviewCanvas = document.getElementById("preview-canvas");
                if (widgetPreviewCanvas) widgetPreviewCanvas.style.overflow = "auto";
            });
            WIDGETBOX.CustomSettings.imageWizard.container.render();
        },
        generateWizardSwf: function() {
            var imageWiz = document.getElementById("pro-image-wizard");
            if (imageWiz == null) {
                // make an element that will be used to hold the image chooser content
                var wizContent = document.createElement("DIV");
                wizContent.id = "pro-image-wizard";
                var wizHtml = "<div class=\"hd\">Image Wizard</div>";
                wizHtml += "<div class=\"bd\" id=\"pro-image-wizard-content\" style=\"border-top:1px solid #000; width:700px; height:600px; padding:0\"></div>";
                wizContent.innerHTML = wizHtml;
                document.body.appendChild(wizContent);
                imageWiz = document.getElementById("pro-image-wizard");
            }
            var imageWizContent = document.getElementById("pro-image-wizard-content");
            var flashTag = null;
            var useFlash10 = WIDGETBOX.flash.Utils.DetectFlashVer(10, 0, 0);
            if (useFlash10) {
                flashTag = new WIDGETBOX.flash.Utils.FlashTag("/flash/ImageCropper10.swf", 700, 600, "10,0,0,0");
            } else {
                flashTag = new WIDGETBOX.flash.Utils.FlashTag("/flash/ImageCropper.swf", 700, 600, "9,0,0,0");
            }
            flashTag.setId("pro-image-wizard-swf");
            flashTag.setAllowScriptAccess("always");
            flashTag.setWmode("transparent");
            flashTag.addFlashVar("jsid", WIDGETBOX.CustomSettings.currentSessionId); // session id
            //flashTag.addFlashVar("userPk", currentUserPk); // user id
            //flashTag.addFlashVar("locked", "false"); // do not lock size
            flashTag.addFlashVar("callback", "WIDGETBOX.CustomSettings.imageWizard.setImageUrl"); // function wizard should call when done
            flashTag.addFlashVar("interim", "WIDGETBOX.CustomSettings.imageWizard.setCurrentImageUrl"); // function wizard should call to save current image url
            flashTag.addFlashVar("contentWidth", WIDGETBOX.CustomSettings.imageWizard.wizardWidth); // images for wizard to use
            flashTag.addFlashVar("contentHeight", WIDGETBOX.CustomSettings.imageWizard.wizardHeight); // images for wizard to use
            flashTag.addFlashVar("currentImage", WIDGETBOX.CustomSettings.imageWizard.currentImage);
            imageWizContent.innerHTML = flashTag.toString();
        },
        showWizard: function(fieldId, callback, widthFieldId, heightFieldId) {
            WIDGETBOX.CustomSettings.imageWizard.currentFieldId = fieldId;
            WIDGETBOX.CustomSettings.imageWizard.widthFieldId = widthFieldId;
            WIDGETBOX.CustomSettings.imageWizard.heightFieldId = heightFieldId;
            WIDGETBOX.CustomSettings.imageWizard.generateWizardSwf();
            WIDGETBOX.CustomSettings.callbackFn = callback;
            if (WIDGETBOX.CustomSettings.imageWizard.container == null) {
                WIDGETBOX.CustomSettings.imageWizard.init();
            }
            var widgetPreview = document.getElementById("preview-div");
            if (widgetPreview) widgetPreview.style.visibility = "hidden";
            WIDGETBOX.CustomSettings.imageWizard.container.center();
            WIDGETBOX.CustomSettings.imageWizard.container.show();
        },
        showWizardWithDimensions: function(fieldId, width, height, callback, widthFieldParamName, heightFieldParamName, widthOverrideParamName, heightOverrideParamName) {
            var completeFieldId = "configValues['" + fieldId + "']";
            var completeWidthFieldId = "configValues['" + widthFieldParamName + "']";
            var completeHeightFieldId = "configValues['" + heightFieldParamName + "']";

            if(width)WIDGETBOX.CustomSettings.imageWizard.wizardWidth = width;
            if(height)WIDGETBOX.CustomSettings.imageWizard.wizardHeight = height;

            if(widthOverrideParamName){
                var completeWidthOverrideFieldId = "configValues['" + widthOverrideParamName + "']";
                var widthOverrideField = document.getElementById(completeWidthOverrideFieldId);
                WIDGETBOX.CustomSettings.imageWizard.wizardWidth = widthOverrideField.value;
            }

            if(heightOverrideParamName){
                var completeHeightOverrideFieldId = "configValues['" + heightOverrideParamName + "']";
                var heightOverrideField = document.getElementById(completeHeightOverrideFieldId);
                WIDGETBOX.CustomSettings.imageWizard.wizardHeight = heightOverrideField.value;
            }

            WIDGETBOX.CustomSettings.imageWizard.showWizard(completeFieldId, callback, completeWidthFieldId, completeHeightFieldId);

        },
        setImageUrl: function(imageUrl, width, height) {
            // flash file should call this back when image upload is complete
            var fieldToUpdate = document.getElementById(WIDGETBOX.CustomSettings.imageWizard.currentFieldId);
            if(fieldToUpdate)fieldToUpdate.value = imageUrl;
            var widthFieldToUpdate = document.getElementById(WIDGETBOX.CustomSettings.imageWizard.widthFieldId);
            if(widthFieldToUpdate)widthFieldToUpdate.value = width;
            var heightFieldToUpdate = document.getElementById(WIDGETBOX.CustomSettings.imageWizard.heightFieldId);
            if(heightFieldToUpdate)heightFieldToUpdate.value = height;
            if (WIDGETBOX.CustomSettings.callbackFn) WIDGETBOX.CustomSettings.callbackFn(imageUrl, width, height);
            WIDGETBOX.CustomSettings.imageWizard.container.hide();
            WIDGETBOX.CustomSettings.sync();
        },
        setCurrentImageUrl: function(imageUrl) {
            WIDGETBOX.CustomSettings.imageWizard.currentImage = imageUrl;
        }
    },
    widgetChooser: {
        nameParamName: null,
        idParamName: null,
        widthParamName: null,
        heightParamName: null,

        setFields: function(nameParamName, idParamName, widthParamName, heightParamName){
            WIDGETBOX.CustomSettings.widgetChooser.nameParamName  = nameParamName;
            WIDGETBOX.CustomSettings.widgetChooser.idParamName  = idParamName;
            WIDGETBOX.CustomSettings.widgetChooser.widthParamName  = widthParamName;
            WIDGETBOX.CustomSettings.widgetChooser.heightParamName  = heightParamName;
        },
        onSelect: function(widgetObj){
            if(WIDGETBOX.CustomSettings.widgetChooser.nameParamName){
                var elementName = "configValues['" + WIDGETBOX.CustomSettings.widgetChooser.nameParamName + "']";
                var field = document.getElementById(elementName);
                field.value = widgetObj.name;
            }
            if(WIDGETBOX.CustomSettings.widgetChooser.idParamName){
                var elementName = "configValues['" + WIDGETBOX.CustomSettings.widgetChooser.idParamName + "']";
                var field = document.getElementById(elementName);
                field.value = widgetObj.id;
            }
            if(WIDGETBOX.CustomSettings.widgetChooser.widthParamName){
                WIDGETBOX.CustomSettings.utils.showParameter(WIDGETBOX.CustomSettings.widgetChooser.widthParamName);
                var elementName = "configValues['" + WIDGETBOX.CustomSettings.widgetChooser.widthParamName + "']";
                var field = document.getElementById(elementName);
                field.value = widgetObj.widgetWidth;
            }
            if(WIDGETBOX.CustomSettings.widgetChooser.heightParamName){
                WIDGETBOX.CustomSettings.utils.showParameter(WIDGETBOX.CustomSettings.widgetChooser.heightParamName);
                var elementName = "configValues['" + WIDGETBOX.CustomSettings.widgetChooser.heightParamName + "']";
                var field = document.getElementById(elementName);
                field.value = widgetObj.widgetHeight;
            }

            WIDGETBOX.CustomSettings.sync();
        }
    },
    feeds: {
        token : null,
        proxyHost : null,
        feedParamName : null,
        fetchWaitTimeout : null,
        fetchFeedForUrl : function(sourceUrl, feedParamName){
            if(sourceUrl != ""){
                if (this.fetchWaitTimeout != null) {
                    clearTimeout(this.fetchWaitTimeout);
                }
                this.fetchWaitTimeout = setTimeout(function() { WIDGETBOX.CustomSettings.feeds.extractFeedFromUrl(sourceUrl, feedParamName)}, 1000)
            }else if(feedParamName){
                    var feedElementName = "configValues['" + feedParamName + "']";
                    var feedParam = document.getElementById(feedElementName);
                    if(feedParam){
                        feedParam.value = "";
                        WIDGETBOX.CustomSettings.sync();
                    }
            }
        },
        extractFeedFromUrl : function(sourceUrl, feedParamName){
            if (this.fetchWaitTimeout != null) {
                clearTimeout(this.fetchWaitTimeout);
            }

            if(sourceUrl && feedParamName){
                var scriptSrc = this.proxyHost + "/extract/callback==WIDGETBOX.CustomSettings.feeds.feedParamName%3D'" + feedParamName + "';WIDGETBOX.CustomSettings.feeds.setExtractedFeed&&format==json&&origin==" + escape(sourceUrl) + "&&element==feed?token=" + this.token;
                //INJECT SCRIPT INTO DOM...
                WbxContainerUtils.loadScript(scriptSrc);
            }
        },
        setExtractedFeed : function(o){
            if(this.feedParamName && o.feedUrl){
                var feedElementName = "configValues['" + this.feedParamName + "']";
                var feedParam = document.getElementById(feedElementName);
                if(feedParam){
                    feedParam.value = o.feedUrl;
                    WIDGETBOX.CustomSettings.sync();
                }
            }
        }
    },
    pro: {
        isSetPro: false,
        proConfigOptions: null,
        basicConfigOptions: null,
        toggleCallbacks: null,
        enable: function(isProEnabled) {
            this.isSetPro = isProEnabled;
            if (isProEnabled) {
                //Show pro, hide basic
                if (this.basicConfigOptions) {
                    for (var i = 0; i < this.basicConfigOptions.length; i++) {
                        var basicConfigOption = this.basicConfigOptions[i];
                        var basicElement = document.getElementById(basicConfigOption.id);
                        if (basicElement) {
                            basicElement.style.display = "none";
                            if (basicConfigOption.param && basicConfigOption.defaultValue) {
                                WIDGETBOX.CustomSettings.setParamValue(basicConfigOption.param, basicConfigOption.defaultValue);
                            }
                        }
                    }
                }
                if (this.proConfigOptions) {
                    for (var i = 0; i < this.proConfigOptions.length; i++) {
                        var proConfigOption = this.proConfigOptions[i];
                        var proElement = document.getElementById(proConfigOption.id);
                        if (proElement) {
                            proElement.style.display = "";
                        }
                    }
                }
            } else {
                //Hide pro, show basic
                if (this.proConfigOptions) {
                    for (var i = 0; i < this.proConfigOptions.length; i++) {
                        var proConfigOption = this.proConfigOptions[i];
                        var proElement = document.getElementById(proConfigOption.id);
                        if (proElement) {
                            proElement.style.display = "none";
                            if (proConfigOption.param && proConfigOption.defaultValue) {
                                WIDGETBOX.CustomSettings.utils.setParamValueById(proConfigOption.param, proConfigOption.defaultValue);
                                WIDGETBOX.CustomSettings.setParamValue(proConfigOption.param, proConfigOption.defaultValue);
                            }
                        }
                    }
                }
                if (this.basicConfigOptions) { 
                    for (var i = 0; i < this.basicConfigOptions.length; i++) {
                        var basicConfigOption = this.basicConfigOptions[i];
                        var basicElement = document.getElementById(basicConfigOption.id);
                        if (basicElement) {
                            basicElement.style.display = "";
                        }
                    }
                }
            }

            if (this.toggleCallbacks) {
                for (var i = 0; i < this.toggleCallbacks.length; i++) {
                    var c = this.toggleCallbacks[i];
		            if (typeof(c) == "string") {
                        eval(c);
                    } else {
                        c(isProEnabled);
                    }
                }
            }
        },
        registerProFeature: function (elementId, paramName, defaultValue) {
            if (this.proConfigOptions == null) {
                this.proConfigOptions = new Array();
            }
            if (elementId) this.proConfigOptions.push({id: elementId, param: paramName, defaultValue: defaultValue});
        },
        registerBasicFeature: function (elementId, paramName, defaultValue) {
            if (this.basicConfigOptions == null) {
                this.basicConfigOptions = new Array();
            }
            if (elementId) this.basicConfigOptions.push({id: elementId, param: paramName, defaultValue: defaultValue});
        },
        registerProToggleCallback: function (func) {
           if (this.toggleCallbacks == null) {
               this.toggleCallbacks = new Array();
           }

           if (func) this.toggleCallbacks.push(func);
        }
    },
    lists: {
        listItems: null,
        ListItem: function(paramName, targetField, minItems, maxItems){
            this.paramName = paramName;
            this.targetField = targetField;
            this.minItems = minItems;
            this.maxItems = maxItems;
            this.inputFields = new Array();
            this.addButton = null;
        },
        addItemField : function(paramName, itemValue){
            var thisItemIndex = self.listItems[paramName].inputFields.length;
            //<input type="text" id="configValues['poll_answers']" onblur="widgetConfig.blurCurrentField(this)" name="configValues['poll_answers']" value="['This is my first answer','This is my second answer']" onkeyup="widgetConfig.keyupCurrentField(this)" onfocus="widgetConfig.setCurrentField(this)" onkeydown="widgetConfig.keydownCurrentField(this)" size="23"/>
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            var newItemDiv = document.createElement("div");
            var newItem = document.createElement("input");
            newItem.type = "text";
            newItem.size = 23;
            newItem.name = newItem.id = paramName +  "-list-item-" + thisItemIndex;
            newItem.onkeyup = newItem.onblur = function(){
                WIDGETBOX.CustomSettings.lists.updateTargetParam(paramName);
            }

            self.listItems[paramName].inputFields[thisItemIndex] = newItem; 

            if(itemValue){
                newItem.value = itemValue;
            }

            newItemDiv.appendChild(newItem);

            //<a id="delete0" href="javascript:if(mbxreg.count > 2){mbxreg.remove('pollanswers-0');unregisterColor(0);WIDGETBOX.CustomSettings.sync();pollUtils.doDeleteButtons();}" title="Delete this answer" class="delete"><img src="/images/delete.png" alt=""/></a>
            var deleteLink = document.createElement("a");
            deleteLink.name = deleteLink.id = paramName +  "-delete-" + thisItemIndex;
            deleteLink.className = "delete";
            deleteLink.title = "Delete";
            deleteLink.onclick = function(){
                newItem.style.display = "none";
                this.style.display = "none";
                newItemDiv.style.display = "none";
                WIDGETBOX.CustomSettings.lists.showHideDeleteButtons(paramName);
                WIDGETBOX.CustomSettings.lists.updateTargetParam(paramName);
            }

            var imgTag = document.createElement("img");
            imgTag.src = "/images/delete.png";

            deleteLink.appendChild(imgTag);

            newItemDiv.appendChild(deleteLink);

            self.listItems[paramName].addButton.parentNode.insertBefore(newItemDiv, self.listItems[paramName].addButton);
            WIDGETBOX.CustomSettings.lists.showHideDeleteButtons(paramName);
        },
        addNewItemButton : function(paramName, buttonLabel){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);

            self.listItems[paramName].addButton = document.createElement("div");
            self.listItems[paramName].addButton.className = "sbtn";
            self.listItems[paramName].addButton.style.paddingTop = "8px";
            self.listItems[paramName].addButton.style.marginLeft = "0px";

            var linkEl = document.createElement("a");
            linkEl.title = buttonLabel;
            linkEl.className = "make-new";
            linkEl.onclick = function(){
                WIDGETBOX.CustomSettings.lists.addItemField(paramName);
            }

            var spanEl = document.createElement("span");
            spanEl.innerHTML = buttonLabel;

            linkEl.appendChild(spanEl);
            self.listItems[paramName].addButton.appendChild(linkEl);

            var clearDiv = document.createElement("div");
            clearDiv.className = "clear";

            self.listItems[paramName].addButton.appendChild(clearDiv);
            param.parentNode.appendChild(self.listItems[paramName].addButton);
        },
        showHideDeleteButtons : function (paramName){
            var fields = self.listItems[paramName].inputFields;
            var numVis = 0;
            for(var i = 0; i < fields.length; i++){
                if(fields[i].style.display == ""){
                    numVis++;
                }
            }

            var displayMode = (numVis > self.listItems[paramName].minItems)?"":"none";
            for(var i = 0; i < fields.length; i++){
                if(fields[i].style.display == ""){
                    var deleteBtn = document.getElementById(paramName +  "-delete-" + i);
                    deleteBtn.style.display = displayMode;
                }
            }
        },
        updateTargetParam : function(paramName){
            var fields = self.listItems[paramName].inputFields;
            var paramValue = "[";
            for(var i = 0; i < fields.length; i++){
                if(fields[i].style.display == "" && fields[i].value != ""){
                    if(paramValue.length > 1){
                        paramValue += ","
                    }
                    paramValue += "'";
                    var regx = /\'/g;
                    var regx2 = /\"/g;

                    paramValue += fields[i].value.replace(regx, '&#39;').replace(regx2, '&#34;');
                    paramValue += "'";
                }
            }
            paramValue += "]";
            self.listItems[paramName].targetField.value = paramValue;
            WIDGETBOX.CustomSettings.delayedSync();
        }
    },
    utils: {
        setParamValueById : function(fieldId, paramValue) {
            var formField = document.getElementById(fieldId);
            if (formField) {
                if (formField.options != null) {
                    for (var i = 0; i < formField.options.length; i++) {
                        if (formField.options[i].value == paramValue) {
                            formField.selectedIndex = i;
                        }
                    }
                } else if (formField.type != null && formField.type == "checkbox") {
                    formField.checked = (paramValue == formField.value);
                } else if (formField.type != null && formField.type == "radio") {
                    var formFieldRef = "document." + formField.form.name + "." + formField.name;
                    var radioEls = eval(formFieldRef);
                    if (radioEls.length && radioEls.length > 0) {
                        for (var i = 0; i < radioEls.length; i++) {
                            var radioEl =  radioEls[i];
                            radioEl.checked = (radioEl.value == paramValue);
                        }
                    }
                } else {
                    formField.value = paramValue;
                }
            }
        },
        getParamValueById : function(fieldId) {
            var fieldValue = null;
            var formField = document.getElementById(fieldId);
            if (formField) {
                if (formField.options != null) {
                    fieldValue =  formField.options[formField.selectedIndex].value;
                } else if (formField.type != null && formField.type == "checkbox") {
                    if (formField.checked) {
                        fieldValue = formField.value;
                    }
                } else if (formField.type != null && formField.type == "radio") {
                    var formFieldRef = "document." + formField.form.name + "." + formField.name;
                    var radioEls = eval(formFieldRef);
                    if (radioEls.length && radioEls.length > 0) {
                        for (var i = 0; i < radioEls.length; i++) {
                            var radioEl =  radioEls[i];
                            if (radioEl.checked) {
                                var radioElVal = radioEl.value;
                                return radioElVal;
                            }
                        }
                    }
                } else {
                    fieldValue = formField.value;
                }
            }
            return fieldValue;
        },
        sectionHeaders: new Array(),
        addSectionHeader: function(header, subheader, paramName, includeDivider){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){

                var sectionHeaderCode = "";
                var dividerCode = ""
                if(includeDivider){
                    dividerCode = '<li class="divider"><hr/></li>';
                }
                sectionHeaderCode = '<li class="bigsteps"><div class="step' + (this.sectionHeaders.length + 1) + '"><h3>' + header + '</h3><span>' + subheader + '</span></div></li>';

                var sectionHeader = document.createElement("DIV");
                sectionHeader.innerHTML = sectionHeaderCode;
                var sectionDivider = document.createElement("DIV");
                sectionDivider.innerHTML = dividerCode;

                this.sectionHeaders[this.sectionHeaders.length] = sectionHeader;

                var configUl = document.getElementById("config-edit-ul");

                var liAfter = param.parentNode;

                if(includeDivider){
                    configUl.insertBefore(sectionDivider.firstChild, liAfter);
                }
                configUl.insertBefore(sectionHeader.firstChild, liAfter);
            }
        },
        registerSubOption: function(childParamName, parentParamName, toggleVisibility){
            var parentParam = document.getElementById("configValues['" + parentParamName + "']");
            var childParam = document.getElementById("configValues['" + childParamName + "']");
            childParam.parentNode.className += " sub-opt";
            if(parentParam && childParam){
                if(toggleVisibility){
                    childParam.parentNode.style.display = (parentParam.checked) ? "" : "none";
                        YAHOO.util.Event.addListener(parentParam, "click", function() {
                            childParam.parentNode.style.display = (parentParam.checked) ? "" : "none";
                    });
                }
            }
        },
        registerSubOptions: function(childParamNames, parentParamName, toggleVisibility){
            if(childParamNames){
                for(var pName in childParamNames){
                   self.registerSubOption(pName, parentParamName, toggleVisibility);
                }
            }
        },
        registerImageChooserOption: function(paramName, imageWidth, imageHeight, widthParamName, heightParamName, widthOverrideParamName, heightOverrideParamName){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
                param.className = "chooserfield";
                var afterParam = param.nextSibling;

                if(!imageWidth){
                    imageWidth = WIDGETBOX.CustomSettings.getAppWidth();
                }
                if(!imageHeight){
                    imageHeight = WIDGETBOX.CustomSettings.getAppHeight();
                }

                var jsCode = "WIDGETBOX.CustomSettings.imageWizard.showWizardWithDimensions(\"" + paramName + "\", " + imageWidth + ", " + imageHeight + ", null, \"" + widthParamName + "\" , \"" + heightParamName + "\"";
                if(widthOverrideParamName){
                    jsCode += ", \"" + widthOverrideParamName + "\"";
                }
                if(heightOverrideParamName){
                    jsCode += ", \"" + heightOverrideParamName + "\"";
                }
                jsCode += ");";
                var buttonCode = "<a href='#' onclick='" + jsCode + " return false;' class='imageChooser' title='Choose Image'><span>Choose</span></a>";

                var buttonHolder = document.createElement("DIV");
                buttonHolder.innerHTML = buttonCode;

                afterParam.parentNode.insertBefore(buttonHolder.firstChild, afterParam);
            }
        },
        registerWidgetChooserOption: function(includeMadeWidgets, includeInstalledWidgets, listedOnly, flashOnly,
                                              paramName, nameFieldId, idFieldId, widthFieldId, heightFieldId, regPK, chooserTitle, chooserSubtitle){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
                param.className = "chooserfield";

                if(widthFieldId){
                    YAHOO.util.Event.addListener(param, "keyup", function() {
                        WIDGETBOX.CustomSettings.utils.showParameter(widthFieldId);
                    });
                    YAHOO.util.Event.addListener(param, "blur", function() {
                        WIDGETBOX.CustomSettings.utils.showParameter(widthFieldId);
                    });
                }

                if(heightFieldId){
                    YAHOO.util.Event.addListener(param, "keyup", function() {
                        WIDGETBOX.CustomSettings.utils.showParameter(heightFieldId);
                    });
                    YAHOO.util.Event.addListener(param, "blur", function() {
                        WIDGETBOX.CustomSettings.utils.showParameter(heightFieldId);
                    });
                }

                var afterParam = param.nextSibling;

                var jsCode = "WIDGETBOX.CustomSettings.widgetChooser.setFields(";
                jsCode += (nameFieldId)?"'" +nameFieldId + "'" : "null";
                jsCode += "," + ((idFieldId)?"'" +idFieldId + "'" : "null");
                jsCode += "," + ((widthFieldId)?"'" +widthFieldId + "'" : "null");
                jsCode += "," + ((heightFieldId)?"'" +heightFieldId + "'" : "null");
                jsCode += ");";
                if(chooserTitle){
                    jsCode += "WbxWidgetChooser.title='" + chooserTitle + "';"
                }else{
                    jsCode += "WbxWidgetChooser.title=null;";
                }
                if(chooserSubtitle){
                    jsCode += "WbxWidgetChooser.subtitle='" + chooserSubtitle + "';"
                }else{
                    jsCode += "WbxWidgetChooser.subtitle=null;";
                }
                jsCode += "WbxWidgetChooser.show(" + includeMadeWidgets + ", " + includeInstalledWidgets + ", " + listedOnly + ", " + flashOnly + ", WIDGETBOX.CustomSettings.widgetChooser.onSelect";

                if(regPK){
                    jsCode += ", '" + regPK + "'";
                }

                jsCode += ");return false;";

                var buttonCode = "<a href='#' onclick=\"" + jsCode + "\" class='imageChooser' title='Choose Widget'><span>Choose</span></a>";

                var buttonHolder = document.createElement("DIV");
                buttonHolder.innerHTML = buttonCode;

                afterParam.parentNode.insertBefore(buttonHolder.firstChild, afterParam);
            }
        },
        registerFeedOption: function(blogSourceParamName, feedSourceParamName){
            var elementName = "configValues['" + blogSourceParamName + "']";
            var param = document.getElementById(elementName);

            var feedElementName = "configValues['" + feedSourceParamName + "']";
            var feedParam = document.getElementById(feedElementName);
            if(param && feedParam){
                //remove existing listeners
                param.onkeydown = null;
                param.onkeyup = null;

                //add change listener to param to
                YAHOO.util.Event.addListener(param, "keyup", function() {
                    WIDGETBOX.CustomSettings.feeds.fetchFeedForUrl(param.value, feedSourceParamName);
                });
            }
        },
        registerListOption: function(paramName, addItemButtonLabel, minItems, maxItems){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);

            if(!addItemButtonLabel)addItemButtonLabel = "Add another";
            if(!minItems) minItems = 0;
            if(!maxItems) maxItems = 1000;
            if(!self.listItems)self.listItems = new Array();
            if(!self.listItems[paramName]){
                self.listItems[paramName] = new WIDGETBOX.CustomSettings.lists.ListItem(paramName, param, minItems, maxItems);
            }

            WIDGETBOX.CustomSettings.lists.addNewItemButton(paramName, addItemButtonLabel);
            var existingData = param.value;
            var items = new Array();
            if(existingData.length > 0){
                if(existingData.indexOf("[") == 0 && existingData.indexOf("]") == (existingData.length - 1)) {
                    items = eval(existingData);
                }else{
                    items[0] = existingData;
                }
            }

            for(var i = 0; i < items.length && i < maxItems; i++){
                var paramValue = items[i];

                paramValue = paramValue.replace(/&#39;/g, '\'').replace(/&#34;/g, '\"');
                WIDGETBOX.CustomSettings.lists.addItemField(paramName, paramValue);
            }

            for(var i = 0; i < minItems - items.length; i++){
                WIDGETBOX.CustomSettings.lists.addItemField(paramName);
            }


            param.style.display = "none";
        },
        addTextField: function(index, name, label, value, size, maxSize, suffix, note){
            var configUl = document.getElementById("config-edit-ul");

            var liAfter = configUl.getElementsByTagName("li")[(index + 1)];
            var liHolder = document.createElement("DIV");
            var content =  '<li>'+
                            '<label class="required" for="'+name+'">'+label+':</label>'+
                            '<input type="text" name="'+name+'" id="'+name+'"';
            if(value){content += ' value="'+value+'"';}
            if(size){content += ' size="'+size+'"';}
            if(maxSize){content += ' maxSize="'+maxSize+'"';}
            content += ' onblur="widgetConfig.blurCurrentField(this)" name="configValues['+name+']" onkeydown="widgetConfig.keydownCurrentField(this)" onfocus="widgetConfig.setCurrentField(this)" onkeyup="widgetConfig.keyupCurrentField(this)"/>';
            if(suffix) content += suffix;
            content += '<p>' + note + '</p>'+
                          '</li>';
            liHolder.innerHTML = content;

            configUl.insertBefore(liHolder.firstChild, liAfter);
        },
        modifyTextField: function(paramName, size, maxSize, label){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
                param.className = "dimensionfield";
                if(size){param.size = size;}
                if(maxSize){param.maxSize = maxSize;}
                if(label){
                    var afterParam = param.nextSibling;
                    var labelHolder = document.createElement("DIV");
                    labelHolder.innerHTML = "&nbsp;" + label;

                    afterParam.parentNode.insertBefore(labelHolder.firstChild, afterParam);
                }
            }
        },
        modifyLabel: function(paramName, newLabel, hide){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
               var label = param.parentNode.getElementsByTagName("label")[0];
               if(label){
                   if(newLabel) label.innerHTML = newLabel;
                   if(hide) label.style.display = "none";
               }
            }
        },
        addLabel: function(paramName, labelText){
            var configUl = document.getElementById("config-edit-ul");
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            var liHolder = document.createElement("DIV");
            liHolder.innerHTML = '<li><label class="required" for="configValues[\'' + paramName + '\']">' + labelText + '</label><div class="clear"/></li>';
            if(param){
                var liAfter = param.parentNode;
                configUl.insertBefore(liHolder.firstChild, liAfter);
            }else{
                configUl.appendChild(liHolder.firstChild);
            }
        },
        addDivider: function(paramName){
            var configUl = document.getElementById("config-edit-ul");
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            var liHolder = document.createElement("DIV");
            liHolder.innerHTML = "<li class='divider'><hr/></li>";
            if(param){
                var liAfter = param.parentNode;
                configUl.insertBefore(liHolder.firstChild, liAfter);
            }else{
                configUl.appendChild(liHolder.firstChild);
            }
        },
        hideParameter: function(paramName){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
                param.parentNode.style.display = "none";
            }
        },
        showParameter: function(paramName){
            var elementName = "configValues['" + paramName + "']";
            var param = document.getElementById(elementName);
            if(param){
                param.parentNode.style.display = "";
            }
        },
        escape: function(string) {
	        if(typeof string == 'string') {
		        return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
            } else if(typeof string == 'number') {
		        return string;
            } else {
		        return '';
            }
        },
        addslashes: function(str) {
            str = str.replace(new RegExp('/\\\'/g'), '\\\'');
            str = str.replace(new RegExp('/\\"/g'), '\\"');
            str = str.replace(new RegExp('/\\/g'), '\\\\');
            str = str.replace(new RegExp('/\0/g'), '\\0');
            return str;
        }
    }
}