/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4-vsdoc.js"/>
/// <reference path="ui.core.js" />
/// <reference path="effects.core.js" />
/// <reference path="effects.highlight.js" />

// function to create a drop down option
function ruleDependentFieldOption(val, text, parentNodeValue) {
    this.val = val;
    this.text = text;
    this.parentNodeValue = parentNodeValue;
}

// function to create a drop down option
function DropDownOption(val, text, isselected) {
    this.val = val;
    this.text = text;
    this.isselected = isselected;
}

function dataField(dataFieldName, sampleData) {
    this.dataFieldName = dataFieldName;
    this.sampleData = sampleData;
}

function vdpDataFileMap(variableID, variableName, dataFieldName, displayName, sampleData, displayOrder, required) {
    this.variableID = variableID;
    this.variableName = variableName;
    this.dataFieldName = dataFieldName;
    this.displayName = displayName;
    this.sampleData = sampleData;
    this.displayOrder = displayOrder;
    this.required = required;
}


// function to define a ruleDependent Array
function ruleDependentArray(ruleValue, dependentArray) {
    this.ruleValue = ruleValue;
    this.dependentArray = dependentArray;
}

function FixQuotes(textIs) {
    // first replace " with &quot;
    thelength = textIs.length;
    for (i = 0; i < thelength; i++) {
        if (textIs.charAt(i) == '"') {
            textIs = textIs.substring(0, i) + "&quot;"
            + textIs.substring(i + 1, thelength);
            thelength += 6;
            i += 6;
        }
    }
    // now replace &apos; with '
    var pos = 0;
    while (pos != -1) {
        pos = textIs.indexOf("&apos;");
        if (pos != -1)
            textIs = textIs.substring(0, pos) + "'" + textIs.substring(pos + 6);
    }
    return textIs;
}

//////////////////////////////////////////////
// function to open browse pictures (ie image gallery)
//////////////////////////////////////////////
function openBrowsePictures(jsVariableID, jsFormIndex, isOnChange, onChangeFunctionName, jsVariableHtmlID, prefillId) {
    var formPrompt = ShortenString(allFormElementsIdMap[jsVariableHtmlID].elemdisplayname);
    var iFrameUrl = 'BrowseImagesFilter.aspx?CompanyID=' + companyid + '&templateID=' + templateID + '&userID=' + userID + '&VariableID=' + jsVariableID + '&formIndex=' + jsFormIndex + '&elemid=' + jsVariableHtmlID + '&imageprefillid=' + prefillId + '&isOnChange=' + isOnChange + '&onChangeFunctionName=' + onChangeFunctionName;    
    var w = 650;
    var h = 550;
    var maxWidth = 720;
    var maxHeight = 620;
    var ddEl = $(jsVariableHtmlID);
    if (ddEl && ddEl != null) {
        if (ddEl.length <= 10)
            maxHeight = 475; 
    }
    if (typeof (jQuery) !== 'undefined') {
        w = parseInt(0.80 * jQuery(window).width());
        h = parseInt(0.80 * jQuery(window).height());
        if (w > maxWidth)
            w = maxWidth;
        if (h > maxHeight)
            h = maxHeight;
        iFrameUrl += '&if_w=' + w + '&if_h=' + h;
    }
    jQuery.fn.colorbox({ width: w, height: h, maxWidth: maxWidth, maxHeight: maxHeight, iframe: true, href: iFrameUrl, open: true, overlayClose: false, scrollbars: false, opacity: 0.70, title: formPrompt });
}

// function to upload image
function uploadImage(jsVariableID, jsUploadFormIndex, fWidth, fHeight, dpi, forceCmyk, jsVariableHtmlID, prefillId, enableEllipse, featherDistance) {   
    // by default we'll use the post message function to communicate between windows in different sub-domains
    if (typeof (postMessageEnabled) == 'undefined') {
        postMessageEnabled = true;
        // disable image resizing on IE7    		
        if (true == isIE7) {            
            postMessageEnabled = false;
        }
    }
    var uploadElement = document.forms[0].elements[jsUploadFormIndex];
    var uploadId = typeof (uploadElement.id) === "undefined" ? uploadElement.name : uploadElement.id;
    var formPrompt = ShortenString(allFormElementsIdMap[jsVariableHtmlID].elemdisplayname);
    var page = 'UploadImage.aspx';
    var w = "550";
    var h = true == postMessageEnabled ? "250" : "500";
    if (dpi && dpi > 0 && false == postMessageEnabled) {
        w = "750";
        h = "600";
    }
    var iFrameUrl = page + '?CompanyID=' + companyid + '&templateID=' + templateID + '&userID=' + userID + '&VariableID=' + jsVariableID + '&formIndex=' + jsUploadFormIndex + '&elemid=' + uploadId + '&imageprefillid=' + prefillId + '&frameWidth=' + fWidth + '&frameHeight=' + fHeight + '&dpi=' + dpi + '&forceCmyk=' + forceCmyk + '&ellipse=' + enableEllipse + '&fd=' + featherDistance + '&doPost=' + postMessageEnabled;
    jQuery.fn.colorbox({ width: "90%", maxWidth: w, height: h, iframe: true, href: iFrameUrl, open: true, overlayClose: false, scrollbars: false, opacity: 0.70, title: formPrompt });
}

// use this to keep track if image has already been deleted after the user selects another image
var disableDeleteUploadedImage = false;
function ReturnCallBrowsePictures(jsFormIndex, elementId, prefillId, imageId, onChangeFunctionName, friendlyName) {
    // delete any image that was previously uploaded by user
    disableDeleteUploadedImage = false; // set this to false so it will delete once
    DeleteUploadedImage(elementId, prefillId);
    disableDeleteUploadedImage = true; // already done once, disable call to it again in this same function
    document.forms[0].elements[jsFormIndex].value = imageId;

    if (prefillId != null && prefillId.length > 0) {
        var ddEl = $(elementId);
        var prefillLinkEl = $(prefillId + 'Link');
        var prefillRemoveEl = $(prefillId + 'Remove');
        var prefillContainerEl = $(prefillId + 'Div');

        if (prefillLinkEl != null && prefillContainerEl != null) {
            var disableRemove = ddEl != null && ddEl.length > 0 && trim(ddEl.options[0].value) != '';
            prefillRemoveEl.style.display = disableRemove ? 'none' : 'inline';

            prefillLinkEl.down("span").innerHTML = friendlyName;
            prefillContainerEl.style.display = 'block';
            prefillContainerEl.style.visibility = 'visible';
        }
    }
    if (arguments.length >= 5 && onChangeFunctionName != null && onChangeFunctionName.length > 0) {
        var fn = onChangeFunctionName + "(document.forms[0].elements[" + jsFormIndex + "]);";
        eval(fn);
    }
}

function ReturnCallUploadImage(jsFormIndex, uploadElementId, uploadPrefillId, imageId, imageDisplayName) {
    document.forms[0].elements[jsFormIndex].value = imageId;

    if (uploadPrefillId != null && uploadPrefillId.length > 0) {
        var prefillEl = $(uploadPrefillId);
        var prefillLinkEl = $(uploadPrefillId + 'Link');
        var prefillRemoveEl = $(uploadPrefillId + 'Remove');
        var prefillContainerEl = $(uploadPrefillId + 'Div');

        prefillEl.value = imageDisplayName;
        prefillLinkEl.down("span").innerHTML = ShortenString(imageDisplayName);
        prefillRemoveEl.style.display = 'inline';        
        prefillContainerEl.style.display = 'block';
        prefillContainerEl.style.visibility = 'visible';
    }
    DisableAddFromVersionedForm();
}

function getLocalImageUrl(frmIndex, prefillId, elementId, imageType) {
    var ddEl = $(elementId);
    var prefillEl = $(prefillId);
    var isImageGalleryEl = prefillEl.value == '';
    var imageId = isImageGalleryEl || typeof (frmIndex) == 'undefined' || frmIndex < 0
        ? (ddEl.options.length > 0 ? ddEl.options[ddEl.selectedIndex].value : '__blank__')
        : document.forms[0].elements[frmIndex].value;

    return 'DownloadProcessor.ashx?downloadType=image&imageType=browse&dropDownValue=' + imageId;
}

function updateImageGalleryName(frmIndex, prefillId, elementId) {
    var ddEl = $(elementId);
    var prefillEl = $(prefillId);
    var isImageGalleryEl = prefillEl.value == '';
    var imageId = isImageGalleryEl || typeof (frmIndex) == 'undefined' || frmIndex < 0
        ? ddEl.options[ddEl.selectedIndex].value
        : document.forms[0].elements[frmIndex].value;
    var displayName = isImageGalleryEl || typeof (frmIndex) == 'undefined' || frmIndex < 0
        ? ddEl.options[ddEl.selectedIndex].text
        : document.forms[0].elements[frmIndex].text;
    var prefillLinkEl = $(prefillId + 'Link');
	var prefillContainerEl = $(prefillId + 'Div');
    if (prefillLinkEl && prefillLinkEl != null) {
        prefillLinkEl.down("span").innerHTML = displayName;
		var show = (displayName == null || displayName.length == 0) ? false : true;
		prefillContainerEl.style.display = show ? 'block' : 'none';
	}
}

function removeLocalImage(frmIndex, prefillId, elementId, onChangeFunctionName) {
	if (frmIndex > -1)
		document.forms[0].elements[frmIndex].value = '';

    var prefillEl = $(prefillId);
    var prefillContainerEl = $(prefillId + 'Div');
    var isImageGalleryEl = prefillEl.value == '';

    prefillEl.value = '';
    prefillContainerEl.style.display = 'none';
    prefillContainerEl.style.visibility = 'hidden';

    if (arguments.length >= 3 && elementId != null && elementId.length > 0) {
        var ddEl = $(elementId);
        if (ddEl != null && ddEl.length > 0) {
            if (isImageGalleryEl) {
                // reset image gallery only hidden dropdown to first index
                ddEl.selectedIndex = 0;
                if (arguments.length >= 4 && onChangeFunctionName != null && onChangeFunctionName.length > 0) {
                    var fn = onChangeFunctionName + "(document.forms[0].elements[" + ( frmIndex > -1 ? frmIndex : returnindex(elementId) ) + "]);";
                    eval(fn);
                }
            }
            else {
                // otherwise this is an upload field that has an image gallery
                //  check if it is an imagegallery only field without a firstdropdownvalueBlank, 
                //  and if so reset to the default prefill (or first value)
                var isHidden = ddEl.style.display == 'none';
                var disableRemove = trim(ddEl.options[0].value) != '';
                var selectedVal = ddEl.options[ddEl.selectedIndex].value;
                if (isHidden && disableRemove) {
                    ReturnCallBrowsePictures(returnindex(elementId), elementId, prefillId, selectedVal, onChangeFunctionName);
                }
            }
        }
    }
    DisableAddFromVersionedForm(); // need to force preview
}

function DeleteUploadedImage(elementId, prefillId) {
    if (!disableDeleteUploadedImage) {
        var uploadImageEl = $(elementId + '__uploadImage');
        var uploadImageElNote = $(elementId + '__uploadImageNote');
        var uploadImageNoteDiv = $(elementId + '__uploadImageNoteDiv');
        if (uploadImageEl != null)
            uploadImageEl.value = '';
        if (uploadImageElNote != null)
            uploadImageElNote.value = '';
        if (uploadImageNoteDiv != null) {
            uploadImageNoteDiv.style.display = 'none';
            uploadImageNoteDiv.style.visibility = 'hidden';
        }
    }
}

function uploadJobDirectFile(variableId, variableHtmlId) {
    // by default we'll use the post message function to communicate between windows in different sub-domains
    if (typeof (postMessageEnabled) == 'undefined') {
        postMessageEnabled = true;
        // disable image resizing on IE7    		
        if (true == isIE7) {
            postMessageEnabled = false;
        }
    }    
    var formPrompt = ShortenString(allFormElementsIdMap[variableHtmlId].elemdisplayname);
    var page = 'UploadImage.aspx';
    var w = "550";
    var h = true == postMessageEnabled ? "250" : "500";
    var iFrameUrl = page + '?CompanyID=' + companyid + '&templateID=' + templateID + '&userID=' + userID + '&VariableID=' + variableId + '&variableHtmlId=' + variableHtmlId + '&elemid=' + variableHtmlId + '&jobDirect=1&formIndex=-1&doPost=' + postMessageEnabled;
    jQuery.fn.colorbox({ width: "90%", maxWidth: w, height: h, iframe: true, href: iFrameUrl, open: true, overlayClose: false, scrollbars: false, opacity: 0.70, title: formPrompt });
}

function ReturnCallUploadJobDirectFile(variableId, variableHtmlId, prefillValue, displayName) {
    // 1. set the raw jobdirect upload prefill value (contains the external id and file display name)
    var prefillId = variableHtmlId + "__uploadImage";
    $(prefillId).value = prefillValue;

    var prefillContainerEl = $(variableHtmlId + '__uploadImageNoteDiv');
    var prefillLinkEl = $(variableHtmlId + '__uploadImageNoteLink');
    var prefillRemoveEl = $(variableHtmlId + '__uploadImageNoteRemove');
    if (prefillContainerEl != null && prefillLinkEl != null) {
        prefillLinkEl.down("span").innerHTML = ShortenString(displayName);
        prefillRemoveEl.style.display = 'inline';
        prefillContainerEl.style.display = 'block';
        prefillContainerEl.style.visibility = 'visible';
    }
}

function removeJobDirectFile(variableId, variableHtmlId) {
    // 1. kill the prefill value (the job direct upload file value)
    var prefillId = variableHtmlId + "__uploadImage";
    $(prefillId).value = '';

    // 2. hide the prefill display UI
    var prefillContainerId = variableHtmlId + "__uploadImageNoteDiv";
    var prefillContainerEl = $(prefillContainerId);
    if (prefillContainerEl != null) {
        prefillContainerEl.style.display = 'none';
        prefillContainerEl.style.visibility = 'hidden';
    }

    // 3. force a preview so the user cannot add to cart
    DisableAddFromVersionedForm();
}

function getJobDirectFileUrl(variableId, variableHtmlId) {
    // 1. get the uploaded job direct file prefill value (this contains the external id for the job direct file)
    var prefillId = variableHtmlId + "__uploadImage";
    var jobDirectFormValue = $(prefillId).value;

    // 2. pass the prefill to the image preview handler so it can lookup the converted pdf file
    return 'DownloadProcessor.ashx?downloadType=JobDirectConvertedImage&imageType=browse&dropDownValue=' + jobDirectFormValue;
}

function closeDialog() {
    jQuery.fn.colorbox.close();
}

function resizeDialog(w, h, customCallback) {    
    jQuery.fn.colorbox.resize({ innerWidth: w, innerHeight: h }, customCallback);
}

function ShortenString(word) {
    if (word == null || word.length == 0)
        return "";

    // make sure the title is not too long
    if (word.length > 35)
        word = word.substring(0, 32) + "...";

    return word;
}

function FormElement(elemname, elemdisplayname, elemtype, elemcheckfor, elemwarning, elemerrmessage, elemdefaultvalue, elemisrequired, elemonchange, sectionIdx, rteEnabled) {
    this.elemname = elemname;
    this.elemdisplayname = elemdisplayname;
    this.elemtype = elemtype;
    this.elemcheckfor = elemcheckfor;
    this.elemwarning = elemwarning;
    this.elemerrmessage = elemerrmessage;
    this.elemdefaultvalue = elemdefaultvalue;
    this.elemisrequired = elemisrequired;
    this.elemonchange = elemonchange;
    this.sectionIndex = sectionIdx;
    this.conditionalparent = null;
    this.rteEnabled = rteEnabled;
}

// check for blank value
function isBlank(varstr) {

    if (varstr.length != 0)
        for (var i = 0; i < varstr.length; i++) {
        var ch = varstr.substring(i, i + 1);
        if (ch != " ") {
            return true;
            break;
        }
        else {
            return false;
            break;
        }
    }

    // FOR LOOP
    else
        return false;
}

// function to check valid number

function isNumber(inStr) {
    inLen = inStr.length
    for (var i = 0; i < inLen; i++) {
        var ch = inStr.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && (ch != "-")) {
            return false;
            break;
        }
    }
    return true;
}

// function to check for Positive number

function isPositive(inStr) {
    inLen = inStr.length
    for (var i = 0; i < inLen; i++) {
        var ch = inStr.substring(i, i + 1)
        if (ch < "0" || "9" < ch) {
            return false;
            break;
        }
    }
    if (parseInt(inStr) <= 0)
        return false;
    return true;

}

//function to trim the value passed to it

function trim(strMessage) {
    var strResult;
    var charTemp;
    var i;
    strResult = "";
    //remove the left space
    for (i = 0; i < strMessage.length; i++) {
        charTemp = strMessage.charAt(i);
        if (charTemp != " ") {
            strResult = strMessage.substring(i);
            break;
        }
    }
    //remove the right space
    for (i = strResult.length - 1; i >= 0; i = i - 1) {
        charTemp = strResult.charAt(i);
        if (charTemp != " ") {
            strResult = strResult.substring(0, i + 1);
            break;
        }
    }
    return (strResult);

}

function isValidEmailAddress(strEmailAddress) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!filter.test(strEmailAddress))
        return false;
    return true;
}

// function to return element index for a form
function returnindex(callingfield, callingform) {
    var elementId;
    for (var i = 0; i < document.forms[0].elements.length; i++) {
        elementId = typeof (document.forms[0].elements[i].id) === "undefined"
            ? document.forms[0].elements[i].name
            : document.forms[0].elements[i].id;

        if (elementId == callingfield)
            return i;
    }
    return -1;
}

// function to check if the character passed is numeric
function IsDigit(chVal) {
    var numStr = "0123456789";
    if (numStr.indexOf(chVal) != -1) {
        return true;
    }
    return false;
}

// function to check if the passed value is a valid currency

function isValidCurrency(curStr) {
    var data = curStr;
    if (data.length == 0)
        return false;

    var nState = 0;
    var chCur = data.charAt(0);
    var nCurChar = 0;

    while (nCurChar < data.length) {
        //alert("character at position " + nCurChar + " is " + chCur);
        //alert("nState at position " + nCurChar + " is " + nState);
        switch (nState) {
            case 0:
                if (chCur == "$")
                    nState = 1;
                else if (IsDigit(chCur))
                    nState = 1;
                else
                    return false;
                break;
            case 1:
                if (IsDigit(chCur))
                    nState = 2;
                else if (chCur == ",")
                    nState = 8;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
                break;
            case 2:
                if (IsDigit(chCur))
                    nState = 3;
                else if (chCur == ",")
                    nState = 8;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
                break;
            case 3:
                if (IsDigit(chCur))
                    nState = 3;
                else if (chCur == ",")
                    nState = 8;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
                break;
            case 4:
                if (IsDigit(chCur))
                    nState = 12;
                else if (chCur == ",")
                    nState = 8;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
                break;
            case 5:
                if (IsDigit(chCur))
                    nState = 6;
                else
                    return false;
                break;
            case 6:
                if (IsDigit(chCur))
                    nState = 7;
                else
                    return false;
                break;
            case 7:
                //return false;
                if (IsDigit(chCur))
                    nState = 8;
                else
                    return false;
                break;
            case 8:
                if (IsDigit(chCur))
                    nState = 9;
                else
                    return false;
                break;
            case 9:
                if (IsDigit(chCur))
                    nState = 10;
                else
                    return false;
                break;
            case 10:
                if (IsDigit(chCur))
                    nState = 11;
                else
                    return false;
                break;
            case 11:
                if (chCur == ",")
                    nState = 8;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
                break;
            case 12:
                if (IsDigit(chCur))
                    nState = 12;
                else if (chCur == ".")
                    nState = 5;
                else
                    return false;
        };

        nCurChar++;
        chCur = data.charAt(nCurChar);
    }
    if ((nState == 5) || (nState == 6))
        return false;

    return true;
}

// function to check if the passed value is a valid decimal value

function isReal(inStr) {
    inLen = inStr.length
    for (var i = 0; i < inLen; i++) {
        var ch = inStr.substring(i, i + 1)
        if (ch != ".")
            if (ch < "0" || "9" < ch) {
            return false;
            break;
        }
    }
    return true;
}

// function to check if valid date

function isDate(date) {
    var dt;
    dt = new Date();
    var stMonth = parseInt(dt.getMonth() + 1);
    var stDate = parseInt(dt.getDate());
    var stYear = parseInt(dt.getYear());

    var s = "" + date;
    var str1 = "";
    var s3 = ""; var s4 = "";

    if (s.charAt(1) == '/' || s.charAt(1) == '-') {
        s = "0" + s;
    }

    if (s.charAt(4) == '/' || s.charAt(4) == '-') {
        s = s.substring(0, 3) + "0" + s.substring(3)
    }

    if (s.length == 10 || s.length == 8) {
        var validnum2 = isNumber(s.substring(0, 2));
        var validnum1 = isNumber(s.substring(3, 5));
        var validnum5 = isNumber(s.substring(6));
        if (validnum2 == false || validnum1 == false || validnum5 == false)
            str1 = "Wrong Date";
        else {
            var s2 = parseInt(s.substring(0, 2));
            var s1 = parseInt(s.substring(3, 5));
            var a1 = "";
            a1 = s.substring(6);
            if (a1.length == 2) {
                a1 = "20" + a1;
            }
            var s5 = parseInt(a1);
            s4 = s.substring(0, 2);
            s3 = s.substring(3, 5);
            if ((s.charAt(2) == '/' || s.charAt(2) == '-') && (s.charAt(5) == '/' || s.charAt(5) == '-')) {
                if (s1 > 31 || s2 > 12 || s3 == "00" || s4 == "00") {
                    str1 = "Wrong Date ";
                }
                else {
                    if (!(((s4 == "04") || (s4 == "06") || (s4 == "09") || (s4 == "11")) && (s1 > 30))) {
                        if (s4 == "02") {
                            if (s1 > 29) {
                                str1 = "Wrong Date";
                            }
                            else {
                                if (!(s5 % 4 == 0) && (s1 > 28)) {
                                    str1 = "Wrong Date";
                                }
                                else {
                                    str1 = "This is a perfect Date";
                                }
                            }
                        }
                        else {
                            str1 = "This is a perfect Date";
                        }
                    }
                    else {
                        str1 = "Wrong Date";
                    }
                }
            }
            else {
                str1 = "Wrong Format ";
            }
        }
    }

    if (str1 != "This is a perfect Date") {
        //alert(str1 + " Please enter a valid Date");
        return false;
    }
    else {
        //alert("Perfect Date!!!");
        return true;
    }
}

// Deletes all the items from the Drop-Down List supplied

function delAllDropDownItems(selField) {
    for (var i = 0; i < selField.length; i++) {
        selField.options[i] = null;
        i--;
    }
}

// function matches element name and returns allFormElements index true if found
function allFormElementsIndex(elementName) {
    for (var j = 0; j < allFormElements.length; j++) {
        if (elementName == allFormElements[j].elemname)
            return j;
    }
    return -1;
}

/* function that checks if all elements are good to go...

values for elemcheckfor

1 - check for blank, depends on element type
if text or textarea then call isBlank function
if include or select check for selectedindex as it is dropdown
2 - check for number (int no decimals)
3 - check for currency (can be of format 0 or $0 or 0.0 or $0.0 or 0.00 or $0.00
4 - check for decimal value
5 - check for valid date
6 - check for positive number > 0

elemerrmessage can hold the error message for the field
so if not empty then display that error message else display the default error message

elemwarning tells if we should warn the user, if an entered value is incorrect
the warning will be displayed only to the fields that are NOT required
and that have been set in the xml to display warning
elemdefaultvalue holds the default value that the field value must be set
if it is incorrect
*/

function checkAll(formname) {
    var ret = true;

    // first check for required elements
    if (typeof (allFormElements) == 'undefined')
        return true;

    for (var j = 0; j < allFormElements.length; j++) {
        var formelem = allFormElements[j];
        var validationResult = checkformelem(formelem, formname);

        if (!validationResult.isvalid) {
            // check if this is a conditional child and if it is hidden then we're all good
            if (formelem.elemconditionalparent != null) {
                // for RTE fields, the text area is always hidden. We want to check the "Add Text..." button instead, since when it is visible the field is empty
                // For Image Gallery Only and Image Collection Gallery Only we want to check the "Gallery" button, since that is what the user sees to select
	            var idToCheck = formelem.elemname;
	            var elemType = formelem.elemtype.toLowerCase();
                if (formelem.rteEnabled == 1)
                    idToCheck = formelem.elemname + "__richTextEditorButtonDiv";
                else if (elemType == 'imagegallery' || elemType == 'imagecollectiongallery')
                    idToCheck = formelem.elemname + "_row";

	            var jqObj = jQuery("#" + idToCheck);
	            var jqParentCell = jqObj.parent().get(0).tagName.toLowerCase() == 'td' ? jqObj.parent() : null;
	            var jqParentRow = jqObj.parent().parent().get(0).tagName.toLowerCase() == 'tr' ? jqObj.parent().parent() : null;

	            // this element is only visible if it's containing table cell and table row are not hidden;
	            //  so if any are hidden or display:none then this child is hidden as well
	            var isHidden = jqObj.css('display') == 'none' 
                            || jqObj.css('visibility') == 'hidden'
	                        || (jqParentCell != null && (jqParentCell.css('display') == 'none' || jqParentCell.css('visibility') == 'hidden'))
                            || (jqParentRow != null && (jqParentRow.css('display') == 'none' || jqParentRow.css('visibility') == 'hidden'));

                // conditional children are not required if they are hidden (ie the parent value was not selected)
                if (isHidden)
                    continue;
            }

            activateSection(formelem);
            alert(validationResult.message);

            $(formelem.elemname).focus();
            ret = false;
            break;
        }
    }
    return ret;
}

function checkformelem(formelem, formname) {
    var ret = true;
    var errorMsg = '';
    var elementObj = null;
    var elementUploadImageObj = null;
    var localImageUpload = false; // for upload local images    
    var str = formelem.elemtype.toLowerCase();
    var textfieldElemTypes = { 'text': true, 'textarea': true, 'tpa_single': true, 'tpa_multi': true, 'password': true, 'labeldropdown': true };
    var dropdownElemTypes = { 'include': true, 'select': true, 'libraryselect': true, 'image': true, 'executefunction': true, 'imagecollection': true, 'imagegallery': true, 'imagecollectiongallery': true, 'imagecollectiondropdown': true };

    if (formelem.elemisrequired == 1) 
    {
        if (typeof (textfieldElemTypes[str]) !== 'undefined') 
        {
            elementObj = $(formelem.elemname);
            if (formelem.elemcheckfor == 1) // check for blank
            {
                if (isBlank(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('EmptyFieldMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
            if (formelem.elemcheckfor == 2) // check for number
            {
                if (isBlank(trim(elementObj.value)) == false || isNumber(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('ValidNumberMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
            if (formelem.elemcheckfor == 3) // check for valid currency
            {
                if (isValidCurrency(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('ValidCurrencyMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
            if (formelem.elemcheckfor == 4) // check for valid currency
            {
                if (isReal(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('ValidDecimalMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
            if (formelem.elemcheckfor == 5) // check for valid date
            {
                if (isDate(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('ValidDateMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
            if (formelem.elemcheckfor == 6) // check for positive number
            {
                if (isBlank(trim(elementObj.value)) == false || isPositive(trim(elementObj.value)) == false) {
                    if (formelem.elemerrmessage == '')
                        errorMsg = formelem.elemdisplayname + GetStringContent('ValidPositiveNumberMessage');
                    else
                        errorMsg = formelem.elemerrmessage;
                    ret = false;
                }
            }
        }

        // if type is include or select ..meaning dropdown
        if (typeof (dropdownElemTypes[str]) !== 'undefined') 
        {
            elementObj = $(formelem.elemname);
            elementUploadImageObj = $(formelem.elemname + '__uploadImage');
            if (formelem.elemcheckfor == 1) 
            {
                if (elementUploadImageObj != null) 
                {
                    if (elementUploadImageObj.value == '');
                    else
                        localImageUpload = true;
                }
                if (localImageUpload == false) 
                {
                    if (elementObj == null || elementObj.selectedIndex < 0 || elementObj.options[elementObj.selectedIndex].value == '') 
                    {
                        if (formelem.elemerrmessage == '')
                            errorMsg = GetStringContent('ValidDropdownValueMessage') + formelem.elemdisplayname + '.';
                        else
                            errorMsg = formelem.elemerrmessage;

                        ret = false;
                    }
                }
            }
        }
    }
    else // now check for other elements and warn if entered incorrectly
    {
        if (typeof (textfieldElemTypes[str]) !== 'undefined') {
            elementObj = $(formelem.elemname);
            if (formelem.elemcheckfor == 2 && formelem.elemwarning == 1) // check for number
            {
                if (isBlank(trim(elementObj.value)) == true && isNumber(trim(elementObj.value)) == false) {
                    activateSection(formelem);
                    if (formelem.elemerrmessage == '')
                        ret = confirm(formelem.elemdisplayname + ' if entered, should be a valid number.\nPress "OK" to set the default value or "Cancel" to enter the appropriate value.');
                    else
                        ret = confirm(formelem.elemerrmessage);
                    if (ret == false) {
                        ;
                    }
                    else
                        elementObj.value = formelem.elemdefaultvalue;

                }
            }
            if (formelem.elemcheckfor == 3 && formelem.elemwarning == 1) // check for valid currency
            {
                if (isBlank(trim(elementObj.value)) == true && isValidCurrency(trim(elementObj.value)) == false) {
                    activateSection(formelem);
                    if (formelem.elemerrmessage == '')
                        ret = confirm(formelem.elemdisplayname + ' if entered, should be a numeric currency value.\nPossible values can be like 0 or $0 or $0.00\nPress "OK" to set the default value or "Cancel" to enter the appropriate value.');
                    else
                        ret = confirm(formelem.elemerrmessage);
                    if (ret == false) {
                        ;
                    }
                    else
                        elementObj.value = formelem.elemdefaultvalue;
                }
            }
            if (formelem.elemcheckfor == 4 && formelem.elemwarning == 1) // check for valid currency
            {
                if (isBlank(trim(elementObj.value)) == true && isReal(trim(elementObj.value)) == false) {
                    activateSection(formelem);
                    if (formelem.elemerrmessage == '')
                        ret = confirm(formelem.elemdisplayname + ' if entered, should be a valid decimal value.\nPossible values can be like 0 or 0.0\nPress "OK" to set the default value or "Cancel" to enter the appropriate value.');
                    else
                        ret = confirm(formelem.elemerrmessage);
                    if (ret == false) {
                        ;
                    }
                    else
                        elementObj.value = formelem.elemdefaultvalue;
                }
            }
            if (formelem.elemcheckfor == 5 && formelem.elemwarning == 1) // check for valid currency
            {
                if (isBlank(trim(elementObj.value)) == true && isDate(trim(elementObj.value)) == false) {
                    activateSection(formelem);
                    if (formelem.elemerrmessage == '')
                        ret = confirm(formelem.elemdisplayname + ' if entered, should be a valid date.\nPress "OK" to set the default value or "Cancel" to enter the appropriate value.');
                    else
                        ret = confirm(formelem.elemerrmessage);
                    if (ret == false) {
                        ;
                    }
                    else
                        elementObj.value = formelem.elemdefaultvalue;
                }
            }
            if (formelem.elemcheckfor == 6 && formelem.elemwarning == 1) // check for positive number
            {
                if (isBlank(trim(-elementObj.value)) == true && isPositive(trim(elementObj.value)) == false) {
                    activateSection(formelem);
                    if (formelem.elemerrmessage == '')
                        ret = confirm(formelem.elemdisplayname + ' if entered, should be a positive number greater than 0.\nPress "OK" to set the default value or "Cancel" to enter the appropriate value.');
                    else
                        ret = confirm(formelem.elemerrmessage);
                    if (ret == false) {
                        ;
                    }
                    else
                        elementObj.value = formelem.elemdefaultvalue;

                }
            }
        }
    }
    return { isvalid: ret, message: errorMsg };
}

function removeWhiteSpace(strValue) {
    return strValue.replace(/\s+/g, '');
}

function RepeatString(str, times) {
    return new Array(times + 1).join(str);
}
//------------------------------------------------ Cascading dropdown functions -----------------------------------
var cascadingTopFiltered = false;

function O(text, value, submenu) {
    this.text = text;
    this.value = value;
    this.length = 0;
    if (submenu != null) {
        // submenu is an array of options...
        for (var i = 0; i < submenu.length; ) {
            this[i] = submenu[i];
            this.length = ++i;
        }
    }
}

function updateCascadingDropDowns(elName, m, grpIndex, group) { // updates submenus - form(num)'s menu options, and all submenus
    // if refd form exists  
    with (document.forms[0].elements[elName]) {
        var selectedOption = 0;
        var selectedOptionText = '';

        for (var i = options.length - 1; 0 <= i; i--) {
            if (options[i].selected && i > 0) {
                //alert("@cascading-->" + group[grpIndex] + " has selected index " + i + " value = " + options[i].value);
                selectedOptionText = options[i].text;
            }
            options[i] = null; // null out options in reverse order (bug work-around)
        }
        for (var i = 0; i < m.length; i++) {
            options[i] = new Option(m[i].text, m[i].value); // fill up next menu's items
            if (removeWhiteSpace(m[i].text) == removeWhiteSpace(selectedOptionText)) {
                //alert(selectedOptionText);
                selectedOption = i; // to render child dropdown
                options[i].selected = true;
            }
        }

        /*
        if(options!=null && options.length) {
        options[selectedOption].selected = true; // default to 1st menu item, windows bug kludge
        }
        */
    }
    if (m[selectedOption] != null && m[selectedOption].length) {
        nxtElName = group[++grpIndex];
        updateCascadingDropDowns(nxtElName, m[selectedOption], grpIndex, group); // update subsequent form if any grandchild menu exists
    }

}

function updateTopDropDown(tree, group) {
    with (document.forms[0].elements[group[0]]) {
        var selectedOption = 0;
        var selectedOptionText = '';
        for (var i = options.length - 1; 0 <= i; i--) {
            if (options[i].selected && i > 0) {
                //alert("@update-->" + group[0] + " has selected index " + i);
                selectedOption = i;
                selectedOptionText = options[i].text;
            }
            options[i] = null; // null out options in reverse order (bug work-around)
        }

        for (var i = 0; i < tree.length; i++) {
            //alert(tree[i].text + " = " + tree[i].value);
            options[i] = new Option(tree[i].text, tree[i].value);
            if (removeWhiteSpace(tree[i].text) == removeWhiteSpace(selectedOptionText)) {
                //alert(selectedOptionText);
                selectedOption = i; // to render child dropdown
                options[i].selected = true;
            }
        }
        /*
        if (options!=null && options.length) {
        options[selectedOption].selected = true; // default to 1st menu item, windows bug kludge
        }
        */
    }
}

function relateCascadingDropDowns(tree, hierarchy, group) {

    if (!cascadingTopFiltered && tree != null) {
        cascadingTopFiltered = true;

        updateTopDropDown(tree, group);

    }

    var a = tree;        // set a to be the tree array      						

    var nxtElName;
    var grpIndex;

    for (grpIndex = 0; grpIndex < hierarchy; grpIndex++) {

        if (a == null) {
            break;
        }
        var sel = document.forms[0].elements[group[grpIndex]].selectedIndex;
        var selectedValue = document.forms[0].elements[group[grpIndex]].options[sel].value;
        if (grpIndex + 1 < group.length) {
            nxtElName = group[grpIndex + 1];
        }
        // get the child array using the selectedValue first and then if not found use the selectedIndex
        var treeFromValue = false;
        for (var i = 0; i < a.length; i++) {
            if (a[i].value == selectedValue) {
                a = a[i];
                treeFromValue = true;
                break;
            }
        }
        if (treeFromValue == false) {
            a = a[sel];
        }
    }

    if (a != null) {
        // if a array exists and it has elements,
        // feed update() w/ this record reference
        updateCascadingDropDowns(nxtElName, a, grpIndex, group);
        return;
    }

}


function RegisterDisableAdd(elementId) {
    var el = $(elementId);
    if (el && el.onchange)
        Event.observe(el, 'change', DisableAdd, false);
}

function submitForm() {
    //alert("about to submit form!!");
    document.forms[0].submit();
}

// limits the size of a textarea control.
// NOTE: this is required for the textarea control only.\n
function limitMaxLength(field, maxlimit) {
    if (field.value.length > maxlimit) // if too long...don't allow it!
        return false;

    return true;
}

// limits the size of a textarea control.
// NOTE: this is required for the textarea control only.\n
function trimMaxLength(field, maxlimit) {
    if (field.value.length > 0) {
        if (field.value.length > maxlimit) // if too long...trim it!
        {
            field.value = field.value.substring(0, maxlimit);
        }
    }
}

// used for manually firing builtin browser events like onchange and onclick
// do not include the "on" prefix of the event name
function fireEvent(element, event) {
    //
    // example usage for manually firing a dropdown's onchange event:
    // var el = document.getElementById("myDropDown");
    // fireEvent(el, 'change');
    //
    if (document.createEvent) {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
    else {
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on' + event, evt);
    }
}

/******************************************************************
* Begin Rich Text Editor Scripts
*******************************************************************/
function OpenTextEditor(varId, varHTMLId) {
    // bring up the editor in a modal dialog
    var iFrameUrl = "texteditor.aspx?varId=" + varId + "&HtmlId=" + varHTMLId;
    var formPrompt = ShortenString(allFormElementsIdMap[varHTMLId].elemdisplayname);
    
    var w = 550;
    var h = 435;
    var maxWidth = 760;
    var maxHeight = 600;
    if (typeof (jQuery) !== 'undefined') {
        w = parseInt(0.80 * jQuery(window).width());
        h = parseInt(0.80 * jQuery(window).height());
        if (w > maxWidth)
            w = maxWidth;
        if (h > maxHeight)
            h = maxHeight;
        iFrameUrl += '&if_w=' + w + '&if_h=' + h;
    }

    jQuery.fn.colorbox({ width: w, height: h, iframe: true, href: iFrameUrl, open: true, overlayClose: false, scrollbars: false, opacity: 0.70, title: formPrompt });    
}

function OnEditorLoad(varHTMLId) {
    // load editor with form value    
    var content = document.getElementById(varHTMLId).value.replace(new RegExp("\\x13", "ig"), "");
    return content;
}

function OnEditorSave(varHTMLId, content, boxSize) {
    document.getElementById(varHTMLId).value = content.replace(new RegExp("\\x13", "ig"), "");
    // call the onChange handler to register for DisableAdd which will force user to preview
    DisableAddFromVersionedForm();
    // update the hyperlink displayed in the form after a value has been set
    EditorUpdateLink(varHTMLId, content, boxSize);
}

function EditorUpdateLink(varHTMLId, content, boxSize) {
    var el = document.getElementById(varHTMLId + '__richTextEditorLink');

    if (el != null) 
    {
        // Clear HTML tags and CRLF
        content = translateSpaceEntityFromFP(content, true);
        var stripContent = stripHTMLTags(content);
        stripContent = stripContent.replace(new RegExp("(\\r\\n|\\r|\\n|\\n\\r)", "ig"), "");

        // get the sample string to display in the hyperlink
        if (stripContent.length > (boxSize * 2))
            stripContent = stripContent.substring(0, (boxSize * 2) - 3)

        // split the string into 2 lines (only if line text is long) 
        if (stripContent.length < boxSize)
            el.innerHTML = stripContent;
        else {
            // Add ... if the text is longer than 2 lines of user defined BoxSize
            var line2 = stripContent.substring(boxSize);
            if (line2.length >= boxSize - 3)
                el.innerHTML = stripContent.substring(0, boxSize) + "\n" + stripContent.substring(boxSize) + "...";
            else
                el.innerHTML = stripContent.substring(0, boxSize) + "\n" + stripContent.substring(boxSize);
        }

        // hide/show button (show only when the fields is empty)
        var rteAddTextContainer = document.getElementById(varHTMLId + '__richTextEditorButtonDiv');
        var rteAddLinkContainer = document.getElementById(varHTMLId + '__richTextEditorLinkDiv');
        if (trim(stripContent).length > 0) {
            rteAddTextContainer.style.display = "none";
            rteAddLinkContainer.style.display = "";
        }
        else {
            rteAddTextContainer.style.display = "";
            rteAddLinkContainer.style.display = "none";
        }
    }
}

String.prototype.replaceAll = function(pcFrom, pcTo) {
    var c = this;
    while (c.match(pcFrom)) {
        c = c.replace(pcFrom, pcTo);
    }
    return c;
}

function translateSpaceEntityToFP(content) {
    var pattern = new RegExp("(</[ ]*[ibu]>)([ ]+)([^<]*)", "i");
    var match = pattern.exec(content);
    while (match) {
        var spaces = "<space count=" + match[2].length + ">";
        content = content.replace(match[0], match[1] + spaces + match[3]);
        match = pattern.exec(content);
    }     
    return content;
}

function translateSpaceEntityFromFP(content, isDesignMode) {
    content = content.replace(new RegExp(String.fromCharCode(19), "ig"), " "); // html view mode
    var space = " ";

    if (isDesignMode) {
        // design mode, handle spaces between entities/tags and replace with nbsp;
        var pattern = new RegExp("(<space count=)([*0123456789 ]+)(>)", "i");
        var match = pattern.exec(content);
        while (match) {
            var spaceCount = parseInt(match[2]);
            var spaces = RepeatString("&nbsp;", spaceCount);
            content = content.replace(match[1] + match[2] + match[3], spaces);
            match = pattern.exec(content);
        }
    }     
    return content;
}
function stripHTMLTags(content) {
    // Replace tags
    var newContent = content.replace(new RegExp("<(.|\\n)*?>", "ig"), "");
    // Replace Breaks - br
    newContent = newContent.replace(new RegExp("<br\\s*?/?>", "ig"), " ");

    return newContent;
}
/******************************************************************
* End Rich Text Editor Scripts
*******************************************************************/

function _stripExternalId(word) {
    if (word.length == 0)
        return word;

    word = word.replace(/\*\*apos\*\*/g, "'").replace(/\\\"/g, '"');
    var idType = word.indexOf('_') > -1 ? word.substring(0, word.indexOf('_')) : "";
    if (true == _isExternalIdType(idType)) {
        var idValueStartIndex = word.length > idType.length
                                    ? word.indexOf('_', idType.length)
                                    : -1;
        var idValueEndIndex = idValueStartIndex > -1 && word.length > idValueStartIndex
                                    ? word.indexOf('_', idValueStartIndex + 1)
                                    : -1;

        if (idValueStartIndex > -1 && idValueEndIndex > idValueStartIndex && word.length > idValueEndIndex)
            return word.substring(idValueEndIndex + 1);
    }
    return word;
}
function _isExternalIdType(idType) {
    idType = idType.toUpperCase();
    return idType == "VALID"
        || idType == "LIT"
        || idType == "EXTRINSICID"
        || idType == "LIBRARYIMGID"
        || idType == "IMGID"
        || idType == "W2P_LISTITEMIMG"
        || idType == "STYLEID"
        || idType == "CLRID"
        || idType == "FONTID"
        || idType == "PROFILEID"
        || idType == "LIBRARYCLRID";
}

function activateSection(formelem) {
	if (formelem.sectionIndex > -1 && jsPlugin != '') {
		var animationDisabled = false;
		if (jsPlugin == 'accordion' || jsPlugin == 'sections') {
			animationDisabled = true;
			jsPluginObj[jsPlugin]("option", { animated: false });
		}
		jsPluginObj[jsPlugin](jsPluginActivate, formelem.sectionIndex);
		if (animationDisabled) {
			jsPluginObj[jsPlugin]("option", { animated: "slide" });
		}
	}
}

function openSections(index) {
    if (arguments.length == 0)
        index = -1;

    if (jsPlugin == 'accordion' || jsPlugin == 'tabs')
        jsPluginObj[jsPlugin](jsPluginActivate, index);
    else if (jsPlugin != '')
        jsPluginObj[jsPlugin]('expand', index);
}

function openRequiredSections() {
    openSections(getRequiredSections());
}

function gotoSection(index, htmlId, hideQuickLinks) {
    openSections(index);
    if (htmlId)
        document.location.hash = htmlId;
    if (arguments.length >= 3 && hideQuickLinks == true)
        jQuery("#quickLinksWrapper").removeClass('hovering');
}

function getRequiredSections() {
    var msg = "";
    var idList = "";
    var formelem;
    for (var j = 0; j < allFormElements.length; j++) {
        formelem = allFormElements[j];
        if (formelem.elemisrequired == 1 && formelem.sectionIndex > -1) {

            if (("," + idList + ",").indexOf("," + formelem.sectionIndex + ",") > -1)
                continue;

            if (idList.length > 0)
                idList += ",";

            idList += formelem.sectionIndex;
        }
    }
    return idList;
}

function closeSections(index) {
    if (arguments.length == 0)
        index = -1;

    if (jsPlugin != '')
        jsPluginObj[jsPlugin]('collapse', index);
}

function addSection(doActivate) {
    if (nextSectionIdx > dynamicSectionIds.length) {
        jQuery('#addSectionWrapper').hide();
        return;
    }

    var section = dynamicSectionIds[nextSectionIdx];
    jQuery('#' + section.id).show();
    if (jsPlugin != '') {
        if (arguments.length == 0 || (arguments.length > 0 && typeof (doActivate) !== "undefined" && doActivate == true))
            jsPluginObj[jsPlugin](jsPluginActivate, section.index);
    }

    // update hidden state variables that track the latest visible section, 
    //   so we can open and show the correct sections on quickfill prefills and edit cart scenarios.
    jQuery('#w2p_visibleDynamicSectionIndex').val(nextSectionIdx);

    //var visibleSectionIndex = jQuery('#w2p_visibleDynamicSectionIndex').val();
    //alert("Set w2p_visibleDynamicSectionIndex.value to: " + visibleSectionIndex);
    
    if (useQuickLinks) {
        // need to add the new section to the quicklinks dropdown
        var onclick = "gotoSection(" + section.index + ",\"" + section.id + "\",true); return false;";
        var html = "<p><a id='" + section.id + "__quickLink' href='javascript:void(0);' onclick='" + onclick + "'>" + section.formPrompt + "</a></p>";
        jQuery('#quickLinksContent').append(html);
        if (nextSectionIdx == 0)
            jQuery('#quickLinksWrapper').show();
    }

    nextSectionIdx += 1;
    if (nextSectionIdx >= dynamicSectionIds.length) {
        jQuery('#addSectionWrapper').hide();
        return;
    }
}

function initDynamicSections() {
    var visibleSectionIndex = jQuery('#w2p_visibleDynamicSectionIndex').val();
    if (typeof (visibleSectionIndex) == "undefined" || visibleSectionIndex == null || visibleSectionIndex == "") {
        //alert("Dynamic section hidden state not found!!");
        return;
    }
    visibleSectionIndex = parseInt(visibleSectionIndex)+0;
    //alert("Dynamic section hidden state found - showing first [" + visibleSectionIndex+1 + "] sections");
    for (var i = 0; i <= visibleSectionIndex; i++) {
        var activateLastSection = i == visibleSectionIndex;
        addSection(activateLastSection);
    }
}

// We need to handle form fixed width.
// Since most sections are initially hidden, and we can't calculate width until it's visible, 
//   we have to wait for tab changes and then run the fix when it's first opened.
// We'll track whether we've fixed each section so we only do once
function onSectionChange(event, ui) {
    if (formFixedWidth > 0) {
        var contentId = null;
        if (jsPlugin == 'accordion' || jsPlugin == 'sections')
            contentId = jQuery(ui.newHeader).parent().attr('id');
        else if (jsPlugin == 'tabs')
            contentId = jQuery(ui.panel).attr('id');

        if (contentId != null && contentId.length > 0 && typeof (fixedSections[contentId]) === 'undefined') {
            fixedSections[contentId] = true;
            handleFormFixedWidth('#' + contentId);
        }
    }  
    recalcScrollProofIntoView();
}

function handleFormFixedWidth(parentId) {
    if (formFixedWidth <= 0)
        return;

    if (arguments.length == 0)
        parentId = "#w2p_form";

	var promptCellSelector = parentId + " table.poVariItemForm tr td.pflabel:first";
	var inputCellSelector = parentId + " table.poVariItemForm tr td.poFormOptions:first";
	var $promptCell = jQuery(promptCellSelector);
	var $inputCell = jQuery(inputCellSelector);
	var promptCellWidthOuter = $promptCell.outerWidth(true);
	var promptCellWidth = $promptCell.width();
	var inputCellWidthOuter = $inputCell.outerWidth(true);
	var inputCellWidth = $inputCell.width();

    var inputSelectors = parentId + " table.poVariItemForm tr td select"
                       + "," + parentId + " table.poVariItemForm tr td input[type=text]";
    jQuery(inputSelectors).each(function() {
        var element = jQuery(this);
        var w = parseInt(element.width());
        var outerW = parseInt(element.outerWidth(true));

        if (w > 0) {
            var padding = (inputCellWidthOuter - inputCellWidth) + (outerW - w);            
            if (jsPlugin != '')
                padding += 42; // 21 on each side

            var widthToCheck = columns == 1 ? outerW : promptCellWidthOuter + outerW;
            if (widthToCheck > formFixedWidth) {
                var newWidth = formFixedWidth - promptCellWidthOuter - padding;
                if (1 == columns) {
                    newWidth = formFixedWidth - padding;
                }
                if (newWidth > 0)
					element.width(newWidth);
            }
        }
    });
}

/***************** Begin ConditionalVisibility *****************/
var ConditionalVisibility;
if (typeof (Class) !== 'undefined') {
    ConditionalVisibility = Class.create();
}
else {
    ConditionalVisibility = {};
}
ConditionalVisibility.PARENTS = {};
ConditionalVisibility.getParent = function(parentControlId) {
    if (typeof (ConditionalVisibility.PARENTS[parentControlId]) == "undefined")
        return new ConditionalVisibility(parentControlId);

    return ConditionalVisibility.PARENTS[parentControlId];
};

ConditionalVisibility.prototype = {
    initialize: function(parentControlId) {
        this._parentControlId = parentControlId;
        this._parentControl = $(parentControlId);
        this._conditions = new Array();
        this._defaultCondition = null;
        this._switchEnabled = false;
        this._allChildren = new Array();
        this._allChildrenMap = new Array();

        if (typeof (ConditionalVisibility.PARENTS[parentControlId]) == "undefined") {
            //alert("ConditionalVisibility.initialize:: setting parent conditional visibility: [" + parentControlId + "]");
            ConditionalVisibility.PARENTS[parentControlId] = this;

            // register for dropdown list datasource changes
            if (typeof (CascadingDropDown) !== "undefined") {
                CascadingDropDown.CustomEventsEnabled = true;
                var eventId = CascadingDropDown.CustomEventsNamespace + parentControlId;
                Event.observe(document, eventId, this.executeBusinessLogic.bind(this));
            }
        }
    },

    get_SelectedValue: function() {
        if (this._parentControl.options.length == 0)
            return "";

        return this._parentControl.options[this._parentControl.selectedIndex].value;
    },

    addCondition: function(valuesToCheckFor, animationType, speed, childrenVisibility, children) {
        if (!this._parentControl.options || !children.length)
            return;

        var allowSwitch = true;
        var condition = { 'animationType': animationType, 'speed': speed, 'childrenVisibility': childrenVisibility, 'children': children, childrenMap: {} };
        for (var i = 0; i < children.length; i++) {
            var childId = children[i];
            if (typeof (condition.childrenMap[childId]) == "undefined")
                condition.childrenMap[childId] = childId;
        }

        for (var i = 0; i < valuesToCheckFor.length; i++) {
            var valueToCheckFor = valuesToCheckFor[i];
            var valueToCheckForSansExtId = _stripExternalId(valueToCheckFor);
            //alert("Checking on condition[" + valueToCheckFor + "]");

            if (typeof (this._conditions[valueToCheckFor]) == "undefined") {
                this._conditions[valueToCheckFor] = condition;

                //alert("Added condition[" + valueToCheckFor + "]");
                if (valueToCheckFor != valueToCheckForSansExtId) {
                    //if (typeof (this._conditions[valueToCheckForSansExtId]) == "undefined")
                    //  alert("ERROR: Already found stripped external ID value in condition map!!");
                    //else
                    this._conditions[valueToCheckForSansExtId] = condition;
                }

                if (this._defaultCondition == null) {
                    allowSwitch = false;
                    this._defaultCondition = condition;
                }
            }
        }

        if (allowSwitch && this._allChildren.length != children.length) {
            this._switchEnabled = true;
        }

        for (var i = 0; i < children.length; i++) {
            var childId = children[i];
            if (typeof (this._allChildrenMap[childId]) == "undefined") {
                this._allChildren.push(childId);
                this._allChildrenMap[childId] = childId;

                if (allowSwitch)
                    this._switchEnabled = true;
            }
        }
    },

    executeBusinessLogic: function() {
        var selectedCondition = null;
        var selectedValueInList = false;
        var i = 0;
        var selectedVal = this.get_SelectedValue();
        var selectedValSansExtId = _stripExternalId(selectedVal);

        if (typeof (this._conditions[selectedVal]) != "undefined") {
            selectedValueInList = true;
            selectedCondition = this._conditions[selectedVal];
        }
        else if (typeof (this._conditions[selectedValSansExtId]) != "undefined") {
            selectedValueInList = true;
            selectedCondition = this._conditions[selectedValSansExtId];
        }
        if (selectedCondition == null) {
            selectedCondition = this._defaultCondition;
        }

        // cache whether the fields are currently displayed or not
        var allowIsHidden = !this._switchEnabled;
        var isHidden = allowIsHidden && jQuery("#" + selectedCondition.children[0]).css('display') == 'none';

        // for each child linked to this parent
        for (var i = 0; i < this._allChildren.length; i++) {
            var childToCheck = this._allChildren[i];
            var childIsInRule = typeof (selectedCondition.childrenMap[childToCheck]) != "undefined";

            // (1) For "Show" Lists:
            //      * We want to show the fields when the selected value is in our "show" list;
            //      * If the field is not in the rule, then we want to Show it if the selectedValue is not in the list; if the selected value is in the list then we want to hide
            // (2) For "Hide" Lists:
            //      * We want to hide the fields when the selected value is in our "hide" list;
            //        In other words, we want to show the fields when the selected value is NOT in our "hide" list;
            //      * If the field is not in the rule, then we want to Hide it if the selectedValue is not in the list; if the selected value is in the list then we want to show            
            var showChild = (selectedCondition.childrenVisibility && selectedValueInList && childIsInRule)
                            || (!selectedCondition.childrenVisibility && !selectedValueInList && childIsInRule)
                            || (selectedCondition.childrenVisibility && !selectedValueInList && !childIsInRule && this._switchEnabled)
                            || (!selectedCondition.childrenVisibility && selectedValueInList && !childIsInRule && this._switchEnabled);

            // check if we want to show the child fields
            if (showChild) {
                if (allowIsHidden && !isHidden)
                    continue; // it's already visible, no need to show it

                // we want to show the fields when the selected value is in our list                
                handleConditionalVisibilityShow(childToCheck, selectedCondition.animationType, selectedCondition.speed);
            }
            else {
                // otherwise we want to hide them 
                if (allowIsHidden && isHidden)
                    continue; // it's already hidden, no need to hide it

                // we want to hide the fields when the selected value is in our list
                // otherwise the value is not in our "hide" list, so show them
                handleConditionalVisibilityHide(childToCheck, selectedCondition.animationType, selectedCondition.speed);
            }
        }
    }
};

function handleConditionalVisibilityShow(childId, animationType, speed) {
    var childRow = jQuery("#" + childId);
    var childTd;
    if (isIE6 || isIE7)
        childTd = jQuery("#" + childId + " td");

    switch (animationType) {
        case "fade":
            if (isLoaded) {
                if (childTd) {
                    childTd.hide();
                    childRow.show();
                    childTd.fadeIn(speed, function() { childRow.show(); removeTextAliasFilter(childTd); });
                }
                else
                    childRow.fadeIn(speed, function() { childRow.show(); removeTextAliasFilter(childRow); });
            }
            else
                childRow.show();
            break;
        case "slide":
            if (isLoaded) {
                if (childTd) {
                    childTd.hide();
                    childRow.show();
                    childTd.slideDown(speed, function() { childRow.show(); });
                }
                else
                    childRow.slideDown(speed, function() { childRow.show(); });
            }
            else
                childRow.show();
            break;
        case "highlight":
            childRow.show();
            if (isLoaded)
                childRow.effect("highlight", {}, speed);
            break;
        default:
            childRow.show();
            break;
    }
}

function handleConditionalVisibilityHide(childId, animationType, speed) {
    var childRow = jQuery("#" + childId);
    var childTd;
    if (isIE6 || isIE7)
        childTd = jQuery("#" + childId + " td");

    switch (animationType) {
        case "fade":
            if (isLoaded) {
                if (childTd)
                    childTd.fadeOut(speed, function() { childRow.hide(); });
                else
                    childRow.fadeOut(speed, function() { childRow.hide(); });
            }
            else
                childRow.hide();
            break;
        case "slide":
            if (isLoaded) {
                if (childTd)
                    childTd.slideUp(speed, function() { childRow.hide(); });
                else
                    childRow.slideUp(speed, function() { childRow.hide(); });
            }
            else
                childRow.hide();
            break;
        default:
            childRow.hide();
            break;
    }

    // clearing out child values
    if (isLoaded) {
        var childInputName = childId.replace(/_row_2/i, "").replace(/_row/i, "");
        var childUploadIndex = returnindex(childInputName + '__uploadImage', formName);

        if (childUploadIndex > -1)
            removeLocalImage(childUploadIndex, childInputName + '__uploadImageNote', childInputName, null);

        var jQueryObj = jQuery("#" + childInputName);
        if (jQueryObj && jQueryObj.length) {
            var type = jQueryObj[0].type;
            var tag = jQueryObj[0].tagName.toLowerCase(); // normalize case

            // it's ok to reset the value attr of text inputs and password inputs
            if (type == 'text' || type == 'password')
                jQueryObj[0].value = "";
            // if textarea check if its an RTE link is loaded Clear up the link text
            else if (tag == 'textarea') {
                jQueryObj[0].value = "";
                EditorUpdateLink(childInputName, "", 1);
            }
            // checkboxes and radios need to have their checked state cleared
            // but should *not* have their 'value' changed
            else if (type == 'checkbox' || type == 'radio')
                jQueryObj[0].checked = false;
            // select elements need to have their 'selectedIndex' property set to -1 or 0
            // (this works for both single and multiple select elements)
            else if (tag == 'select')
                jQueryObj[0].selectedIndex = 0;
        }
    }
}

function removeTextAliasFilter(jQueryElem) {
    if (isIE && jQueryElem) {
        jQueryElem.each(function() {
            try {
                jQuery(this).get(0).style.removeAttribute('filter');
            } catch (smother) { }
        });
    }
}
/***************** End ConditionalVisibility *****************/


/***************** Begin Sliding Previews *****************/
var $lastScrollEvent = null;
var $scrollEventDelay = 0;
function scrollProofIntoViewWithDelay() {
    $lastScrollEvent = new Date();
    pollForScrollProofIntoView();
}

function pollForScrollProofIntoView() {
    $scrollEventDelay = new Date() - $lastScrollEvent;
    if ($scrollEventDelay >= 400)
        scrollProofIntoView();
    else
        setTimeout(pollForScrollProofIntoView, 200);
}

var $win;
var $winHeight;
var $proof = null;
var $proofHeight = 0;
var $proofTopOrig = 0;
var $proofClientId = "tblProof";
var $proofParentContainerId = "tdProof";
var $maxOffsetTop = 0;
function scrollProofIntoView() {
    if ($proof == null) {
        $win = jQuery(window);
        $winHeight = $win.height();
        $proof = jQuery("#" + $proofClientId);
        $proofHeight = $proof.height();
        $proofTopOrig = $proof.offset().top;
        $maxOffsetTop = jQuery("#" + $proofParentContainerId).height() - $proofHeight;

        // if the window gets resized let's re-init our viewport height
        $win.bind("resize", function() {
            recalcScrollProofIntoView();
        });
    }

    var viewportTop = $win.scrollTop();
    var viewportBottom = viewportTop + $winHeight;

    var proofTop = $proof.offset().top;
    var proofBottom = proofTop + $proofHeight;

    var targetOffsetTop = viewportTop - $proofTopOrig;
    if (targetOffsetTop < 0)
        targetOffsetTop = 0;
    else if (targetOffsetTop > $maxOffsetTop)
        targetOffsetTop = $maxOffsetTop;

    var isInView = $proofHeight <= $winHeight
        ? viewportTop <= proofTop && viewportBottom >= proofBottom
        : proofTop < viewportBottom && proofBottom > viewportTop;
    var canPositionAtTop = isInView
                            && viewportTop <= $proofTopOrig
                            && viewportBottom >= ($proofTopOrig + $proofHeight)
                            && proofTop > $proofTopOrig;

    if (!isInView) {
        $proof.stop().animate({ marginTop: targetOffsetTop, speed: "fast" });
    } else if (canPositionAtTop) {
        $proof.stop().animate({ marginTop: 0, speed: "fast" });
    }
}

function recalcScrollProofIntoView(execScrollIntoView) {
    if ($proof != null) {
        $winHeight = $win.height();
        $proofHeight = $proof.height();
        $maxOffsetTop = jQuery("#" + $proofParentContainerId).height() - $proofHeight;
        scrollProofIntoViewWithDelay();
    }
}
/***************** End Sliding Previews *****************/


/***************** Start External Data Files *****************/
// function to upload image
function buildExternalDataFile() {  
    var page = 'CollectExternalDataFile.aspx';
    var w = "550";
    var h = "200";

    var iFrameUrl = page + '?CompanyID=' + companyid + '&product_id=' + categoryid + '&userID=' + userID;
    jQuery.fn.colorbox({ width: "90%", maxWidth: w, height: h, iframe: true, href: iFrameUrl, open: true, overlayClose: false, scrollbars: false, opacity: 0.70, title: false, showClose: false, escKey: false });
    dataFileCreateSuccess = false;
    DisableAddFromVersionedForm();
}

function ReturnCallCollectExternalDataFile(inputFieldId, datafileId) {    
    var XDFel = $(inputFieldId);
    XDFel.value = datafileId;
    dataFileCreateSuccess = true;
}

function ReturnCallCollectExternalDataFileError(errorMsg) {
    dataFileCreateSuccess = false;
    jQuery("#cb_error").html(errorMsg);
    jQuery.fn.colorbox({ width: "50%", inline: true, href: "#cb_error", open: true, overlayClose: true, scrollbars: true, opacity: 0.70, title: 'Error' });
}

function CheckExternalDataFile() {
    if (!autoDataFileCreateEnabled) {
        return true;
    }
    else {
        var XDel = $('mcc_xdf_datafileId')// 
        return dataFileCreateSuccess || XDel.value != "";
    }
}
/***************** Start External Data Files *****************/

