PRVD.APP.UC.PersonalizationSelection = function (htmlElementID) {
    this.ElementID = htmlElementID;
    this.Element = document.getElementById(this.ElementID);
    this.OnPersonalizationSelectionChangedEvent = new PRVD.CT.EVENTS.CustomEvent(this.ElementID + "_PersonalizationSelectionChangedEvent");
    this.PersonalizationValidationFailedEvent = new PRVD.CT.EVENTS.CustomEvent(this.ElementID + "_PersonalizationValidationFailedEvent");
    var grouptitlevalueElement = "";
    this.HandleTextChangedEvent = function (type, args, obj) {
        obj.UpdatePersonalizationText();
    };

    this.UpdatePersonalizationText = function () {
        personalizationText = "";

        for (var i = 0; i < this.FixedPersonalizationItems.length; i++) {
            if (this.FixedPersonalizationItems[i].ProductID.value == this.SelectedPersonalizationPID) {
                personalizationText += this.FixedPersonalizationItems[i].SelectedText;
            }
        }

        for (var i = 0; i < this.VariablePersonalizationItems.length; i++) {
            if (this.VariablePersonalizationItems[i].ProductID.value == this.SelectedPersonalizationPID) {
                personalizationText += this.VariablePersonalizationItems[i].SelectedText;
            }
        }

        this.PersonalizationTextElement.value = escape('<PersonalizationText ProductID=\"' + this.SelectedPersonalizationPID + '\">' + personalizationText + '</PersonalizationText>');
    };

    this.HandleItemSelectEvent = function (e, obj) {
        obj.SelectedPersonalizationPID = obj.PersonalizationSelectionDropDown.value.split(",")[0];
        obj.PersonalizedProdElement.value = obj.SelectedPersonalizationPID;
        obj.PersonalizedProdRelationElement.value = obj.PersonalizationSelectionDropDown.value.split(",")[1];
        obj.UpdatePersonalizationText();

        // this is for grouptitle



        if (obj.SelectedPersonalizationPID > "0") {

            for (var a = 0; a < grouptitlevalueElement.length; a++) {
                grouptitlevalueElement[a].style.display = "block";

            }
        }
        else {

            for (var a = 0; a < grouptitlevalueElement.length; a++) {

                grouptitlevalueElement[a].style.display = "none";

            }
        }
        // this is for grouptitle

        for (var i = 0; i < obj.FixedPersonalizationItems.length; i++) {
            if (obj.FixedPersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                obj.FixedPersonalizationItems[i].Show();
            }
            else {
                obj.FixedPersonalizationItems[i].Hide();
            }
        }
        i = null;

        for (var i = 0; i < obj.VariablePersonalizationItems.length; i++) {
            if (obj.VariablePersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                obj.VariablePersonalizationItems[i].Show();
            }
            else {
                obj.VariablePersonalizationItems[i].Hide();
            }
        }
        obj.OnPersonalizationSelectionChangedEvent.fire(obj.PersonalizationSelectionDropDown.value, obj.PersonalizationTextElement.value);
        i = null;
    };

    this.CheckError = function (e, obj) {
        var wasAllGood = true;

        if (obj.SelectedPersonalizationPID != "0") {
            for (var i = 0; i < obj.FixedPersonalizationItems.length; i++) {
                /*Check to see if the Product ID is selected*/
                if (obj.FixedPersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                    if (obj.FixedPersonalizationItems[i].HasError == "true") {
                        obj.FixedPersonalizationItems[i].ShowError();
                        wasAllGood = false;
                        PRVD.CT.EVENTS.Event.stopEvent(e);
                    }
                }
            }

            for (var i = 0; i < obj.VariablePersonalizationItems.length; i++) {
                /*Check to see if the Product ID is selected*/
                if (obj.VariablePersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                    if (obj.VariablePersonalizationItems[i].HasError == "true") {
                        obj.VariablePersonalizationItems[i].ShowError();
                        wasAllGood = false;
                        PRVD.CT.EVENTS.Event.stopEvent(e);
                    }
                }
            }
        }

        if (wasAllGood == false) {
            obj.PersonalizationValidationFailedEvent.fire();
        }
    };

    this.ShouldBuyNowBeBlocked = function (e, obj) {
        try {
            $("[prvdid='orderbutton']").css('cursor', 'pointer');
            if (obj.SelectedPersonalizationPID != "0") {
                for (var i = 0; i < obj.FixedPersonalizationItems.length; i++) {
                    /*Check to see if the Product ID is selected*/
                    if (obj.FixedPersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                        if (obj.FixedPersonalizationItems[i].HasError == "true") {
                            $("[prvdid='orderbutton']").css('cursor', 'not-allowed');
                            $("[prvdid='OrderNowError']").show();
                            i = obj.FixedPersonalizationItems.length;
                        }
                    }
                }

                for (var i = 0; i < obj.personalizationItems.length; i++) {
                    /*Check to see if the Product ID was selected*/
                    if (obj.VariablePersonalizationItems[i].ProductID.value == obj.SelectedPersonalizationPID) {
                        if (obj.VariablePersonalizationItems[i].HasError == "true") {
                            $("[prvdid='orderbutton']").css('cursor', 'not-allowed');
                            $("[prvdid='OrderNowError']").show();
                            i = obj.VariablePersonalizationItems.length;
                        }
                    }
                }
            }
        }
        catch (exception) {

        }
    };

    this.ClearBuyNowSpecialTreatment = function (e, obj) {
        $("[prvdid='orderbutton']").css('cursor', 'pointer');
        $("[prvdid='OrderNowError']").hide();
    };

    this.Clear = function () {
        while (this.Element.childNodes.length > 0) {
            this.Element.removeChild(this.Element.childNodes[0]);
        }
    };

    this.Reload = function (html) {
        this.Element.innerHTML = html;
        this.LoadMemoryObjects();
    };

    this.HandleVariableSeclectionChanged = function (type, args, obj) {
        obj.LoadMemoryObjects(true);
    };

    this.LoadMemoryObjects = function (isResultOfVariableSelctorRefresh) {
        if (PRVD.CT.UT.GetElementsByPrvdName(this.Element, "personalizationtext").length > 0) {
            this.PersonalizationTextElement = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "personalizationtext")[0];
            this.PersonalizedProdRelationElement = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "selectedpersonalizedproductrelationid")[0];
            this.PersonalizedProdElement = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "selectedpersonalizedproductid")[0];
            this.SelectedPersonalizationPID = this.PersonalizedProdElement.value;

            grouptitlevalueElement = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "grouptitlevalue");
            if (PRVD.CT.UT.GetElementsByPrvdName(this.Element, "ddlpersonalizationproducts").length > 0) {
                this.PersonalizationSelectionDropDown = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "ddlpersonalizationproducts")[0];
            }
            this.VariableGroupSelectorsList = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "variablegroupselector");


            this.VariableGroupSelectors = new Array(this.VariableGroupSelectorsList.length);
            for (var j = 0; j < this.VariableGroupSelectorsList.length; j++) {
                this.VariableGroupSelectors[j] = new PRVD.APP.UC.PersonalizationVariableGroupSelector(this.VariableGroupSelectorsList[j].id, this.SelectedPersonalizationPID);
                this.VariableGroupSelectors[j].SelectionChangeEvent.subscribe(this.HandleVariableSeclectionChanged, this);
            }
            j = null;

            variableItemList = $("#variableLineItemsHolder [prvdid='personalizationitem']");

            if (isResultOfVariableSelctorRefresh == null || isResultOfVariableSelctorRefresh == false) {
                fixeditemList = $("[prvdid='personalizationitem']", this.Element).not(variableItemList);
                this.FixedPersonalizationItems = new Array(fixeditemList.count);
                for (var i = 0; i < fixeditemList.length; i++) {
                    this.FixedPersonalizationItems[i] = new PRVD.APP.UC.PersonalizationItem(fixeditemList[i].id, i);
                    this.FixedPersonalizationItems[i].UpdatePersonalizationText();
                    this.FixedPersonalizationItems[i].TextChangeEvent.subscribe(this.HandleTextChangedEvent, this);
                }
                fixeditemList = null;
                i = null;
            }

            if (this.VariablePersonalizationItems != null && this.VariablePersonalizationItems.length > 0) {
                for (var k = 0; k < this.VariablePersonalizationItems.length; k++) {
                    this.VariablePersonalizationItems[k] = null;
                }
                k = null;
            }

            this.VariablePersonalizationItems = new Array(variableItemList.length);
            for (var i = 0; i < variableItemList.length; i++) {
                this.VariablePersonalizationItems[i] = new PRVD.APP.UC.PersonalizationItem(variableItemList.eq(i).attr('id'), variableItemList.get(i));
                this.VariablePersonalizationItems[i].UpdatePersonalizationText();
                this.VariablePersonalizationItems[i].TextChangeEvent.subscribe(this.HandleTextChangedEvent, this);
            }
            variableItemList = null;
            i = null;

            this.UpdatePersonalizationText();

            if (this.PersonalizationSelectionDropDown) {
                // this is for hide the personlizion on page load
                this.SelectedPersonalizationPID = this.PersonalizationSelectionDropDown.value.split(",")[0];
                this.PersonalizedProdElement.value = this.SelectedPersonalizationPID;
                this.PersonalizedProdRelationElement.value = this.PersonalizationSelectionDropDown.value.split(",")[1];
                this.UpdatePersonalizationText();

                for (var i = 0; i < this.FixedPersonalizationItems.length; i++) {
                    if (this.FixedPersonalizationItems[i].ProductID.value == this.SelectedPersonalizationPID) {
                        this.FixedPersonalizationItems[i].Show();
                    }
                    else {
                        this.FixedPersonalizationItems[i].Hide();
                    }
                }
                // this is for hide the personlizion on page load

                PRVD.CT.EVENTS.Event.addListener(this.PersonalizationSelectionDropDown.id, "change", this.HandleItemSelectEvent, this, false);
                // this is for hide and show GroupTitleText
                if (this.SelectedPersonalizationPID == "0") {
                    for (var a = 0; a < grouptitlevalueElement.length; a++) {
                        grouptitlevalueElement[a].style.display = "none";

                    }
                }
                else {
                    for (var a = 0; a < grouptitlevalueElement.length; a++) {
                        grouptitlevalueElement[a].style.display = "block";

                    }
                }
                // this is for hide and show GroupTitleText
            }

            if (document.getElementsByTagName) {
                /*var objForm = document.getElementsByTagName('form');*/
                var objForm = $("form").not(".ThirdPartyContainer form");
                PRVD.CT.EVENTS.Event.addListener(objForm, "submit", this.CheckError, this, false);
            }

            if (isResultOfVariableSelctorRefresh != null && isResultOfVariableSelctorRefresh == true) {
                PRVD.APP.UC.PrepFlashWrappers("#" + this.VariableGroupSelectors[0].PlaceHolder.id);
            }
            else {
                PRVD.APP.UC.PrepFlashWrappers();
            }

            if ($("#ConfirmPersonalizationCorrectMessage").length > 0) {
                $("#ConfirmPersonalizationCorrectMessage").show();
                $("#Form1").submit(PRVD.APP.PB.UCConfirmPersonalizationIsCorrect.checkForConfirmation);
            }

            if ($("[prvdid='OrderNowError']").length > 0) {
                var scopeHolder = this;
                $("div[prvdid='orderbuttoncontainer']").mouseenter(function (eventObj) {
                    scopeHolder.ShouldBuyNowBeBlocked(eventObj, scopeHolder);
                }).mouseleave(function (eventObj) {
                    scopeHolder.ClearBuyNowSpecialTreatment(eventObj, scopeHolder);
                });
            }
        }
        else {
            /* clear out any variables that may hold up submission if they aren't needed after a reload */
            this.FixedPersonalizationLineItems = new Array();
            this.VariablePersonalizationItems = new Array();
            this.VariableGroupSelectors = new Array();

            if ($("#ConfirmPersonalizationCorrectMessage").length > 0) {
                $("#ConfirmPersonalizationCorrectMessage").hide();
                $("#confirmPersonalizationErrorMessage").hide();
            }
        }
    };

    this.LoadMemoryObjects();
};


PRVD.APP.UC.PersonalizationVariableGroupSelector = function (htmlElementID, productID) {

    this.ElementID = htmlElementID;
    this.Element = document.getElementById(this.ElementID);
    this.DropDownElement = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "variabledropdown")[0];
    this.PlaceHolder = $("#" + this.ElementID + " + [prvdid='variablelineitemsholder']")[0];
    this.SelectionChangeEvent = new PRVD.CT.EVENTS.CustomEvent(this.ElementID + "_SelectionChangeEvent");
    this.SelectedPersonalizationPID = productID;

    this.HandleVariableSelectorChangedEvent = function (e, obj) {
        $("#" + obj.DropDownElement.id).attr('disabled', 'disabled');
        $("body").css('cursor', 'wait');

        if (document.ProductDetailAppDS.DefaultValues.Rows[0].PartnerID == "RED") {

            var e = document.getElementById("productDetailBodyD_productpersonalization__dropDownList");
            var selectedvalue = e.options[e.selectedIndex].value.split(",");
           
            obj.SelectedPersonalizationPID = selectedvalue[0];
        }
      

        PRVD.CT.AJAX.CallServer("GET", PRVD.CT.CONFIG.PRODUCTDETAILSPRODUCTCATALOGSERVICEPATH + PRVD.CT.CONFIG.PRODUCTDETAILSCWS_GETVARIABLEPERSONALIZATIONPATH + "?PersonalizationProductID=" + obj.SelectedPersonalizationPID + "&NumberOfGroupsToRetrieve=" + this.value + "&PartnerID=" + document.ProductDetailAppDS.DefaultValues.Rows[0].PartnerID, "", obj.HandleVariableSelectorChangedFinished, obj.ErrorCallBack, obj, false);
    };

    this.HandleVariableSelectorChangedFinished = function (request) {
        /* set the new html data */
        div = document.createElement("div");
        div.innerHTML = request.responseText.replace('<string xmlns="http://tempuri.org/">', '').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
        elementToReplace = document.getElementById(this.PlaceHolder.id);
        /* for firefox, must strip out any white space nodes */
        while (elementToReplace.childNodes.length > 0) {
            elementToReplace.removeChild(elementToReplace.firstChild);
        }
        elementToReplace.appendChild(div, elementToReplace);
        div = null;
        elementToReplace = null;
        elementsToReplace = null;
        /* fire the event to reload the parent object */
        this.SelectionChangeEvent.fire();
    };

    this.ErrorCallBack = function (xmlhttp, err) {
        $("#" + this.DropDownElement.id).removeAttr('disabled');
        $("body").css('cursor', 'default');

        if (document.ProductDetailAppDS.DefaultValues.Rows[0].PartnerID != "RED");
        {
            alert("There was a problem communicating with the server. Please wait a moment and try again your selection again.");
        }
       
    };

    PRVD.CT.EVENTS.Event.addListener(this.DropDownElement, "change", this.HandleVariableSelectorChangedEvent, this, false);
    $("#" + this.DropDownElement.id).removeAttr('disabled');
    $("body").css('cursor', 'default');

};

PRVD.APP.UC.PersonalizationItem = function (htmlElementID, iElementNumberInList) {
    this.ElementID = htmlElementID;
    this.Element = document.getElementById(this.ElementID);
    this.ElementNumberInList = iElementNumberInList;
    this.ItemName = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "itemname")[0];
    this.ItemText = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "itemtext")[0];
    this.FileName = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "filename")[0];
    this.SortOrder = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "sortorder")[0];
    this.ItemCode = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "itemcode")[0];
    this.ItemType = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "itemtype")[0];
    this.OptionGroupCode = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "optiongroupcode")[0];
    this.FulfillmentSequence = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "fulfillmentsequence")[0];
    this.ProductID = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "personalizationProductID")[0];
    this.ErrorPanel = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "itemerror")[0];
    this.ValidationExp = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "regex")[0];
    this.ViewChoicesButton = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "viewchoicesbutton");
    this.ViewChoicesPane = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "viewchoicespane");
    this.IconPlaceHolder = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "iconplaceholder");
    this.CloseViewChoicesButton = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "closechoicespane");
    this.CharactersLeftCounterMessage = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "charsleftmessage");
    this.MaxCharacterCount = PRVD.CT.UT.GetElementsByPrvdName(this.Element, "maxcount");
    this.HasError = "true";
    this.SelectedText = "";
    this.IconsAlreadyBound = false;
    this.ViewChoicesDialogAlreadyOpen = false;
    this.TextChangeEvent = new PRVD.CT.EVENTS.CustomEvent(this.ElementID + "_TextChangeEvent");


    this.Show = function () {
        this.Element.style.display = "inline";
    };

    this.Hide = function () {
        this.Element.style.display = "none";
    };

    this.ShowError = function () {
        this.HasError = "true";
        this.ErrorPanel.style.display = "block";
    };

    this.HideError = function () {
        this.HasError = "false";
        this.ErrorPanel.style.display = "none";
    };

    this.HandleTextChange = function (e, obj) {
        var regexp = new RegExp(obj.ValidationExp.value);
        if (regexp.test(obj.ItemText.value)) {
            obj.HideError();
            obj.UpdatePersonalizationText();
            obj.TextChangeEvent.fire(obj.ElementNumberInList, obj.SelectedText);
        }
        else {
            obj.ShowError();
        }
    };

    this.HandleTextChangeForImage = function (obj) {

        var isRequired = (obj.ValidationExp.value.indexOf('+') > -1);
        var currentState = $("#" + obj.ElementID + " .state").val();

        var regexp = new RegExp(obj.ValidationExp.value);
        if (regexp.test(obj.ItemText.value)) {
            obj.HideError();
            obj.UpdatePersonalizationText();

            switch (currentState) {
                case 'UPLOADED':
                    $("#" + obj.ErrorPanel.id).html("Please crop the image as needed before continuing, or just click 'DONE' to accept the default");
                    obj.HasError = "true";
                    break;

                case 'CROPPING':
                    $("#" + obj.ErrorPanel.id).html("Please finish cropping the image and click 'DONE' before continuing");
                    obj.HasError = "true";
                    break;

                case 'CROPPED':
                    break;

                default:
                    break;
            }

            obj.TextChangeEvent.fire(obj.ElementNumberInList, obj.SelectedText);
        }
        else {

            switch (currentState) {
                case '':
                    if (isRequired == true) {
                        obj.HasError = "true";
                    }
                    break;

                case 'SELECTED':
                    if (isRequired == true) {
                        $("#" + obj.ErrorPanel.id).html("Please upload the image using the button to the right before continuing");
                        obj.HasError = "true";
                    }
                    else {
                        $("#" + obj.ErrorPanel.id).html("Please upload the image using the button to the right before continuing, or remove the image");
                        obj.HasError = "true";
                    }
                    break;

                case 'UPLOADING':
                    if (isRequired == true) {
                        $("#" + obj.ErrorPanel.id).html("Please let the image finish uploading before continuing");
                        obj.HasError = "true";
                    }
                    else {
                        $("#" + obj.ErrorPanel.id).html("Please let the image finish uploading before continuing");
                        obj.HasError = "true";
                    }
                    break;

                case 'UPLOADED':
                    if (isRequired == true) {
                        $("#" + obj.ErrorPanel.id).html("Please crop the image as needed before continuing");
                        obj.HasError = "true";
                    }
                    break;

                case 'CROPPING':
                    if (isRequired == true) {
                        $("#" + obj.ErrorPanel.id).html("Please finish cropping the image and click 'DONE' before continuing");
                        obj.HasError = "true";
                    }
                    else {
                        $("#" + obj.ErrorPanel.id).html("Please finish cropping the image and click 'DONE' before continuing");
                        obj.HasError = "true";
                    }
                    break;

                case 'CROPPED':
                    /* case shouldn't happen */
                    break;

                default:
                    break;
            }
        }
    };

    this.ShowViewChoicesPane = function (e, obj) {
        if (obj.ViewChoicesDialogAlreadyOpen == false) {
            hideFormInputElements();
            if (obj.IconsAlreadyBound == false) {
                $("#" + obj.ViewChoicesPane[0].id).dialog('destroy');
                obj.ClonedOverlayHandle = $("#" + obj.ViewChoicesPane[0].id, obj.Element).clone();
                obj.ClonedOverlayHandle.dialog({ autoOpen: false, closeText: 'Close Window', draggable: false, modal: true, position: 'center', resizable: false, width: 670, dialogClass: 'persIconOverlay', beforeclose: function (event, ui) { showFormInputElements(); } });
                var iconsForThisItem = $("[prvdid='iconinoverlay']", obj.ClonedOverlayHandle).hover(function () { $(this).addClass("iconChoiceHover"); }, function () { $(this).removeClass("iconChoiceHover"); });

                for (var i = 0; i < iconsForThisItem.length; i++) {
                    PRVD.CT.EVENTS.Event.addListener(iconsForThisItem[i], "click", obj.SelectIconValueFromOverlay, obj, false);
                }
                i = null;
                obj.IconsAlreadyBound = true;
            }
            obj.ViewChoicesDialogAlreadyOpen = true;
            obj.ClonedOverlayHandle.dialog("open");
            obj.ViewChoicesDialogAlreadyOpen = false;
            
            $(".ui-widget-overlay").live("click", function () {
                $(obj.ClonedOverlayHandle).dialog("close");
            });
        }
    };

    this.CloseViewChoicesPane = function (e, obj) {
        if (obj.ViewChoicesDialogAlreadyOpen == true) {
            obj.ClonedOverlayHandle.dialog("close");
            obj.ViewChoicesDialogAlreadyOpen = false;
        }
    };

    this.UpdateCharsLeftCounterMessage = function (e, obj) {
        if (obj.MaxCharacterCount.length > 0) {
            if (obj.ItemText.value == "") {
                obj.CharactersLeftCounterMessage[0].innerHTML = obj.MaxCharacterCount[0].value + " characters max";
            }
            else {
                ;
                obj.CharactersLeftCounterMessage[0].innerHTML = (parseInt(obj.MaxCharacterCount[0].value) - parseInt(obj.ItemText.value.length)).toString() + " characters left";
            }
        }
    };

    this.UpdatePersonalizationText = function () {
        var displayName = this.ItemName.innerText || this.ItemName.textContent;

        if (this.ItemType != undefined) {
            /* not all fields are required, so if the itemtext is empty, don't add a line item for it */

            if ((this.ItemType.value == 'Icon')) {
                if (this.ItemText.selectedIndex > 0) {
                    /*split the value into filename and itemcode, and use the display text for itemtext */
                    this.FileName.value = this.ItemText.value.split(',')[0];
                    this.ItemCode.value = this.ItemText.value.split(',')[1];
                    this.SelectedText = "<LineItem SortOrder=\"" + this.SortOrder.value + "\" DisplayName=\"" + displayName + "\" ItemText=\"" + this.ItemText.options[this.ItemText.selectedIndex].text + "\" FileName=\"" + this.FileName.value + "\" ItemCode=\"" + this.ItemCode.value + "\" OptionGroupCode=\"" + this.OptionGroupCode.value + "\" FulfillmentSequence=\"" + this.FulfillmentSequence.value + "\" ItemType=\"" + this.ItemType.value + "\"  />";
                }
                else {
                    this.SelectedText = "";
                }
            }
            else if (this.ItemType.value == 'Text' && $('#' + this.ItemText.id).attr('tagName') == 'SELECT') {
                /* handle non icon dropdowns  */
                if (this.ItemText.selectedIndex > 0) {
                    this.ItemCode.value = this.ItemText.value;
                    this.SelectedText = "<LineItem SortOrder=\"" + this.SortOrder.value + "\" DisplayName=\"" + displayName + "\" ItemText=\"" + this.ItemText.options[this.ItemText.selectedIndex].text + "\" FileName=\"" + this.FileName.value + "\" ItemCode=\"" + this.ItemCode.value + "\" OptionGroupCode=\"" + this.OptionGroupCode.value + "\" FulfillmentSequence=\"" + this.FulfillmentSequence.value + "\" ItemType=\"" + this.ItemType.value + "\"  />";
                }
                else {
                    this.SelectedText = "";
                }
            }
            else {
                /* handle text fields */
                if (this.ItemText != "") {
                    this.SelectedText = "<LineItem SortOrder=\"" + this.SortOrder.value + "\" DisplayName=\"" + displayName + "\" ItemText=\"" + this.ItemText.value + "\" FileName=\"" + this.FileName.value + "\" ItemCode=\"" + this.ItemCode.value + "\" OptionGroupCode=\"" + this.OptionGroupCode.value + "\" FulfillmentSequence=\"" + this.FulfillmentSequence.value + "\" ItemType=\"" + this.ItemType.value + "\"  />";
                }
                else {
                    this.SelectedText = "";
                }
            }
        }
        else {
            /* legacy RED handling for now, will need to be updated */
            this.SelectedText = "<LineItem SortOrder=\"" + this.SortOrder.value + "\" DisplayName=\"" + displayName + "\" ItemText=\"" + this.ItemText.value + "\" FileName=\"\" ItemCode=\"\" OptionGroupCode=\"\" FulfillmentSequence=\"\" ItemType=\"Text\"  />";
        }
    };

    this.SelectIconValueFromOverlay = function (e, obj) {
        $("#" + obj.ItemText.id).val($("#" + this.id + " > img").attr('alt'));
        $(".iconChoiceInOverlay", obj.ClonedOverlayHandle).removeClass('iconChoiceSelected');
        $("#" + this.id, obj.ClonedOverlayHandle).addClass('iconChoiceSelected');
        obj.ClonedOverlayHandle.dialog("close");
        obj.ViewChoicesDialogAlreadyOpen = false;
        $("#" + obj.ItemText.id).focus();
        $("#" + obj.ItemText.id).blur();

        $(PRVD.CT.UT.GetElementsByPrvdName(obj.Element, "iconplaceholder")[0]).css({ 'background-image': 'url(' + $("#" + this.id + " > img").attr('src') + ')', 'background-position': '0px 0px', 'background-repeat': 'no-repeat' });
    };

    this.SelectIconValueFromDropDown = function (e, obj) {
        var imagePath = $("#" + obj.ViewChoicesPane[0].id + " [alt='" + this.options[this.selectedIndex].text + "']").attr('src');
        $("#" + obj.ViewChoicesPane[0].id + " .iconChoiceInOverlay").removeClass('iconChoiceSelected');
        $("#" + obj.ViewChoicesPane[0].id + " .iconChoiceInOverlay:has([alt='" + this.options[this.selectedIndex].text + "'])").addClass('iconChoiceSelected');
        $(PRVD.CT.UT.GetElementsByPrvdName(obj.Element, "iconplaceholder")[0]).css({ 'background-image': 'url(' + imagePath + ')', 'background-position': '0px 0px', 'background-repeat': 'no-repeat' });
    };

    switch ($('#' + this.ItemText.id).attr('tagName')) {
        case 'INPUT':
            if (this.ItemType && this.ItemType.value == 'Image') {
                var scopeVariable = this;
                $("#" + this.ItemText.id).change(function () { scopeVariable.HandleTextChangeForImage(scopeVariable) });
                $("#" + this.ElementID + " .state").change(function () { scopeVariable.HandleTextChangeForImage(scopeVariable) });
            }
            else {
                PRVD.CT.EVENTS.Event.addListener(this.ItemText, "blur", this.HandleTextChange, this, false);
                if (this.CharactersLeftCounterMessage.length > 0) {
                    PRVD.CT.EVENTS.Event.addListener(this.ItemText, "keyup", this.UpdateCharsLeftCounterMessage, this, false);
                }
            }
            break;

        case 'SELECT':
            if (this.ItemType.value == 'Icon') {
                PRVD.CT.EVENTS.Event.addListener(this.ItemText, "change", this.SelectIconValueFromDropDown, this, false);

                /* has to be after above loop since creating the dialog moves the div in the DOM out of the scope of this object */
                /* check for empty list in case this is after a reload and the dialog has already been bound */
                /*if (this.ViewChoicesPane.length > 0) {
                $("#" + this.ViewChoicesPane[0].id).dialog({ autoOpen: false, closeText: 'Close Window', draggable: false, height: 500, maxHeight: 500, modal: true, position: 'center', resizable: false, width: 800 });
                }
                moved from this location because IE6 chokes on the dialog call at this point. this is because IE6 cannot handle changing the dom above the
                parent of an element before it has completely loaded the element being manipulated. the jquery ui dialog call causes the div being made
                into a dialog to move in the DOM, thereby causing the exception. thus, the dialog creation for these choices panes has been moved to the following
                two locations until such time as we no longer support IE6:
                1) a document.ready() event for the panes visible on the page when it is first rendered.
                2) in the HandleVariableSelctorChanged event, in case new elements were added to the page
                */
                if (this.ViewChoicesButton != undefined && this.ViewChoicesButton.length > 0) {
                    PRVD.CT.EVENTS.Event.addListener(this.ViewChoicesButton[0], "click", this.ShowViewChoicesPane, this, false);
                }
                if (this.IconPlaceHolder != undefined && this.IconPlaceHolder.length > 0) {
                    PRVD.CT.EVENTS.Event.addListener(this.IconPlaceHolder[0], "click", this.ShowViewChoicesPane, this, false);
                }

            }
            PRVD.CT.EVENTS.Event.addListener(this.ItemText, "blur", this.HandleTextChange, this, false);
            break;
    }

    /* retest on object intialization since this may be after a reload and the data could be good already */
    var regexp = new RegExp(this.ValidationExp.value);
    if (regexp.test(this.ItemText.value)) {
        this.HideError();
    }

    this.UpdateCharsLeftCounterMessage(null, this);

};

PRVD.APP.UC.PrepFlashWrappers = function (optionalRootElement) {
    /* Add the flash image upload object to each of the .flashWrapper > .imageUploader elements. */
    var selector = "";
    if (optionalRootElement != null) {
        selector = optionalRootElement + " .flashWrapper";
    }
    else {
        selector = ".flashWrapper";
    }

    var wrappers = $(selector);
    for (i = 0; i < wrappers.length; i++) {
        var wrapper = wrappers.eq(i);
        wrapper.find(".imageUploader").flash(createImageUploaderFlashArguments(wrapper.attr('id')));
    }
};

PRVD.APP.UC.BindIconOverlays = function () {
    var panes = $("[prvdid='viewchoicespane']");
    for (var i = 0; i < panes.length; i++) {
        panes.eq(i).clone().dialog({ autoOpen: false, closeText: 'Close Window', draggable: false, modal: true, position: 'center', resizable: false, width: 670, dialogClass: 'persIconOverlay', beforeclose: function (event, ui) { showFormInputElements(); } });
    }
    i = null;

    $(".iconChoiceInOverlay").hover(
		function () {
		    $(this).addClass("iconChoiceHover");
		},
		function () {
		    $(this).removeClass("iconChoiceHover");
		}
	);

};

$(document).ready(function () {
    /* Clear existing state*/
    $(".aspect, .state, .name").val("");
});



/*****
BEGIN: Utility Methods used by flash
*****/
/* note: do not pass a specific movie name id below--one is assigned programmatically, and we require each flash to have a unique id. */
function createImageUploaderFlashArguments(parentName) {
    var flashArguments = {
        hasVersion: 10,
        expressInstall: PRVD.CT.CONFIG.PRODUCTDETAILS_FLASHAPPPATH + '/ExpressInstall/expressInstall.swf',
        hasVersionFail: function () {
            if ($.flash.available) {
                $(parentName).css('display', 'none');
                $(".BeforePickPanel, .DefaultImage").hide();
                return true;
            } else {
                $(".flashWrapper").children().hide();
                $(".flashWrapper").eq(0).append(
					"<div class='errorMsg hasError'>We have detected that you do not have the Flash 10 player installed. Please download the latest Flash plug in to use this page.</div>" +
					"<a href='http://www.adobe.com/go/getflashplayer/' target='_blank'><img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>");
                return false;
            }
        },
        swf: PRVD.CT.CONFIG.PRODUCTDETAILS_FLASHAPPPATH + '/ImageUploader/ImageUploader.swf',
        width: 450,
        height: 150,
        allowscriptaccess: 'always',
        wmode: 'transparent',
        flashvars: {
            wrapperName: parentName,
            uploadServiceURL: PRVD.CT.CONFIG.PRODUCTDETAILS_CUSTOMERIMAGEUPLOADSERVICEPATH.split('?')[0] + PRVD.CT.CONFIG.PRODUCTDETAILS_UPLOADAPPPATH
        },
        attributes: {}
    };
    return flashArguments;
}

/* note: do not pass a specific movie name id below--one is assigned programmatically, and we require each flash to have a unique id. */
function createImageCropperFlashArguments(parentName) {
    var expectedAspect = $(parentName).find("[prvdid='expectedaspectratio']").val().toString();
    if (expectedAspect.length == 0) {
        expectedAspect = 1;
    }

    var flashArguments = {
        swf: PRVD.CT.CONFIG.PRODUCTDETAILS_FLASHAPPPATH + '/PCAResize/PCAResize.swf',
        width: 400,
        height: 310,
        allowscriptaccess: 'always',
        wmode: 'transparent',
        flashvars: {
            wrapperName: parentName,
            imageName: PRVD.CT.CONFIG.PERSONALIZATIONIMAGEITEMUPLOADURLPATH.split('?')[0] + $(parentName).find(".name").val(),
            headerName: ' ',
            defaultPercent: 1,
            maskAspect: expectedAspect,
            imageAspect: $(parentName).find(".aspect").val(),
            cropServiceURL: PRVD.CT.CONFIG.PRODUCTDETAILS_CUSTOMERIMAGEUPLOADSERVICEPATH.split('?')[0] + PRVD.CT.CONFIG.PRODUCTDETAILS_CROPAPPPATH
        },
        attributes: {}
    };
    return flashArguments;
}

function setInputValue(jQuerySelector, value) {
    $(jQuerySelector).val(value);
    $(jQuerySelector).change();
}

/* Set the inner html of a specified jquery object 
optional parameter "append" adds the specified value to the end of the existing value.
default behavior is to replace the existing value with the value specified.
*/
function setHtmlValue(jQuerySelector, value, append) {
    if (arguments.length == 3) {
        if (append == "true") {
            node = $(jQuerySelector);
            node.html(node.html() + "<div>" + value + "</div>");
        } else {
            $(jQuerySelector).html(value);
        }
    } else {
        $(jQuerySelector).html(value);
    }

    if (jQuerySelector.indexOf('.errorMsg') > -1) {
        if (value != '') {
            $(jQuerySelector).addClass('hasError');
            $(jQuerySelector).html("<div class='errorIcon'></div>" + node.html());
        } else {
            $(jQuerySelector).removeClass('hasError');
        }
    }
}

function setStateClassName(jQuerySelector, stateClass) {
    $(jQuerySelector).attr("class", "flashWrapper").addClass(stateClass);
}


/*
Crop Queue Function collection 
Images specified by the image uploader need to be cropped to the propper aspect ratio. We need to present a modal cropper widget to the 
user once these images have finished uploading to the server (this can happen in an unknown order and timing). The following functions 
establish a FIFO queue for images so that we can display the cropper widget for the images which have completed uploading.
TODO: rewrite in OO JS.
*/
var cropQueue = new Array();



function addToCropQueue(jQuerySelector) {
    /*
    cropQueue.push(jQuerySelector);
    if (cropReady() == "true") {
    cropDetermination();
    }
    */
    var bypassCrop = false;
    var expectedAspect = $(jQuerySelector).find("[prvdid='expectedaspectratio']").val().toString();
    if (expectedAspect.length == 0) {
        bypassCrop = true;
    }
    else if (GetQueryStringParam("IsOffsiteAdmin") != false) {
        bypassCrop = true;
    }
    else if (document.URL.indexOf("admin.") > -1) {
        bypassCrop = true;
    }
    if (bypassCrop == false) {
        showCropWidget(jQuerySelector);
    }
    else {
        $(jQuerySelector + " .state").val("CROPPED");
        $(jQuerySelector + " .state").change();
        var el = $(jQuerySelector).find(".imageUploader object, .imageUploader embed").attr("id");
        document.getElementById(el).doneCropping();
    }
}

function cropDetermination() {
    if (cropQueue.length > 0) {
        if (cropReady() == "false") {
            showCropWidget(cropQueue.shift());
        } else if (cropReady() == "true") {
            cropReady("false");
        }
    }
}

function cropReady(setVal) {
    if (arguments.length == 1) {
        $("#cropReady").val(setVal);
        $("#cropReady").change();
    }
    return $("#cropReady").val();
}

function showCropWidget(jQuerySelector) {
    $(jQuerySelector).find(".imageCropper").flash(createImageCropperFlashArguments(jQuerySelector));
}

function removeCropper(jQuerySelector) {
    $(jQuerySelector).find(".imageCropper").animate(
		{ height: '0' }, 300, 'swing', function () {
		    $(jQuerySelector).find(".imageCropper").hide();
		    /* remove the cropper widget...wait for a second to do it though, b/c needs to perform a couple of functions before closing. */
		    setTimeout(function () { $(jQuerySelector).find(".imageCropper").html("").show().css('height', 'inherit'); }, 1000);
		}
	);

    /* reveal the "change / edit" icon in the image uploader flash widget.		
    To do this we need to call the imageUploader's 'doneCropping' function, but the jQuery wrapper 
    prevents access to the callback function, so we have to get the element using the standard "getElementById".
    */
    var el = $(jQuerySelector).find(".imageUploader object, .imageUploader embed").attr("id");
    document.getElementById(el).doneCropping();
}

$().ready(
		function () {
		    $("body").append("<input type='hidden' id='cropReady' value='true' />");

		    $("#cropReady").change(
				function () {
				    cropDetermination();
				}
			);
		});

/* END crop queue functionality */


/*****
END: Utility Methods used by flash
*****/

