﻿// Hack para que en FF y Geko based browsers tengamos activeElement
function onElementFocused(e) {
    if ((!$.browser.msie) && e && e.target) {
        try {
            document.activeElement = e.target == document ? null : e.target;
        }
        catch (ex) {
        }
    }
}

if (document.addEventListener) {
    document.addEventListener("focus", Pb.Utils.createDelegate(this, onElementFocused), true);
}

function CmsBasePageEIP(aCmsDataMappingList, aContentVersionList, aTraceErrorList, aTextDataTypeId, aHtmlDataTypeId, aMultilineTextTypeId, aIsOnlineRequest, aMainContentId, aBackofficeUrl, aInitTime, aLoadingMsg,aEmptyImgUrl) {
    this.CmsDataMappingList = aCmsDataMappingList;
    this.ContentVersionList = aContentVersionList;
    this.TraceErrorList = aTraceErrorList;
    this.TextDataTypeId = aTextDataTypeId;
    this.HtmlDataTypeId = aHtmlDataTypeId;
    this.MultilineTextTypeId = aMultilineTextTypeId;
    this.IsOnlineRequest = aIsOnlineRequest;
    this.MainContentId = aMainContentId;
    this.BackofficeUrl = aBackofficeUrl;
    this.EmptyImgUrl = aEmptyImgUrl;
    this.FocusedElement = null;
    this.OnKeyPressEventHandler = null;
    this.contentViewerContainer = null;
    this.BufferMapping = null;

    this.GuidEmpty = "00000000-0000-0000-0000-000000000000";

    this.CtxMenuId = null;
    this.CtxMenuEnabled = false;
    this.NavigationEnabled = false;
    // layout properties
    this._tempDragItem;
    this._paletteParentId = null;
    this._loadingMsg = aLoadingMsg;
    this._ctxMenu = null;
    // event helper
    this._isToolbarClicked = false;
    
    this._onprompt = false;

    // para poder llamarnos desde los manejadores de eventos de control
    var self = this;

    // Controlar navegación de enlaces
    //    $(document).rightMouseDown(function(evt) {
    //        self.NavigationEnabled = true;
    //        self.ShowBackMsg("Navegación de enlaces activada.");
    //        return false;
    //    });
    //    $(document).rightMouseUp(function(evt) {
    //        self.NavigationEnabled = false;
    //        self.ShowBackMsg("Navegación de enlaces desactivada.");
    //        return false;
    //    });

    // delegado para mostrar mesajes en segundo plano
    // implementacion por defecto para que sea sobrescrita por el js de EIPUpperBar
    this.OnShowBackgroundMessage = function(aMessage) {
        $(".EIPBackgroundProgressInfo").hide().remove();
        var lDiv = $("<div class='EIPBackgroundProgressInfo RibbonNotification'>" + aMessage + "</div>").appendTo($("body")).maxZIndex();
        lDiv.fadeIn(1000, function() {
            lDiv.fadeOut(3000);
        });
    };

    this.OnSave = function() {
    };

    // suscribirnos a los eventos de teclado para negrita, subrayado, etc.
    $(document).bind('keydown', 'Ctrl+n',
            function(e) { return self.HtmlEditBoldHandler(e, self); }
        );
    $(document).bind('keydown', 'Ctrl+k',
            function(e) { return self.HtmlEditItalicHandler(e, self); }
        );
    $(document).bind('keydown', 'Ctrl+s',
            function(e) { return self.HtmlEditUnderlineHandler(e, self); }
        );
    $(document).bind('keydown', 'Ctrl+0',
            function(e) { return self.HtmlEditPastePlainTextHandler(e, self); }
        );

    $(document).bind('keydown', 'Return', function(e) {
        return self.HtmlEditCancelEnterHandler(e, self);
    });

    $(document).bind('keydown', 'Shift+Return', function(e) {
        return self.HtmlEditCancelShiftEnterHandler(e, self);
    });

    $(document).bind('keydown', 'Ctrl+Return', function(e) {
        return self.HtmlEditCancelCtrlEnterHandler(e, self);
    });

    this.InitTime = aInitTime;
    this.EnableEIP(true);
    this.BuildErrorTraceList();
}
// si ha cambiado, preguntar si guardar el valor
// hay que quitar las cositas del jQuery del valor antes de comparar
// \\sjquery[0-9]*=\"[^\"]*\"
CmsBasePageEIP.prototype.reJQuery = new RegExp("\\sjquery[0-9]*\\=\"[0-9]*\"", "gi");

CmsBasePageEIP.prototype.GetCtxMenu = function() {
    if (!this._ctxMenu) {
        this._ctxMenu = $find($('.EipCtxMenu').parent()[0].id);
    }
    return this._ctxMenu;
};
CmsBasePageEIP.prototype.loadingWindow = function(aMessage) {
    if ($(document).find("#EipLoadingWindow").size() == 0) {
        var loadingScreen = $('<div id="EipLoadingWindow" class="progressBackgroundFilter" ><center><div class="progressImagePosition"><img alt="' + aMessage + '" src="/pb/Uc/ElementEdition/Skins/Default/img/loading_blue.gif" style="border: 0px;" /></div><div id="progressTextPosition" class="TitleLabelField">' + aMessage + '</div></center></div>');

        loadingScreen.css('position', 'fixed');
        loadingScreen.css('top', '0px');
        loadingScreen.css('left', '0px');
        loadingScreen.css('right', '0px');
        loadingScreen.css('bottom', '0px');
        loadingScreen.css('height', '100%');
        loadingScreen.css('width', '100%');
        loadingScreen.css('z-index', '10000');
        loadingScreen.appendTo('body');
    }
};
CmsBasePageEIP.prototype.unloadLoadingWindow = function() {
    window.top.$('#EipLoadingWindow').remove();
};
/**
* Hack rightclick guardar scrolltop del body
*/
CmsBasePageEIP.prototype.StoreBodyCenterScroll = function() {
    var jBodyCenter = $('.ui-layout-center');
    if (jBodyCenter.data('scrollTop') != jBodyCenter.attr('scrollTop')) {
        jBodyCenter.data('scrollTop', jBodyCenter.attr('scrollTop'));
    }
};

/**
* Hack rightclick guardar scrolltop del body
*/
CmsBasePageEIP.prototype.RestoreBodyCenterScroll = function() {
    var jBodyCenter = $('.ui-layout-center');
    if (jBodyCenter.data('scrollTop') != jBodyCenter.attr('scrollTop')) {
        jBodyCenter.attr('scrollTop', jBodyCenter.data('scrollTop'));
    }
};

CmsBasePageEIP.prototype.isDescendant = function(ancestor, candidate) {
    if (ancestor == candidate) {
        return true;
    }

    if (candidate === null || ancestor === null) {
        return false;
    }

    var temp = candidate.parentElement;
    while (temp !== null) {
        if (temp == ancestor) {
            return true;
        }

        temp = temp.parentElement;
    }

    return false;
};
CmsBasePageEIP.prototype.onControlMouseOver = function(e) {

};

CmsBasePageEIP.prototype.toggleDefaultValue = function(aCtrl) {
    var lTag = aCtrl.tagName.toLowerCase();
    if ((lTag == "span") || (lTag=="a")){
        var lTxt = aCtrl.innerText;
        // trim()
        var lTrimmedTxt = lTxt.replace(/^\s+|\s+$/g, "").replace(/[\s(&nbsp;)]+$/g, '');
        if (
        // si no hay texto, esta vacio
        lTrimmedTxt.length == 0
        // si hay algo que no sea un span o un div, consideramos que no esta vacio tampoco
        && $(aCtrl).find("*").not("div").not("span").not("p").length == 0
        ) {
            $(aCtrl).addClass("EIPDefaultValue");
//            this.CrearMarcoForDefaultValues(aCtrl, "EIPHiliteMarcoForEmptyDefaultValue");
        } else {
            $(aCtrl).removeClass("EIPDefaultValue");
        }
    }
    else if (
        (lTag == "img" || (lTag == "input" && aCtrl.type.toLowerCase() == "image"))
        &&
        (!aCtrl.src || aCtrl.src.length == 0 || aCtrl.src.match(this.GuidEmpty))
        ) {
        // es imagen y esta vacio
        aCtrl.src = this.EmptyImgUrl;
    }
}

CmsBasePageEIP.prototype.EnableEIP = function(aIsEnabled) {
    this.NavigationEnabled = !aIsEnabled;
    var self = this;

    var cvCont = self.getContentViewerContainer();
    cvCont.unbind('click');
    // click sobre cualquier lado no editable (que no sea una barra) hace desaparecer las barras
    cvCont.click(function(e) {

        try {
            // Atención. Este código es un extra pedido por el ProductOwner pero
            //el mismo dijo que si toca la pera se quita y listo. Se deja el código justo debajo,
            //mas simple pero efectivo 
            if (!e.originalEvent) {
                return;
            }
            if ($(e.originalEvent.srcElement).parents('.EIPToolBarRowWrap').length === 0) {
                self.DownliteAll();
            }

            //if (cvCont.attr('id') == $(e.originalEvent.srcElement).attr('id')) {
            //self.DownliteAll();
            //}
        }
        catch (e) {
        } // Si no va que aprieten Esc que si va seguro
    });

    // suscribirnos al onmouseover de los controles mapeados
    $.each(this.CmsDataMappingList, function(i, val) {
        //var lCtrlElem = $get(val.TargetControlClientId);
        var lCtrlElem = self.GetEffectiveDomElement(val);
        var lCtrl = $(lCtrlElem);
        if (!(lCtrlElem)) {
            return;
        }

        lCtrl.unbind("mouseover");
        lCtrl.unbind("focus");
        lCtrl.keydown(function(event) {
            switch (event.keyCode) {
                case 37:
                    event.stopPropagation();
                    break;
                case 38:
                    event.stopPropagation();
                    break;
                case 39:
                    event.stopPropagation();
                    break;
                case 40:
                    event.stopPropagation();
                    break;
            }
        });

        if (!aIsEnabled) {
            lCtrl.unbind("mouseout");
            lCtrl.unbind("blur");
            lCtrl.unbind("click");
            lCtrlElem.contentEditable = 'false';
        }
        else {
            lCtrl.data('IsEipMappingTargetControl', true);

            var lCtrlOnMouseOver = function(e) {
                var ljElementosMarco = $("div.EIPHiliteMarco");
                var lDeleted = self.removeIfNotCurrent(ljElementosMarco, this);
                if ((ljElementosMarco.length === 0) || (lDeleted)) {
                    self.CrearMarco(lCtrlElem, val);
                }
            };
            // resaltar el control al hover
            lCtrl.mouseover(lCtrlOnMouseOver);

            // chequeo de clase vacío
            self.toggleDefaultValue(lCtrlElem);

            // Mostrar las barras de edición:
            // Para flash utilizamos el mouseOver. El botón derecho sino llama al menu flash
            // ATENCION: Si esto da por culo, se deja todo en el rigthClick. El menu se activa
            // con primero click derecho y luego click izquierdo
            if (self.isFlashObject(lCtrl)) {
                var lCtrlFlashMouseOver = function(e) {
                    self.ControlRigthClick(self, e, lCtrlElem, val);
                };
                lCtrl.mouseover(lCtrlFlashMouseOver);
            }
            var lCtrlOnMouseRightClick = function(e) {
                // Hack rightclick restaurar scrolltop del body 
                self.RestoreBodyCenterScroll();
                self.ControlRigthClick(self, e, lCtrlElem, val);
            };

            // Caso general: Barras de edición en el botón derecho. Fácil. Fácil. Fácil
            lCtrl.rightClick(lCtrlOnMouseRightClick);
            var lCtrlOnMouseRightButtonDown = function(e) {
                // Hack rightclick guardar scrolltop del body 
                self.StoreBodyCenterScroll();
            };

            lCtrl.rightMouseDown(lCtrlOnMouseRightButtonDown);
            var lCtrlOnEscKeyDown = function(e) {
                //if (self.FocusedElement == null)
                self.DownliteAll();
                self.DestroyEditionToolbar();
            };
            // Cuando queremos ocultar todas las capas de over de eip, Esc, y a no romper las pelotas 
            $(document).bind('keydown', 'Esc', lCtrlOnEscKeyDown);

            // Esto permite seleccionar correctamente en el caso de anidados y evita
            // flickering de creación de marcos al moverse por una propiedad html con
            // párrafos <p>'s,
            var lCtrlOnMouseOut = function(e) {
                var ljEipToolbar = $('div.EIPToolBarRowWrap');

                if ((self.CtxMenuEnabled
                || self.isDescendant($get(lCtrlElem.id + "_EIP_Toolbar"), e.toElement)
                || (ljEipToolbar.size() > 0 && self.isDescendant(ljEipToolbar[0], e.toElement)))
                ) {
                    return;
                }

                var twPos = ljEipToolbar.offset();
                var lMouseCoords = Pb.Utils.getPageEventCoords(e);

                // MSM. Tolerancia en píxels mínimo 1
                var lTolerance = 1;

                var isInToolbarRegion = (ljEipToolbar.size() > 0) && (((twPos.left - lTolerance) <= lMouseCoords.left) &&
                (lMouseCoords.left <= (twPos.left + lCtrl.width() + lTolerance)) &&
                ((twPos.top - lTolerance) <= lMouseCoords.top) &&
                (lMouseCoords.top <= (twPos.top + lCtrl.height() + lTolerance)));

                if ((lMouseCoords.left > 0) &&
                (lMouseCoords.top > 0) &&
                (isInToolbarRegion)) {
                    return;
                }

                twPos = lCtrl.offset();
                var isInLayoutTemplateRegion = (((twPos.left - lTolerance) <= lMouseCoords.left) &&
                (lMouseCoords.left <= (twPos.left + lCtrl.width() + lTolerance)) &&
                ((twPos.top - lTolerance) <= lMouseCoords.top) &&
                (lMouseCoords.top <= (twPos.top + lCtrl.height() + lTolerance)));

                if (((lMouseCoords.left > 0)
                    && (lMouseCoords.top > 0)
                    && (!isInLayoutTemplateRegion))
                        || ($(e.srcElement).data('IsEipMappingTargetControl')
                            && $(e.toElement).data('IsEipMappingTargetControl')
                    )) {
                    self.DownliteAll();
                }
            };
            lCtrl.mouseout(lCtrlOnMouseOut);

            var lCtrlOnFocus = function(e) {
                self.DownliteAll(lCtrlElem);
                if (this.contentEditable != 'true') {
                    return;
                }
                self.FocusedElement = this;

                self.CreateEditionToolbar(this, val, val.SourcePropertyTypeId == self.HtmlDataTypeId);

                // capturar esc, siempre
                $(document).bind('keydown', 'Esc', function(e) {
                    self.HtmlEditEscHandler(e, val, lCtrlElem);
                });
                lCtrl.unbind('mouseover', lCtrlOnMouseOver);
            };
            // mientras tengamos foco no queremos que salte la capa amarilla
            // MSM: Cuando coge el foco empezamos a editar
            lCtrl.focus(lCtrlOnFocus);

            // editable
            if (self.IsContentEditable(val)) {
                lCtrlElem.contentEditable = 'true';

                //                if (lCtrlElem.innerHTML === '') {
                //                    lCtrlElem.style.minWidth = "10px";
                //                }

                // guardar valor original del control
                val.origValue = lCtrlElem.innerHTML;

                var lOnBlur = function(e) {
                    if (self._onprompt == true) {
                        return;
                    }

                    if (self._isToolbarClicked) {
                        return;
                    }

                    self.FocusedElement = null;
                    self.DestroyEditionToolbar();

                    var lInnerHTML = lCtrlElem.innerHTML.replace(self.reJQuery, "");
                    // chequeo de clase vacío
                    self.toggleDefaultValue(lCtrlElem);

                    if (lInnerHTML != val.origValue &&
                    !(val.saveError)) {
                        // MSM: val.saveError se usa para evitar guardar en el blur + de una ver en caso de error?
                        // porqué si no es así, val.saveError es asíncrono y siempre valdrá false
                        // porque se pone a true en error pero tras notificar el error por pantalla se pone a false.
                        // No lo toco porsiaca.

                        // guardar
                        self.save(val, lInnerHTML);
                    }
                    else {
                        // MSM: La restauración del valor original en caso de error de guardado es peligrosa 
                        // porqué el usuario puede perder los cambios realizados sin querer
                        // No sé si puede llegar a paras por aquí pero no lo toco porsiaca.

                        // Restaurar label
                        if (!val.saveError) {
                            lCtrlElem.innerHTML = val.origValue;
                            // chequeo de clase vacío
                            self.toggleDefaultValue(lCtrlElem);
                        }
                    }
                    lCtrl.mouseover(lCtrlOnMouseOver);
                };
                // al perder el foco...
                lCtrl.blur(lOnBlur);
            }
            else if (val.IsDefaultProperty) {
                if (val.IsGuid) {
                    lCtrl.css("cursor", "pointer");

                    var lCtrlOnGuidPropClick = function(e) {
                        //if (e.altKey) {
                        if (self.NavigationEnabled) {
                            return; // nada de nada, respetar el click
                        }
                        
                        TLK.OpenModalWindow("/" + Pb.Utils.Url.getPageLang() + val.SelectorUrl, function(radWindow, returnValue) {
                            if (returnValue) {
                                // cambiarlo y guardar
                                lCtrlElem.src = returnValue;
                                self.save(val, returnValue);
                                val.GuidValue = returnValue;
                            }
                            radWindow.close();
                        });
                        e.stopPropagation();
                        e.preventDefault();
                        return false;
                    };
                    lCtrl.click(lCtrlOnGuidPropClick);
                }
                else {
                    //                    var OnPropertyEditorPopupValueChanged = function(event, aNewValue, aRadWindow) {
                    //                        if (event.data.radWindow && event.data.radWindow == aRadWindow) {
                    //                            if (lCtrl.data('dateFormat')) {
                    //                                var lNewDate = new Date(aNewValue);
                    //                                var lNewTextValue = lNewDate.format(lCtrl.data('dateFormat'));

                    //                                lCtrl.text(lNewTextValue);
                    //                            }
                    //                        }
                    //                        // MSM. Puede que la radwindow no exista por abrirse en callback de save (html)
                    //                        Pb.Utils.TopEvents.topUnBind('PropertyEditorPopupValueChanged', OnPropertyEditorPopupValueChanged);
                    //                    };
                    var lCtrlOnPropEditorClick = function(e) {
                        // MSM. Puede que la radwindow no exista por abrirse en callback de save (html)
                        var lRadWnd = self.OpenPropertyEditorDialog(val, true);
                        //                        Pb.Utils.TopEvents.topBind('PropertyEditorPopupValueChanged', OnPropertyEditorPopupValueChanged, {
                        //                            radWindow: lRadWnd
                        //                        });
                        //                        // Evitar la propagación y esconder capa
                        $(".EIPHiliteDiv").remove();
                        e.stopPropagation();
                        e.preventDefault();
                        return false;
                    };
                    lCtrl.click(lCtrlOnPropEditorClick);
                }
            }
        }
    });

    if (!aIsEnabled) {
        // desactivamos todos los marcos
        $("div.EIPHiliteMarco").remove();
        $("div.EIPToolBarRowWrap").remove();
        $("div.EIPHiliteCapaGris").remove();
    }

    // layout


};

CmsBasePageEIP.prototype.isFlashObject = function(jSource) {
    return jSource.find('[classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000]').length == 1 || jSource.attr('classid') == "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
};

CmsBasePageEIP.prototype.CreatePaletteLayout = function(aListViewLayoutDelegate) {
    var self = this;

    var lDiv = $("<div id='cmsContentPalette' class='cmsContentPaletteDialog ui-layout-west' title='Contenidos' />");
    lDiv.appendTo($("body"));

    var lSearchDiv = $("<div class='cmsContentPaletteSearchBoxDiv' />");
    var msgFiltrar = 'Escriba texto para filtrar';
    var lSearch = $("<input type='text' class='cmsContentPaletteSearchBox' value='" + msgFiltrar + "'/>");
    lSearch.keyup(function(e) {
        // lanzar la busqueda si apretaron enter
        if (e.keyCode == 13) {
            self.UpdatePalette(lDivTopLevelPalette, self._paletteParentId, e.target.value);
        }
    });

    lSearch.focus(function() {
        if (lSearch[0].value == msgFiltrar) {
            lSearch[0].value = '';
        }
    });

    lSearch.blur(function() {
        if (lSearch[0].value === '') {
            lSearch[0].value = msgFiltrar;
        }
    });

    lSearchDiv.append(lSearch);
    lSearchDiv.appendTo(lDiv);
    var lDivTopLevelPalette = $("<div class='cmsContentPalette' style='padding-left:0px; margin-top: 10px' />");
    lDivTopLevelPalette.appendTo(lDiv);

    // jquery layout
    $('body').layout({
        north: {
            applyDefaultStyles: false,
            resizable: false,
            size: 90
        },
        west: {
            applyDefaultStyles: true,
            resizable: true,
            slidable: true,
            size: 250,
            onopen_end: function() {
                if (aListViewLayoutDelegate) {
                    aListViewLayoutDelegate();
                }
            },
            onclose_end: function() {
                if (aListViewLayoutDelegate) {
                    aListViewLayoutDelegate();
                }
            },
            onresize_end: function() {
                if (aListViewLayoutDelegate) {
                    aListViewLayoutDelegate();
                }
            }
        }
    });

    self.UpdatePalette(lDivTopLevelPalette, this._paletteParentId);
};

CmsBasePageEIP.prototype.RemovePaletteLayout = function() {
    $("div#cmsContentPalette").remove();

    $('body').layout({
        north: {
            applyDefaultStyles: false,
            resizable: false,
            size: 90
        }
    });
};

CmsBasePageEIP.prototype._getPaletteProperties = function() {
    this._propTemplateId = "~SdkWebUtils.GetListTemplateId(ver.Site.GetContentById(SdkFK.Create(\"" + EIP.MainContentId + "\")), ver.Content)~";
    this._propIcon = "~UIUtils.GetElementIconUrl(ver.Content)~";
    this._propTreeName = "~UIUtils.GetElementNameWithIcons(ver.Content)~";
    this._propHasSubContents = "~ver.Content.HasSubElements~";

    var lProps = [this._propTemplateId, this._propIcon, this._propTreeName, this._propHasSubContents];
    return lProps;
};

CmsBasePageEIP.prototype.RenderPalette = function(lDiv, aRes) {
    var self = this;
    // eliminar contenido anterior de la paleta
    lDiv.empty();
    // crear cada item del selector
    var lDivItems = $("<div id='cmsContentPaletteItems' style='width:100%'/>");
    lDiv.append(lDivItems);
    $.each(aRes.SubContents, function(i, n) {
        self.CreatePaletteItem(lDivItems, n);
    });

    // convertirlos en draggables
    self.MakeDraggable(lDivItems);

    lDiv.disableSelection();

};

CmsBasePageEIP.prototype.CreatePaletteItemTitle = function(aProperties, aExpanded) {

    var self = this;

    var lHasSubContents = aProperties.Rows[0].Properties[self._propHasSubContents] == "True";
    var lTreeName = aProperties.Rows[0].Properties[self._propTreeName];
    var lIcon = aProperties.Rows[0].Properties[self._propIcon] + "?pw=true&ph=true&mw=24&mh=19";
    var lTemplateId = aProperties.Rows[0].Properties[self._propTemplateId];

    var lItemTitle = $("<div id='" + aProperties.Id + "' class='cmsContentPaletteItemTitle'><img src='" + lIcon + "' style='vertical-align:middle;' alt='" + aProperties.Name + "' />" + lTreeName + "</div>");
    lItemTitle.rightClick(function(e) {
        // Mostrar menu contextual del arbol
        // Obtener los items
        var lParams = {
            aContentId: aProperties.Id
        };
        self._executeBackofficeMethod("EIPService", "GetTreeContextMenuItems", lParams, function(res) {
            // Mostrar el menu contextual
            var ofs = lItemTitle.offset();
            var lMenu = self.GetCtxMenu();
            lMenu.get_items().clear();
            self._createTreeContextMenuItems(lMenu.get_items(), res.d, lItemTitle);
            lMenu.showAt(ofs.left, ofs.top + lItemTitle.outerHeight());
        });
    });

    if (lHasSubContents) {
        lItemTitle.addClass(aExpanded ? "cmsContentPaletteHasSubContentsExpanded" : "cmsContentPaletteHasSubContents");
        // agregar evento de click para ver subcontenidos
        lItemTitle.click(function(e) {
            var lItTitle = $(e.target).closest(".cmsContentPaletteItemTitle");
            var lIt = lItTitle.parent();
            var lCapaHijos = lItTitle.siblings('.cmsContentPalette');
            if (lCapaHijos.length === 0) {
                lCapaHijos = $("<div class='cmsContentPalette' />");
                lIt.append(lCapaHijos);
                self.UpdatePalette(lCapaHijos, lItTitle.attr("id"));
            }
            else {
                lCapaHijos.toggle();
            }
            // darle la vuelta al icono de +/-
            lItTitle.toggleClass("cmsContentPaletteHasSubContents");
            lItTitle.toggleClass("cmsContentPaletteHasSubContentsExpanded");

            e.stopPropagation();
            e.preventDefault();
            return false;
        });
    }
    else {
        lItemTitle.addClass("cmsContentPaletteNoSubContents");
    }
    if (!lTemplateId) {
        lItemTitle.addClass("cmsContentPaletteNotDraggable");
    }
    else {
        lItemTitle.addClass("cmsContentPaletteDraggable");
    }
    return lItemTitle;
};

CmsBasePageEIP.prototype.CreatePaletteItem = function(aParentDiv, aProperties) {
    var self = this;

    var lItem = $("<div class='cmsContentPaletteItem' />");

    var lItemTitle = this.CreatePaletteItemTitle(aProperties);

    lItem.append(lItemTitle);
    aParentDiv.append(lItem);
};

CmsBasePageEIP.prototype.MakeDraggable = function(aDivItems) {
    var self = this;
    aDivItems.find(".cmsContentPaletteDraggable").draggable({
        appendTo: 'body',
        revert: 'invalid',
        connectToSortable: '.CmsListViewLayoutWrapper.isLayout',
        cancel: 'img',
        helper: function(e) {
            var lClone = $(e.srcElement).clone(false);
            lClone.removeClass("cmsContentPaletteHasSubContents");
            lClone.removeClass("cmsContentPaletteHasSubContentsExpanded");
            lClone.removeClass("cmsContentPaletteItemTitle");
            lClone.removeClass("cmsContentPaletteNoSubContents");
            lClone.removeClass("cmsContentPaletteDraggable");
            lClone.addClass("isDragging");
            lClone.css("min-width", 0);
            lClone.css("min-height", 0);
            lClone.data("isRendered", false);
            return lClone.get(0);
        },
        zIndex: $.maxZIndex(),
        start: function(event, ui) {
            self._tempDragItem = null;
            self._executeBackofficeMethod("EIPService", "GetRenderedContent", {
                "aPrefix": "CmsListViewLayoutWrapper",
                "aPageContentId": EIP.MainContentId,
                "aContentId": ui.helper.attr("id"),
                "aRowId": null
            }, function(res) {
                ui.helper.css("height", "");
                ui.helper.html(res.d);
                var lDragLayer = $(".isDragging");
                lDragLayer.css("height", "");
                lDragLayer.html(res.d);
                self._tempDragItem = res.d;
                lDragLayer.trigger("renderedContent");
                lDragLayer.data("isRendered", true);
            }, function(XMLHttpRequest, textStatus, errorThrown) {
                EIP.ShowBackMsg("Error: " + $.evalJSON(XMLHttpRequest.responseText).Message, "EIPBackgroundProgressError");
            });
        }
    }).disableSelection();
};

CmsBasePageEIP.prototype.UpdatePalette = function(aDiv, aId, aTxt) {
    var lDiv = aDiv;
    lDiv.html(this._loadingMsg);

    var lProperties = this._getPaletteProperties();

    var lMethod = "GetSubContents";
    var lParams = {
        aPageContentId: EIP.MainContentId,
        aParentId: aId,
        aProperties: lProperties,
        aConditions: null,
        aParentProperties: lProperties
    };

    if (aTxt && aTxt.length > 0) {
        if (aTxt.length > 1 && aTxt[0] == "~" && aTxt[aTxt.length - 1] == "~") {
            lMethod = "SelectContents";
            lParams = {
                aPageContentId: EIP.MainContentId,
                aSelectExpression: aTxt.substring(1, aTxt.length - 1),
                aProperties: lProperties,
                aConditions: null
            };
        }
        else {
            lMethod = "GetDescendantsByPattern";
            lParams = {
                aPageContentId: EIP.MainContentId,
                aParentId: aId,
                aPattern: aTxt,
                aProperties: lProperties,
                aConditions: null
            };
        }
    }

    var self = this;
    this._executeBackofficeMethod("EIPService", lMethod, lParams, function(res) {
        self.RenderPalette(lDiv, res.d);
    });
};

CmsBasePageEIP.prototype._createTreeContextMenuItems = function(aMenuItems, aItemsToAdd, aDivTitle) {
    var self = this;
    $.each(aItemsToAdd, function(i, aItem) {
        var lItem = new Telerik.Web.UI.RadMenuItem();
        if (aItem.Text) {
            lItem.set_text(aItem.Text);
        }
        if (aItem.NavigateUrl) {
            lItem.set_navigateUrl(aItem.NavigateUrl);
        }
        if (aItem.UrlIcon) {
            var lIconUrl = aItem.UrlIcon;
            if (lIconUrl[0] == '~') {
                lIconUrl = lIconUrl.substr(1);
            }
            lItem.set_imageUrl(lIconUrl);
        }
        lItem.set_isSeparator(aItem.IsSeparator);
        aMenuItems.add(lItem);
        if (aItem.CommandName) {
            var lnk = lItem.get_linkElement();
            $(lnk).click(function(e) {
                self.ExecuteCtxMenuCommand(e, aItem, aDivTitle);
            });
        }
        if (aItem.Items) {
            self._createTreeContextMenuItems(lItem.get_items(), aItem.Items, aDivTitle);
        }
    });
};

CmsBasePageEIP.prototype.RefreshNode = function(aDivTitle) {
    var self = this;
    var lItTitleOld = $(aDivTitle);
    var lIt = lItTitleOld.parent();
    var lId = lItTitleOld.attr("id");

    var lProperties = this._getPaletteProperties();

    var lMethod = "GetSubContents";
    var lParams = {
        aPageContentId: EIP.MainContentId,
        aParentId: lId,
        aProperties: lProperties,
        aConditions: null,
        aParentProperties: lProperties
    };

    // Poner un aviso de Cargando...
    //lItTitleOld.html(self._loadingMsg);

    this._executeBackofficeMethod("EIPService", lMethod, lParams, function(res) {
        // Eliminar la antigua lista de los hijos, si la hubiera
        lItTitleOld.siblings('.cmsContentPalette').remove();
        // Reescribir el titulo
        var lItTitleNew = self.CreatePaletteItemTitle(res.d.ParentProperties, true);
        lItTitleOld.before(lItTitleNew);
        lItTitleOld.remove();
        // Hacerlo draggable
        self.MakeDraggable(lItTitleNew.parent());
        // Renderizar la nueva lista de los hijos
        var lChildrenDivNew = $("<div class='cmsContentPalette' />");
        lItTitleNew.parent().append(lChildrenDivNew);
        self.RenderPalette(lChildrenDivNew, res.d);
    });
};

CmsBasePageEIP.prototype.ExecuteCtxMenuCommand = function(e, aItem, aDivTitle) {
    var self = this;
    var lId = $(aDivTitle).attr("id");
    var lDivTitle = aDivTitle;
    switch (aItem.CommandName) {
        case "REFRESH":
            self.RefreshNode(lDivTitle);
            break;
        case "NEW":
            window.top.GlobalRefreshManager.InvokeWizardNewElement(aItem.CommandArgument, lId, function(sender, args) {
                self.RefreshNode(lDivTitle);
            });
            break;
        case "RENAME":
            window.top.GlobalRefreshManager.InvokeWizardRenameElement(aItem.CommandArgument, function(sender, args) {
                self.RefreshNode(lDivTitle);
            });
            break;
        case "INHERIT_META":
            var lElemId = aItem.CommandArgument;
            $.ajax({
                type: "POST",
                url: "/pb/Services/BackOffice.asmx/MakeInheritFromMeta?pbl=" + Pb.Utils.Url.getPageLang(),
                data: $.compactJSON({
                    "aElementId": lElemId
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(res) {
                    self.RefreshNode(lDivTitle);
                }
            });
            break;
        case "REMOVE":
            self.RemoveNode(lDivTitle);
            //$(lDivTitle).parent().remove();
            break;
        default:
            alert(aItem.CommandName);
            break;
    }
};

CmsBasePageEIP.prototype.RemoveNode = function(aDivTitle) {
    var self = this;
    var lId = $(aDivTitle).attr("id");
    // Llamar al webMethod con la lógica para determinar si el elemento se puede eliminar
    // indicando el callback de eliminación
    var lDeletion = new CmsElementDeletion(lId, //RemoveNodeCallBackFn
 function(arg) {
     if (arg) {
         var lIds = [];
         lIds[0] = lId;

         Pb.Utils.execAjaxSvcMethod("BackOffice.asmx", "DeleteElement", $.compactJSON({
             "aKeys": lIds
         }), function(res) {
             var lTitleParent = $(aDivTitle).parent().parent().parent().siblings(".cmsContentPaletteItemTitle");
             // si tiene padre, refrescarlo
             // si no lo tiene, borramos el propio item
             if (lTitleParent.length > 0) {
                 self.RefreshNode(lTitleParent[0]);
             }
             else {
                 $(aDivTitle).parent().remove();
             }
         });
     }
 }, //RemoveLocalizatedNodeCallBackFn
 function(args) {
     if (args) {
         var lArguments = $.compactJSON({
             "aElementId": lId,
             "aCultureStr": Pb.Utils.Url.getPageLang()
         });

         Pb.Utils.execAjaxSvcMethod("BackOffice.asmx", "RemoveLocalizatedContentVersion", lArguments, function(res) {
             self.RefreshNode(aDivTitle);
         });
     }
 });
    lDeletion.RemoveWithConfirm();
};

function deleteSimpleLocalizationConfirmCallFn(aResult) {

    if (aResult !== null) {
        var lArguments = $.compactJSON({
            "aElementId": aResult,
            "aCultureStr": Pb.Utils.Url.getPageLang()
        });

        var lDelegateUpdateEIP = Function.createDelegate(this, this._onDeleteElementLocazationSuccess);

        Pb.Utils.execAjaxSvcMethod("BackOffice.asmx", "RemoveLocalizatedContentVersion", lArguments, onElementDeleted);
    }
}

CmsBasePageEIP.prototype.IsContentEditable = function(val) {
    return val.IsInlineEditable && val.IsDefaultProperty && val.IsEditableForCurrentLang;
};

//MSM. Aquí el primer parámetro es guanero pq se puede crear un delegado en la llamada
//a la función y usar this en lugar de self dentro del método
CmsBasePageEIP.prototype.ControlRigthClick = function(self, e, ctrl, val) {
    //Se ha comentado esto para evitar que se cancele el despliegue de los menús de telerik.
    //e.stopPropagation();
    //e.preventDefault();
    //return false;
    //}
    self.IsContentEditable(val);
    if (!self.NavigationEnabled) {
        $(ctrl).data("highlighted", false);
        self.HiliteControl(ctrl, val, e);
    }
};

CmsBasePageEIP.prototype.GetEffectiveDomElement = function(mapping) {
    return $get(mapping.TargetControlClientId);
};

CmsBasePageEIP.prototype.DestroyEditionToolbar = function() {
    // destruir toolbar de Edicion
    $(".EIPEditionToolBar").remove();
};
CmsBasePageEIP.prototype.CreateEditionToolbar = function(source, mapping, enableHtml) {

    var jSource = $(source);
    var ofs = jSource.offset();

    var self = this;

    this.DestroyEditionToolbar();

    // si no ha de ser HTML, no va a haber botones por lo que carece de sentido
    if (!enableHtml) {
        return;
    }

    var lDivId = source.id + '_EditionToolbar';
    var cvCont = this.getContentViewerContainer();
    $("<div class='EIPEditionToolBar' id='" + lDivId + "'></div>").appendTo(cvCont);
    var lDivToolbar = $get(lDivId);

    // celda intermedia a modo de separador
    var lButtonsHtml = "<div class='Actions'>";

    // ids de todos los botones
    var lBoldId = lDivId + '_Bold';
    var lItalicId = lDivId + '_Italic';
    var lUnderlineId = lDivId + '_Underline';
    var lPastePlainTextId = lDivId + '_PastePlainText';
    var lLinkId = lDivId + '_Link';
    var lLinkContentId = lDivId + '_LinkContent';
    var lSaveId = lDivId + '_Save';
    var lCancelId = lDivId + '_Cancel';
    var lEditorId = lDivId + '_Editor';

    if (enableHtml) {
        // Agregamos el popup del editor
        lButtonsHtml += "<a title='\"Editor avanzado para la propiedad: '" + mapping.EffectiveName + "\"' unselectable='on' id='" + lEditorId + "' class=\"divMain\"><img class='imgBtnRibbon' src='/pb/img/Backoffice/Editinplace/bolaPequeLapizEip.gif' alt='Editor avanzado para la propiedad \"" + mapping.EffectiveName + "\"' unselectable='on'/><img src='/pb/img/eiptoolbar/Edit.png' style='position:absolute; left:9px; top:7px' unselectable='on' id='imgRibbonInnerImg'  alt='Editor avanzado para la propiedad \"" + mapping.EffectiveName + "\"' width=\"20px\" /></a>";
        ////        lButtonsHtml += "<a class='EIPBoton' title=\"Editor avanzado para la propiedad: '" + mapping.EffectiveName + "'\" unselectable='on' id='" + lEditorId + "'><img src='/pb/img/eiptoolbar/Edit.png' unselectable='on'/></a>";
        lButtonsHtml += "<div class='divEditOptions'>";
        lButtonsHtml += "<img class='EIPBoton_separador' src='/pb/img/backoffice/toolbarseparator.png'/>";
        //        // Agregamos botones de estilo de fuente
        lButtonsHtml += "<a class='EIPBoton UpperToolbarButton' title='Negrita' unselectable='on' id='" + lBoldId + "'><img src='/pb/img/EIPToolbar/Negrita.png'/ unselectable='on'/></a>";
        lButtonsHtml += "<a class='EIPBoton UpperToolbarButton' title='Cursiva' unselectable='on' id='" + lItalicId + "'><img src='/pb/img/EIPToolbar/Kursiva.png'/ unselectable='on'/></a>";
        lButtonsHtml += "<a class='EIPBoton UpperToolbarButton' title='Subrayado' unselectable='on' id='" + lUnderlineId + "'><img src='/pb/img/EIPToolbar/Subrayado.png' unselectable='on'/></a>";
        lButtonsHtml += "<a class='EIPBoton UpperToolbarButton' title='Pegar como texto simple' unselectable='on' id='" + lPastePlainTextId + "'><img src='/pb/img/EIPToolbar/PegarTextoSimple.png' unselectable='on'/></a>";
        lButtonsHtml += "</div>";
        //lButtonsHtml += "<a class='EIPBoton' title='Enlace URL' unselectable='on' id='" + lLinkId + "'><img src='/pb/img/EIPToolbar/botonEnlaceHTML.png' unselectable='on'/></a>";
        //lButtonsHtml += "<a class='EIPBoton' title='Enlace a Contenido' unselectable='on' id='" + lLinkContentId + "'><img src='/pb/Controls/BackOffice/Edition/PropertyEditors/HtmlEditor08/CmsLink.gif' unselectable='on'/></a>";
        //lButtonsHtml += "</td>";
    }

    //lButtonsHtml += "<div style='float:right;'>";
    //lButtonsHtml += "<a class='EIPBoton' id='" + lSaveId + "' unselectable='on'><img src='/pb/img/EIPToolbar/Guardar.png' title='Guardar' alt='Guardar' unselectable='on'/></a>";
    //lButtonsHtml += "<a class='EIPBoton' id='" + lCancelId + "' unselectable='on'><img src='/pb/img/Common/DataEditing/Undo.gif' title='Cancelar' alt='Cancelar' unselectable='on'/></a>";
    //lButtonsHtml += "</div>";
    lButtonsHtml += "</div>";

    var jDivToolbar = $(lDivToolbar);

    $(lButtonsHtml).appendTo(jDivToolbar);

    jDivToolbar.find('.imgBtnRibbon').hover(function() {
        $(this).attr('src', '/pb/img/Backoffice/Editinplace/bolaPequeLapizEipSel.gif');
    }, function() {
        $(this).attr('src', '/pb/img/Backoffice/Editinplace/bolaPequeLapizEip.gif');
    });

    jDivToolbar.find('#imgRibbonInnerImg').hover(function() {
        jDivToolbar.find('.imgBtnRibbon').attr('src', '/pb/img/Backoffice/Editinplace/bolaPequeLapizEipSel.gif');
    }, function() {
        jDivToolbar.find('.imgBtnRibbon').attr('src', '/pb/img/Backoffice/Editinplace/bolaPequeLapizEip.gif');
    });

    $('#' + lSaveId).click(function(e) {
        self.save(mapping, source.innerHTML);
    });
    $('#' + lCancelId).click(function(e) {
        source.innerHTML = mapping.origValue;
    });
    $('#' + lBoldId).mousedown(function(e) {
        self._isToolbarClicked = true;
        return self.HtmlEditBoldHandler(e, self);
    });
    $('#' + lBoldId).mouseup(function(e) {
        self._isToolbarClicked = false;
    });
    $('#' + lItalicId).mousedown(function(e) {
        self._isToolbarClicked = true;
        return self.HtmlEditItalicHandler(e, self);
    });
    $('#' + lItalicId).mouseup(function(e) {
        self._isToolbarClicked = false;
    });
    $('#' + lUnderlineId).mousedown(function(e) {
        self._isToolbarClicked = true;
        return self.HtmlEditUnderlineHandler(e, self);
    });
    $('#' + lUnderlineId).mouseup(function(e) { self._isToolbarClicked = false; });
    $('#' + lPastePlainTextId).click(function(e) { return self.HtmlEditPastePlainTextHandler(e, self); });
    $('#' + lLinkId).click(function(e) { self.OpenHTMLLinkDialog(mapping.FinalBranchId, mapping.FinalContentRowId, mapping.FinalSourceProperty); });
    $('#' + lLinkContentId).click(function(e) { self.OpenContentLinkDialog(mapping.FinalBranchId, mapping.FinalContentRowId, mapping.FinalSourceProperty); });
    // Agregamos le popup del editor
    $('#' + lEditorId).click(function(e) {
        self.DestroyEditionToolbar();
        self.OpenPropertyEditorDialog(mapping);
    });

    var lMinWidth = enableHtml ? 100 : 40;
    var lSourceWidth = $(source).outerWidth();
    var lDivWidth = lMinWidth > lSourceWidth ? lMinWidth : lSourceWidth;

    var lTop = this.ApplyJQueryLayoutTopCorrection(ofs.top);
    var lLeft = this.ApplyJQueryLayoutLeftCorrection(ofs.left);

    jDivToolbar.width(lDivWidth);
    jDivToolbar.css("display", "");
    jDivToolbar.css("position", "absolute");
    jDivToolbar.css("left", lLeft);
    jDivToolbar.css("top", lTop - jDivToolbar.outerHeight());
    $("<div class=\"EditionToolbarFin\">&nbsp;</div>").appendTo($(".EIPEditionToolBar"));
    $("<div class=\"EditionToolbarInicio\">&nbsp;</div>").prependTo($(".EIPEditionToolBar"));
};

CmsBasePageEIP.prototype.HtmlEditBoldHandler = function(e, self) {
    var lCtrlElem = self.FocusedElement;
    if (!lCtrlElem) {
        return;
    }
    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
        document.execCommand("Bold", false, null);
    }
    e.stopPropagation();
    e.preventDefault();
    return false;
};
CmsBasePageEIP.prototype.HtmlEditItalicHandler = function(e, self) {
    var lCtrlElem = self.FocusedElement;
    if (!lCtrlElem) {
        return;
    }
    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
        document.execCommand("Italic", false, null);
    }
    e.stopPropagation();
    e.preventDefault();
    return false;
};
CmsBasePageEIP.prototype.HtmlEditUnderlineHandler = function(e, self) {
    var lCtrlElem = self.FocusedElement;
    if (!lCtrlElem) {
        return;
    }
    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
        document.execCommand("Underline", false, null);
    }
    e.stopPropagation();
    e.preventDefault();
    return false;
};
CmsBasePageEIP.prototype.HtmlEditPastePlainTextHandler = function(e, self) {
    var lCtrlElem = self.FocusedElement;
    if (!lCtrlElem) return;
    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {

        var replaceNewLineWithBr = function(textData) {
            try {
                textData = textData.replace(/\n/g, "<br>");
                return textData;
            }
            catch (exc) { }
        }

        var cleanAndPaste = function(content) {
            if (content) {
                var plainText = content.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                plainText = replaceNewLineWithBr(plainText);
                if (plainText) {
                    var rng = document.selection.createRange();
                    rng.pasteHTML(plainText);
                }
            }
        }

        if ($.browser.msie) {
            cleanAndPaste(window.clipboardData.getData("Text"));
        }
        else if (window.getSelection) {
            var userSelectionRng = window.getSelection().getRangeAt(0);

            function PastePlainTextDialogCallBack(text) {
                var selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(userSelectionRng);
                if (text) {
                    window.document.execCommand('insertHTML', false, text);
                }
                this._onprompt = false;
                return false;
            }

            self._onprompt = true;

            TLK.RadPrompt('Por favor, pegue el texto en esta caja utilizando Ctrl+V.', Function.createDelegate(self, PastePlainTextDialogCallBack), 'Pegar como texto simple', ' ', 250, 165);
        }
    }
    e.stopPropagation();
    e.preventDefault();
    return false;
};

CmsBasePageEIP.prototype.HtmlEditCancelCtrlEnterHandler = function(e, self) {
    // Cancelarlo, para los campos de texto simple   
    var lCtrlElem = self.FocusedElement;
    if (lCtrlElem &&
    !self.isHtmlEditor(lCtrlElem) &&
    lCtrlElem.contentEditable &&
    lCtrlElem.contentEditable == 'true') {
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
};

CmsBasePageEIP.prototype.HtmlEditCancelShiftEnterHandler = function(e, self) {
    // Cancelarlo, para los campos de texto simple        
    var lCtrlElem = self.FocusedElement;
    if (lCtrlElem &&
    !self.isHtmlEditor(lCtrlElem) &&
    !self.isMultiLineTextEditor(lCtrlElem) &&
    lCtrlElem.contentEditable &&
    lCtrlElem.contentEditable == 'true') {
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
};

CmsBasePageEIP.prototype.HtmlEditCancelEnterHandler = function(e, self) {
    // Cancelarlo, para los campos de texto simple    
    var lCtrlElem = self.FocusedElement;
    if (lCtrlElem &&
    !self.isHtmlEditor(lCtrlElem) &&
    lCtrlElem.contentEditable &&
    lCtrlElem.contentEditable == 'true') {
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
};

CmsBasePageEIP.prototype.HtmlNewLine = function(e, self) {
    var lCtrlElem = self.FocusedElement;
    if (!lCtrlElem) {
        return;
    }
    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
        document.execCommand("InsertParagraph", false, null);
    }
    e.stopPropagation();
    e.preventDefault();
    return false;
};

CmsBasePageEIP.prototype.HtmlEditEscHandler = function(e, val, elem) {
    var lCtrlElem = elem;
    if (lCtrlElem && lCtrlElem.contentEditable == 'true') {
        if (val.origValue) {
            elem.innerHTML = val.origValue;
            // chequeo de clase vacío
            this.toggleDefaultValue(lCtrlElem);
            elem.blur();
        }
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
};

/**
* Metodo para crear un capa gris sobre un contenido
*/
CmsBasePageEIP.prototype.CrearCapaGris = function(source, mapping) {

    var padding = 3;
    var jSource = $(source);
    var ofs = jSource.offset();
    var h = jSource.outerHeight();
    var w = jSource.outerWidth();

    var cvCont = this.getContentViewerContainer();
    var lTop = this.ApplyJQueryLayoutTopCorrection(ofs.top);
    var lLeft = this.ApplyJQueryLayoutLeftCorrection(ofs.left);

    var lDivHightliteLeft = $("<div class='EIPHiliteCapaGris'></div>").appendTo(cvCont);
    lDivHightliteLeft.css("left", lLeft - padding);
    lDivHightliteLeft.css("top", lTop - padding);
    lDivHightliteLeft.css("width", w + 2 * padding);
    lDivHightliteLeft.css("height", h + 2 * padding);
    lDivHightliteLeft.data("sourceElement", source);

    $('.EIPHiliteCapaGris').show();
    $('.EIPHiliteCapaGris').css("opacity", "0.3");
};

CmsBasePageEIP.prototype.CrearMarcoGenerico = function(source, classname) {
    var padding = 3;
    var jSource = $(source);
    var ofs = jSource.offset();
    var h = jSource.outerHeight();
    var w = jSource.outerWidth();

    var lTop = this.ApplyJQueryLayoutTopCorrection(ofs.top);
    var lLeft = this.ApplyJQueryLayoutLeftCorrection(ofs.left);

    var cvCont = this.getContentViewerContainer();

    var lDivHightliteLeft = $("<div class='" + classname + "'></div>").appendTo(cvCont);
    lDivHightliteLeft.css("left", lLeft - padding);
    lDivHightliteLeft.css("top", lTop );
    lDivHightliteLeft.css("width", 1);
    //    lDivHightliteLeft.css("height", h + 2 * padding);
    lDivHightliteLeft.css("height", h);
    lDivHightliteLeft.data("sourceElement", source);

    var lDivHightliteRight = $("<div class='" + classname + "'></div>").appendTo(cvCont);
    lDivHightliteRight.css("left", lLeft + w );
    lDivHightliteRight.css("top", lTop - 1 );
    lDivHightliteRight.css("width", 1);
    //lDivHightliteRight.css("height", h + 1 + 2 * padding);
    lDivHightliteRight.css("height", h + 1);
    lDivHightliteRight.data("sourceElement", source);

    var lDivHightliteTop = $("<div class='" + classname + "'></div>").appendTo(cvCont);
    lDivHightliteTop.css("left", lLeft - padding);
    lDivHightliteTop.css("top", lTop - 1);
//    lDivHightliteTop.css("width", w + 2 * padding);
    lDivHightliteTop.css("width", w + padding);
    lDivHightliteTop.css("height", 1);
    lDivHightliteTop.data("sourceElement", source);

    var lDivHightliteBottom = $("<div class='" + classname + "'></div>").appendTo(cvCont);
    lDivHightliteBottom.css("left", lLeft - padding);
    lDivHightliteBottom.css("top", lTop + h -1);
//    lDivHightliteBottom.css("width", w + 2 * padding);
    lDivHightliteBottom.css("width", w + padding);
    lDivHightliteBottom.css("height", 1);
    lDivHightliteBottom.data("sourceElement", source);

    $("." + classname).fadeIn(300);
    jSource.data('highlighted', true);
};

CmsBasePageEIP.prototype.CrearMarcoForDefaultValues = function(source, classname) {
    var jSource = $(source);
    jSource.children("div." + classname).remove();

    var padding = 3;
    var ofs = jSource.offset();
    var h = jSource.outerHeight();
    var w = jSource.outerWidth();

    var lTop = this.ApplyJQueryLayoutTopCorrection(ofs.top);
    var lLeft = this.ApplyJQueryLayoutLeftCorrection(ofs.left);

    var cvCont = this.getContentViewerContainer();


    var lDivHightliteTop = $("<div class='" + classname + "'></div>").appendTo(jSource);
    lDivHightliteTop.css("left", 0);
    lDivHightliteTop.css("top", 0);
    lDivHightliteTop.css("width", w);
    lDivHightliteTop.css("height", 1);
    lDivHightliteTop.data("sourceElement", source);

    var lDivHightliteLeft = $("<div class='" + classname + "'></div>").appendTo(jSource);
    lDivHightliteLeft.css("left", 0);
    lDivHightliteLeft.css("top", 0);
    lDivHightliteLeft.css("width", 1);
    lDivHightliteLeft.css("height", h);
    lDivHightliteLeft.data("sourceElement", source);

    var lDivHightliteRight = $("<div class='" + classname + "'></div>").appendTo(jSource);
    lDivHightliteRight.css("left", w-1);
    lDivHightliteRight.css("top", 0);
    lDivHightliteRight.css("width", 1);
    lDivHightliteRight.css("height", h + 1);
    lDivHightliteRight.data("sourceElement", source);


    var lDivHightliteBottom = $("<div class='" + classname + "'></div>").appendTo(jSource);
    lDivHightliteBottom.css("left", 0);
    lDivHightliteBottom.css("top", h);
    lDivHightliteBottom.css("width", w);
    lDivHightliteBottom.css("height", 1);
    lDivHightliteBottom.data("sourceElement", source);

    $("." + classname).fadeIn(300);
    jSource.data('highlighted', true);
};

CmsBasePageEIP.prototype.CrearMarco = function(source, mapping) {
    this.CrearMarcoGenerico(source, 'EIPHiliteMarco');
};


CmsBasePageEIP.prototype.removeIfNotCurrent = function(elemArray, domElementToIgnore) {
    if (!(elemArray === null)) {
        var deleted = false;
        for (var i = 0; i < elemArray.length; i++) {
            var jCurrentElement = $(elemArray[i]);
            var lSourcElement = jCurrentElement.data("sourceElement");
            if (lSourcElement !== domElementToIgnore) {
                jCurrentElement.remove();
                deleted = true;
                if ($(lSourcElement).data("highlighted")) {
                    $(lSourcElement).data("highlighted", false);
                }
            }
        }
        return deleted;
    }
};

CmsBasePageEIP.prototype.DownliteAll = function(domElementToIgnore) {
    this.removeIfNotCurrent($("div.EIPHiliteMarco"), domElementToIgnore);
    this.removeIfNotCurrent($("div.EIPToolBarRowWrap"), domElementToIgnore);
    this.removeIfNotCurrent($("div.EIPHiliteCapaGris"), domElementToIgnore);
    $(document).removeData("CurrentHighLitedElement");
};

CmsBasePageEIP.prototype.HiliteContentVersionPropertyMappings = function(aBranchId, aRowId, aSourcePropertyName) {
    var self = this;
    var lMappings = $.grep(self.CmsDataMappingList, function(val) {
        return (val.FinalBranchId == aBranchId && val.FinalContentRowId == aRowId && aSourcePropertyName == val.FinalSourceProperty);
    });
    $.each(lMappings, function(i, val) {
        //var lCtrl = $get(val.TargetControlClientId);
        var lCtrl = self.GetEffectiveDomElement(val);
        if (lCtrl) {
            self.CrearCapaGris(lCtrl, val);
        }
    });
};

/**
* Nos crea la capa que nos marca el control activo y sus hermanos
* @source {Object} Control activo
* @mapping {Object} CmsDataBindingEntity del control activo
* @e {Object} Event object
*/
CmsBasePageEIP.prototype.HiliteControl = function(source, mapping, e) {
    // si hay menu desplegado, no mostrar
    //if (this.CtxMenuEnabled) return;
    // obtener coordenadas y tamaño del control destino
    // crear un div de color rojo con z-index por encima de todo semi-transparente
    // posicionado y con su tamaño
    var self = this;
    var jSource = $(source);
    if (!jSource.data("highlighted")) {
        var ofs = jSource.offset();
        var h = jSource.outerHeight();
        var w = jSource.outerWidth();
        //var lDivId = source.id + "_EIP";
        var lDivIdBotonera = source.id + "_EIP_Toolbar";
        // crear capa para nuestro control
        this.DownliteAll(source);
        this.CrearMarco(source, mapping);

        $(".EIPToolBarRowWrap").remove();
        this.HideCtxMenu();

        var lDivHightliteToolBar = $("<div class='EIPToolBarRowWrap' id='" + lDivIdBotonera + "'></div>");
        lDivHightliteToolBar.data("sourceElement", source);

        // 140909: nuevo menu
        //var lTableHightliteToolbar = $("<table border='0' id='table_" + lDivIdBotonera + "' border=0 cellspacing=0 cellpadding=0 align=left></table>");
        //lTableHightliteToolbar.appendTo($(lDivHightliteToolBar));

        // BEGIN - Otra implementación
        // Todos los mapeos de este control
        var lAllControlMappings = $.grep(this.CmsDataMappingList, function(val) {
            return (val.TargetControlClientId == mapping.TargetControlClientId);
        });
        // ContentVersions unicos
        var lBranchIds = [];
        // ContentVersions default unicos
        var lDefBranchIds = [];
        // Listas de ContentVersionIds default y no default.
        $.each(lAllControlMappings, function(i, val) {
            if (val.IsDefaultProperty) {
                self.ArrayPushUnique(lDefBranchIds, val.FinalBranchId);
                var lIndex = $.inArray(val.FinalBranchId, lBranchIds);
                if (lIndex >= 0) {
                    lBranchIds.splice(lIndex, 1);
                }
            }
            if ($.inArray(val.FinalBranchId, lDefBranchIds) == -1) {
                self.ArrayPushUnique(lBranchIds, val.FinalBranchId);
            }
        });
        // A los default, agregamos los otros
        $.each(lBranchIds, function(i, val) {
            lDefBranchIds.push(val);
        });

        // POR CADA BRANCH
        $.each(lDefBranchIds, function(i, val) {
            // Todos los mapeos de este CV
            var lCVMappings = $.grep(lAllControlMappings, function(mapVal) {
                return (mapVal.FinalBranchId == val);
            });
            // Ordenamos primero las DEFAULT
            lCVMappings.sort(function(a, b) {
                if (a.IsDefaultProperty) {
                    return -1;
                }
                else {
                    return 1;
                }
            });

            var lPrimero = lCVMappings[0];
            var lContVerInfo = self.GetContentVersionInfo(lPrimero.FinalBranchId);

            // DIV contenedor de cada branch
            var lTableRow = $("<div class='EIPToolBarRow' id='row_" + lDivIdBotonera + "_" + lPrimero.FinalBranchId + "'></div>");

            // BOTON ICONO CONTENIDO PARA MENU CONTEXTUAL
            var lBoButtonDiv = $("<div class='EIPToolBarRow_ContentIco'></div>");
            var lBoButtonLink = $("<a title='Ver opciones...' ></a>");
            var lBoButtonLinkDiv = $("<div></div>");
            //Esto hace que todos los iconos built-in los muestre en un tamaño grande y las imagenes no se salgan
            //TODO: Identificar mejor los iconos que con....... esto........
            var lBoButtonLinkImg;
            if (lPrimero.IconId.substring(lPrimero.IconId.length - 12, lPrimero.IconId.length) == "000000000000" || lPrimero.IconId.substring(lPrimero.IconId.length - 12, lPrimero.IconId.length) == "2b220b4ad877" || lPrimero.IconId.substring(lPrimero.IconId.length - 12, lPrimero.IconId.length) == "b01437916ecb") {
                lBoButtonLinkImg = $("<img title='Ver opciones...' alt='Ver opciones...' src='/online/" + Pb.Utils.Url.getPageLang() + "/" + lPrimero.IconId + "?mw=24&mh=28' border=0 />");
            }
            else {
                lBoButtonLinkImg = $("<img title='Ver opciones...' alt='Ver opciones...' src='/online/" + Pb.Utils.Url.getPageLang() + "/" + lPrimero.IconId + "?mw=18&mh=28' border=0 />");
            }

            // Poner icono en fila
            lBoButtonDiv.appendTo(lTableRow);
            lBoButtonLink.appendTo(lBoButtonDiv);
            lBoButtonLinkDiv.appendTo(lBoButtonLink);
            lBoButtonLinkImg.appendTo(lBoButtonLinkDiv);

            // Inyectar el menu del contenido cuando cliquen
            lBoButtonLink.click(function(e) {
                self.ShowCtxMenu(e, val, lPrimero.TargetControlClientId);
            });

            var lPropDivs = $("<div class='EIPToolBarRow_Propiedades' ></div>");
            // Iteramos a través de las propiedades.
            $.each(lCVMappings, function(j, mapVal) {

                var lClass = "EIPToolBarRow_Prop";

                var lTitle = "";
                if (mapVal.EffectiveName.indexOf("Nombre de propiedad") < 0) {
                    lTitle = "Desde aquí puede editar la propiedad \"" + mapVal.EffectiveName + "\" del contenido \"" + lContVerInfo.Name + "\"";
                }
                else {
                    lTitle = "Desde aquí puede editar el nombre de la propiedad \"" + mapVal.EffectiveName.replace("Nombre de propiedad ", "") + "\" del contenido \"" + lContVerInfo.Name + "\"";
                }
                if (mapVal.IsDefaultProperty) {
                    lClass += " default";
                }
                if (!mapVal.IsEditableForCurrentLang) {
                    lClass += " disabled";
                    lTitle = "La propiedad no es editable en el idioma actual";
                }

                var lProp = $("<a class='" + lClass + "' title='" + lTitle + "'>" + mapVal.EffectiveName + "</a>");
                var lBoSeparator = $("<img class='EIPBoton_separador' src='/pb/img/BackOffice/toolBarSeparator.png' complete='complete'/>");

                lProp.appendTo(lPropDivs);
                lBoSeparator.appendTo(lPropDivs);

                if (mapVal.IsEditableForCurrentLang) {
                    lProp.click(function(e) {
                        self.OpenPropertyEditorDialog(mapVal);
                        // Evitar la propagación y esconder capa
                        $(".EIPHiliteDiv").remove();
                        e.stopPropagation();
                        e.preventDefault();
                        return false;
                    });
                }
            });
            lPropDivs.appendTo(lTableRow);

            var lIconDiv = $("<div class='EIPToolBarRow_Estado' ></div>");
            lIconDiv.appendTo(lTableRow);
            // inyectar iconos con llamada ajax
            self.ShowStatusIcons(e, val, lIconDiv);

            // Agregar la fila al contenedor
            lTableRow.appendTo(lDivHightliteToolBar);
        });

        var cvCont = self.getContentViewerContainer();

        var lTop = this.ApplyJQueryLayoutTopCorrection(ofs.top);
        var lLeft = this.ApplyJQueryLayoutLeftCorrection(ofs.left);

        lDivHightliteToolBar.appendTo(cvCont);
        lDivHightliteToolBar.css("left", e.pageX + "px");
        lDivHightliteToolBar.css("top", e.pageY + lTop - ofs.top + "px");
        lDivHightliteToolBar.css("position", "absolute");
        $(".EIPToolBarRow_Propiedades").find(".EIPBoton_separador:last").remove();
        $("<img class='EIPBoton_separador' src='/pb/img/BackOffice/toolBarSeparator.png' />").prependTo(".EIPToolBarRow_Estado");

        var Tamanyo = 0;
        var ljRowWraps = $(".EIPToolBarRowWrap");
        var lRowControlWraps = ljRowWraps.children(".EIPToolBarRow");
        /*for (var i = 0; i <= lRowControlWraps.size() - 1; i++) {
        var TamBarra;
        var ljRowControlWrap = $(lRowControlWraps[i]);
        if (navigator.appVersion.indexOf("MSIE 7.") > 0) {
        TamBarra = 0;
        for (var j = 0; j <= ljRowControlWrap.find("a,img").size() - 2; j++) {
        TamBarra = TamBarra + ljRowControlWrap.find("a,img")[j].scrollWidth;
        }
        for (var k = 0; k <= ljRowControlWrap.find("div").size() - 1; k++) {
        TamBarra = TamBarra + ljRowControlWrap.find("div")[k].scrollWidth / 4;
        }
        if (TamBarra > Tamanyo) {
        Tamanyo = TamBarra;
        }
        }
        else {
        TamBarra = lRowControlWraps.width();
        TamBarra = TamBarra + (25 * ljRowControlWrap.find(".EIPToolBarRow_Propiedades").find("a").size());

                if (TamBarra > Tamanyo) {
        Tamanyo = TamBarra;
        }
        }
        }*/

        var miArray = new Array()
        for (var i = 0; i <= ljRowWraps.children().size() - 1; i++) {
            var barras = ljRowWraps.children()
            var TamBarra = 0;
            /**/
            TamBarra = barras.find(".EIPToolBarRow_ContentIco").width() + barras.find(".EIPToolBarRow_Estado").width() + 45

            for (var j = 0; j <= barras.find(".EIPToolBarRow_Propiedades").children("a").size() - 1; j++) {
                TamBarra = TamBarra + $(barras.find(".EIPToolBarRow_Propiedades").children("a")[j]).width();
            }
            miArray.push(TamBarra);

        }

        miArray.sort(compareNumbers);
        Tamanyo = miArray[miArray.length - 1] + 50;

        ljRowWraps.css("width", Tamanyo + "px");
        lRowControlWraps.css("width", "100%");
        if ((ljRowWraps[0].offsetWidth + ljRowWraps.position().left) > window.screen.availWidth) {
            ljRowWraps.css("left", (window.screen.availWidth - ljRowWraps[0].offsetWidth - 40) + "px");
        }

        lDivHightliteToolBar.css("display", "none");
        lDivHightliteToolBar.fadeIn(100);
        jSource.data("highlighted", true);
        $(document).data("CurrentHighLitedElement", source);
    }
};
function compareNumbers(a, b) {
    if (a < b)
        return -1;
    if (a > b)
        return 1;
    return 0; // a == b
}

CmsBasePageEIP.prototype.ArrayPushUnique = function(array, element) {
    if ($.inArray(element, array) == -1) {
        array.push(element);
    }
};

// Devuelve un array con los elementos UNIQUE
CmsBasePageEIP.prototype.GetArrayUnique = function(array) {
    var lTemp = [];
    $.each(array, function(i, val) {
        if ($.inArray(lTemp, val) == -1) {
            lTemp.push(val);
        }
    });

    return lTemp;
};

CmsBasePageEIP.prototype.GetContentVersionInfo = function(contVerId) {
    var result = $.grep(this.ContentVersionList, function(val) {
        return (val.BranchId == contVerId);
    });

    return result[0];
};

CmsBasePageEIP.prototype.isHtmlEditor = function(lCtrlElem) {
    var lmap = this.getMappingFromElement(lCtrlElem);
    return lmap && lmap.SourcePropertyTypeId == this.HtmlDataTypeId;
};

/**
* Indica si es un editor de texto multi linea
*/
CmsBasePageEIP.prototype.isMultiLineTextEditor = function(lCtrlElem) {
    var lmap = this.getMappingFromElement(lCtrlElem);
    return lmap && lmap.SourcePropertyTypeId == this.MultilineTextTypeId;

};

CmsBasePageEIP.prototype.getMappingFromElement = function(lCtrlElem) {
    if (lCtrlElem && lCtrlElem.id) {
        var lmapping = $.grep(this.CmsDataMappingList, function(val) {
            return val.TargetControlClientId == lCtrlElem.id && val.IsDefaultProperty;
        });
        return lmapping[0];
    }
    return;
};

/*
* Actualiza todos los mapeos equivalentes que tengamos en la página,
* puesto que venimos de una edición "INLINE".
*/
CmsBasePageEIP.prototype.UpdateSameMappings = function(aMapping, aUpdateSelf) {
    var self = this;

    //if (!aMapping.IsInlineEditable || !aMapping.IsDefaultProperty) {
    if (!aMapping.IsDefaultProperty) {
        return;
    }

    var lEqMappings = $.grep(this.CmsDataMappingList, function(val) {
        return (val.FinalBranchId == aMapping.FinalBranchId &&
        val.FinalContentRowId == aMapping.FinalContentRowId &&
        val.FinalSourceProperty == aMapping.FinalSourceProperty &&
        ((val.TargetControlClientId != aMapping.TargetControlClientId) || aUpdateSelf) &&
        //val.IsInlineEditable &&
        val.IsDefaultProperty);
    });

    // Por cada mapeo coincidente, modificaremos el TargetControl.
    if (lEqMappings.length === 0) {
        return;
    }

    $.each(lEqMappings, function(i, val) {
        var lCtrl = $get(val.TargetControlClientId);
        var ljCtrl = $(lCtrl);
        // y si es un control de fecha??
        if (ljCtrl.data('dateFormat')) {
            // el constructor de date requiere formato mm/dd/yy pero recibimos dd/mm/yy
            // 2010-19-04: Cambiamos para usar el constructor estándar new Date(year, month, day) y
            // no tener problemas según idiomas del hilo, browser o lo que haya.
            // Al año por las dudas, le quitamos las horas que pueda tener, ya que se tenía en cuenta
            // que venía sólo fecha.
            // Al mes hay que restarle UNO!
            var lSplit = aMapping.origValue.split("/");
            // aMapping.origValue = lSplit[1] + "/" + lSplit[0] + "/" + lSplit[2];
            // Quitamos las horas
            lSplit[2] = lSplit[2].split(" ")[0];
            lSplit[1] = lSplit[1] - 1;
            // var lNewDate = new Date(aMapping.origValue);
            var lNewDate = new Date(lSplit[2], lSplit[1], lSplit[0]);
            var lNewTextValue = lNewDate.format(ljCtrl.data('dateFormat'));
            ljCtrl.text(lNewTextValue);
        } else if (val.IsDefaultProperty && val.IsGuid) {
            // imagenes
            lCtrl.src = aMapping.origValue;
            aMapping.GuidValue = aMapping.origValue;
        } else {
            lCtrl.innerHTML = aMapping.origValue;
        }
        // chequeo de clase vacío
        self.toggleDefaultValue(lCtrl);
    });
};

CmsBasePageEIP.prototype.DoOpenPropertyEditorDialog = function(aMapping, aAvoidRedirection) {

    // Cambiamos los parámetros separados por el mapping...
    var aBranchId = aMapping.FinalBranchId;
    var aContentRowId = aMapping.FinalContentRowId;
    var aSourceProperty = aMapping.FinalSourceProperty;
    var aSourcePropertyTypeId = aMapping.SourcePropertyTypeId;

    var self = this;
    self.DownliteAll();

    var lInitTime = this.InitTime; // Por defecto usamos la fecha de renderizado de la página pero...
    // ... puede que el control haya sido modificado (y guardado), entonces usamos la fecha de cuando se guardó.
    if (aMapping === null) // Si no viene informado como argumento a la función, todavía lo podemos encontrar (si existe, claro)
    {
        var mappingList = $.grep(self.CmsDataMappingList, function(mapping) {
            return mapping.FinalBranchId == aBranchId;
        });

        if (mappingList.length > 0) {
            aMapping = mappingList[0]; // Con el primero ya nos vale, ya que la fecha será la misma para todos los encontrados
        }
    }

    if (aMapping && aMapping.EIPModificationDate) {
        lInitTime = aMapping.EIPModificationDate;
    }

    var url = "/" + Pb.Utils.Url.getPageLang() + "/pb/forms/BackOffice/EditInPlace/PropertyEditorPopup.aspx?BranchId=" + aBranchId + "&RowId=" + aContentRowId + "&PropertyName=" + aSourceProperty.replace('&', '-amp-') + "&IsOnlineRequest=" + this.IsOnlineRequest + "&MainContentId=" + this.MainContentId + "&InitTime=" + lInitTime;
    var oWnd;
    $("IFRAME").attr("scrolling", "yes");


    function SetForceLoadingMessageHidingTimeout(miliseconds) {
        // Si la conexión es algo lenta, puede que la primera vez que se abra el popup se quede
        // enganchado el panel de "cargando" (en IE, cuando los recursos no están en caché). Con 
        // esta función forzamos su ocultación mientras no encontramos una solución mejor.
        function ForceLoadingMessageHiding() {
            var iframe = $(".rwWindowContent iframe");

            if (iframe.length > 0) {
                $(iframe).css('left', '0px');
                $(iframe).css('top', '0px');
            }
            else { // Si todavía no se ha creado el iframe, volvemos a esperar...
                SetForceLoadingMessageHidingTimeout(500);
            }
        }
        setTimeout(ForceLoadingMessageHiding, miliseconds);
    }

    SetForceLoadingMessageHidingTimeout(4000);

    try {
        if (window.top.TLK) {
            oWnd = window.top.TLK.ShowCenteredWindow(url, null);
        }
    }
    catch (e) {
        oWnd = TLK.ShowCenteredWindow(url, null);
    }

    var lBrowserWindow = oWnd.get_browserWindow();
    oWnd.autosize = true;
    oWnd.set_modal(true);

    if (aSourcePropertyTypeId == self.HtmlDataTypeId) {
        oWnd.set_height(750);
    }
    else if (aSourcePropertyTypeId == self.MultilineTextTypeId) {
        oWnd.set_height(600);
    }
    else if (aSourcePropertyTypeId == self.TextDataTypeId) {
        oWnd.set_height(420);
    }
    else {
        oWnd.set_height(480);
    }

    oWnd.set_width(850);
    oWnd.center();

    oWnd.ClientCallBackFunction = function(radWindow, returnValue) {
        if (returnValue) {
            //if (aMapping.IsInlineEditable && aMapping.IsDefaultProperty) {
            if (aMapping.IsDefaultProperty) {
                aMapping.origValue = self.BufferMapping;
                self.UpdateSameMappings(aMapping, true);
            }
            else if (!aAvoidRedirection) {
                self.UrlRedirect(returnValue);
            }
//            else {
//                aMapping.origValue = self.BufferMapping;
//                self.UpdateSameMappings(aMapping, true);
//            }
        }
    };
    return oWnd;
};
/**
* Abre una ventana de Telerik en la que seleccionamos un elemento
* para sus relaciones
*/
CmsBasePageEIP.prototype.OpenPropertyEditorDialog = function(aMapping, aAvoidRedirection) {
    var self = this;

    if (self.IsContentEditable(aMapping)) {
        // Esto solo se usa para propiedades con edición in-place
        // que son de tipo html 
        var lCtrlElem = self.GetEffectiveDomElement(aMapping);
        var lInnerHTML = lCtrlElem.innerHTML.replace(self.reJQuery, "");
        if (aMapping.originalValue != lInnerHTML) {
            // Se abren los editores en el callback del save para que el editor que se abre 
            // mientras se está grabando asíncrono (por el save) coja el cambio en 
            // sesión ya guardado y no coja el valor antiguo.
            self.save(aMapping, lInnerHTML);
            var lCallOpenPropertyDialogOnSaveSuccess = function(event, mapping, value, previousValue) {
                if (mapping == aMapping && value == lInnerHTML) {
                    self.DoOpenPropertyEditorDialog(aMapping, aAvoidRedirection);
                    Pb.Utils.TopEvents.topUnBind('sessionMappingSaveSuccess.' + lCtrlElem.id);
                    Pb.Utils.TopEvents.topUnBind('sessionMappingSaveError.' + lCtrlElem.id);
                }
            };
            var lCallOpenPropertyDialogOnSaveError = function(event, mapping, value) {
                if (mapping == aMapping && value == lInnerHTML) {
                    self.DoOpenPropertyEditorDialog(aMapping, aAvoidRedirection);
                    Pb.Utils.TopEvents.topUnBind('sessionMappingSaveSuccess.' + lCtrlElem.id);
                    Pb.Utils.TopEvents.topUnBind('sessionMappingSaveError.' + lCtrlElem.id);
                }
            };
            Pb.Utils.TopEvents.topBind('sessionMappingSaveSuccess.' + lCtrlElem.id, lCallOpenPropertyDialogOnSaveSuccess);
            Pb.Utils.TopEvents.topBind('sessionMappingSaveError.' + lCtrlElem.id, lCallOpenPropertyDialogOnSaveError);
        }
        else {
            return self.DoOpenPropertyEditorDialog(aMapping, aAvoidRedirection);
        }
    }
    else {
        return self.DoOpenPropertyEditorDialog(aMapping, aAvoidRedirection);
    }
};


/**
* Abre la ventana de relaciones del contenido.
*
*/
CmsBasePageEIP.prototype.OpenElementRelationsForm = function(aElementId) {
    var self = this;
    self.DownliteAll();
    // Cambio a Path absoluto.
    //    var url = "/" + Pb.Utils.Url.getPageLang() + "/pb/Forms/BackOffice/MainForm/Detail/ElementRelationsForm.aspx?ElementId=" + aElementId + "&IsEIP=true";
    var url = "/" + Pb.Utils.Url.getPageLang() + "/pb/Forms/BackOffice/EditInPlace/RelationsPopup.aspx?ElementId=" + aElementId + "&IsEIP=true";
    var oWnd;
    $("IFRAME").attr("scrolling", "yes");

    try {
        if (window.top.TLK) {
            oWnd = window.top.TLK.ShowCenteredWindow(url, null);
        }
    }
    catch (e) {
        oWnd = TLK.ShowCenteredWindow(url, null);
    }

    oWnd.autosize = true;
    oWnd.set_modal(true);
    oWnd.set_height(520);
    oWnd.set_width(850);
    oWnd.center();

    oWnd.add_close(function() {
        window.location.reload();
    });
};

/**
* Actualiza la URL de la página
*/
CmsBasePageEIP.prototype.UrlRedirect = function(aUrl) {
    document.location.href = aUrl + $.query.toString();
};

/**
* Abre el dialogo para crear un enlace a una URL
*/
CmsBasePageEIP.prototype.OpenHTMLLinkDialog = function(aConVerId, aRowId, aPropName) {

    // TODO: Obtener el link actual del texto seleccionado
    //    var lCtrlElem = self.FocusedElement;
    //    var lMapping = self.getMappingFromElement(lCtrlElem);
    //    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
    //        // document.execCommand("Bold", false, null);
    //    }

    var aDialogOpener = TLK.GetTopDialogOpener();

    var args = new Telerik.Web.UI.EditorCommandEventArgs("LinkManager", null, document.createElement("a"));
    args.CssClasses = [];
    args.set_callbackFunction(this.OpenHTMLLinkDialogCallBack);
    args.CmsText = "aa";
    args.realLink = {
        title: "titulo aqui"
    };

    //aDialogOpener.set_additionalQueryString('&PreselectedItemUrl=' + encodeURIComponent(initialPath));
    // Establecer función de CallBack
    //aDialogOpener.get_dialogDefinitions().DocumentManager.ClientCallbackFunction = this.OpenContentLinkDialogCallBack;

    // Abrir diálogo
    aDialogOpener.open('LinkManager', args);
};

CmsBasePageEIP.prototype.OpenHTMLLinkDialogCallBack = function(sender, args) {
    alert(args);
};


/**
* Abre el dialogo para crear un enlace a un contenido
*/
CmsBasePageEIP.prototype.OpenContentLinkDialog = function(aConVerId, aRowId, aPropName) {
    // http://cmsdevbo/pb/Forms/BackOffice/MainForm/Telerik.Web.UI.DialogHandler.aspx?DialogName=CmsLinkManager&Skin=PortalBuilder_Blue&Title=Link Manager&doid=a0e8697b-bdcc-4e81-908c-16da4fba15ed&dpptn=&dp=YHFlMzs5L1lRHRhySTV%2BM1cfUHN5ZXBCT1VfFFE2FBMuSmJDUzBiVTxgBmZqOmRZfwU7CQdhfghhc2kRbAR7blVjVEV%2BXHdRUUh6VHQMKBJdWEcpYwkNbTNZYVBhWwIhAicOUGY8d2R%2BU3I3b2hQRUdfYEJibnVOUjVBVTVKUHh9GWYyM1oKX2QkfARqclQvAUV%2BLXhZegtqFm9fbWBLYU5fY0licGIsYCNXFmFJcmpTIy9DGnJlCmAGaTo4Cy9DVDJBbnwPSCxkeQQPbAJ4QnRvS1JqUmMiARV2dFEJSAgpciRfUSp4Wn8EIBI%2FRFtRSQZEEncXRUd5BhIAfFlJb1AVQDh%2BCCBOdXYFbGkJUGQbYHobU35DDSw0LxtpVhhkSSVyBmZHcl51AUJAelRbb2oNaxIHYn5SZSRcPTxhGmRRDkZvZi4RLAdselZ0BR0xWQd%2Fa2dcZVp8AUVKZEhYKncKJFJdd3Y%2FZR4zRidNfSxmZw59
    // TLK.OpenModalWindow("/pb/forms/Details/RelationsSelector.aspx?GUID=" + val.GuidValue, function(radWindow, returnValue) {

    // var lUrl = "/pb/Controls/Backoffice/Edition/PropertyEditors/HtmlEditor08/CmsLinkDialog.ascx";


    // TODO: Obtener el link actual del texto seleccionado
    //    var lCtrlElem = self.FocusedElement;
    //    var lMapping = self.getMappingFromElement(lCtrlElem);
    //    if (lCtrlElem.contentEditable == 'true' && self.isHtmlEditor(lCtrlElem)) {
    //        // document.execCommand("Bold", false, null);
    //    }

    var aDialogOpener = TLK.GetTopDialogOpener();

    var args = new Telerik.Web.UI.EditorCommandEventArgs("CmsLinkManager", null, document.createElement("a"));
    args.CssClasses = [];
    args.set_callbackFunction(this.OpenContentLinkDialogCallBack);
    args.CmsText = "aa";
    args.realLink = {
        title: "titulo aqui"
    };

    //aDialogOpener.set_additionalQueryString('&PreselectedItemUrl=' + encodeURIComponent(initialPath));
    // Establecer función de CallBack
    //aDialogOpener.get_dialogDefinitions().DocumentManager.ClientCallbackFunction = this.OpenContentLinkDialogCallBack;

    // Abrir diálogo
    aDialogOpener.open('CmsLinkManager', args);
};

CmsBasePageEIP.prototype.OpenContentLinkDialogCallBack = function(sender, args) {
    alert(args);

    // TODO: Establecer link en el EIP
};


/**
* Guarda la modificación actual a través de un WebService
* @mapping {Object} CmsDataBindingEntity del control activo
* @value {String} Valor modificado
*/
CmsBasePageEIP.prototype.save = function(mapping, value) {
    var self = this;

    var lToSave = value;

    //    // filtrar html si se ha de guardar en texto simple
    //    if (mapping.SourcePropertyTypeId != this.HtmlDataTypeId)
    //        lToSave = lToSave.replace(/(<([^>]+)>)/ig, "");

    var params = $.compactJSON({
        "aOnline": self.IsOnlineRequest,
        "aBranchId": mapping.FinalBranchId,
        "aRowId": mapping.FinalContentRowId,
        "aPropertyName": mapping.FinalSourceProperty,
        "aPropertyValue": lToSave,
        "aInitTime": mapping.EIPModificationDate === null ? self.InitTime : mapping.EIPModificationDate
    });

    $.ajax({
        type: "POST",
        url: "/pb/Services/EIPService.asmx/SaveEIPChange?pbl=" + Pb.Utils.Url.getPageLang(),
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            var lPreviousValue = mapping.origValue;
            mapping.origValue = value;
            self.UpdateSameMappings(mapping, false);
            Pb.Utils.TopEvents.topTrigger('sessionMappingSaveSuccess', [mapping, value, lPreviousValue]);
            self.OnSave();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            mapping.saveError = true;
            self.ShowBackMsg("Error: " + $.evalJSON(XMLHttpRequest.responseText).Message, "EIPBackgroundProgressError");
            mapping.saveError = false;
            Pb.Utils.TopEvents.topTrigger('sessionMappingSaveError', [mapping, value]);
        }
    });
};

CmsBasePageEIP.prototype.ShowStatusIcons = function(e, aBranchId, aRow) {
    var param = [aBranchId];
    var self = this;
    this.GetBranchDetails(param, function(result) {
        var lInfo = result.d[0];
        //inyectando iconos
        $(lInfo.PublishingInfoImageTag).appendTo(aRow);
        $(lInfo.LockingInfoImageTag).appendTo(aRow);
        if (!lInfo.HasVersionLocalizated) {
            $(lInfo.NoVersionLocalizatedInfoImageTag).appendTo(aRow);
        }
    });
};

CmsBasePageEIP.prototype.ShowCtxMenu = function(e, aBranchId) {
    var param = [aBranchId];
    var self = this;
    if (!self.CtxMenuEnabled) {
        self.CtxMenuEnabled = true;
        this.GetBranchDetails(param, function(result) {
            var lInfo = result.d[0];
            // menu contextual método definido en Pb.Eip.Ribbon.Basic
            self.CtxMenuId = self.OnShowContentVersionCtxMenu(e, lInfo);
            // suscribirnos a la ocultacion del menu
            var lMenu = $find(self.CtxMenuId);
            lMenu.add_hidden(function(e) {
                self.CtxMenuEnabled = false;
                //self.DownliteAll();
            });
        });
    }
    else {
        self.HideCtxMenu();
    }
};

CmsBasePageEIP.prototype.HideCtxMenu = function() {
    this.CtxMenuEnabled = false;
    var lMenu = $find(this.CtxMenuId);
    if (lMenu)
        lMenu.hide();

};

CmsBasePageEIP.prototype.GetBranchDetails = function(aBranchIdList, aSuccessFunc) {
    var self = this;

    var params = $.compactJSON({
        "aOnline": this.IsOnlineRequest,
        "aBranchIdList": aBranchIdList
    });

    $.ajax({
        type: "POST",
        url: "/pb/Services/EIPService.asmx/GetBranchDetails?pbl=" + Pb.Utils.Url.getPageLang(),
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: aSuccessFunc,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            self.ShowBackMsg("Error: " + $.evalJSON(XMLHttpRequest.responseText).Message, "EIPBackgroundProgressError");
        }
    });
};

CmsBasePageEIP.prototype.ShowBackMsg = function(aMessage, aCssClass, aNoAutoFadeOut, aElapsedTimeAutoFadeOut, aCallBackFunction) {
    if (this.OnShowBackgroundMessage) {
        this.OnShowBackgroundMessage(aMessage, aCssClass, aNoAutoFadeOut, aElapsedTimeAutoFadeOut, aCallBackFunction);
    }
};

CmsBasePageEIP.prototype.BuildErrorTraceList = function() {
    var lWrapper = $("#EIPErrorTraceList");
    if (this.TraceErrorList) {
        if (this.TraceErrorList.length > 0) {
            $.each(this.TraceErrorList, function(i, val) {
                var lErrorListItem = $("<div id='EIPErrorListItem'" + i + " class='EIPErrorListItem'>" + val.toString() + "</div>").appendTo(lWrapper);
            });
        }
    }

    $("#EIPspanOcultar_ListaErrores").click(function() {
        $("#EIPErrorTraceListWrapper").fadeOut(300);
    });
};

CmsBasePageEIP.prototype.getContentViewerContainer = function(jSource) {
    if (this.contentViewerContainer === null) {
        this.contentViewerContainer = $('.EIPContentViewerContainer');
    }
    return this.contentViewerContainer;
};

//Aplicar corrección de posicion de debido a jquery layout
CmsBasePageEIP.prototype.ApplyJQueryLayoutTopCorrection = function(top) {
    var cvCont = this.getContentViewerContainer();
    var parentOffset = cvCont.offset();
    top = cvCont.scrollTop() + top - parentOffset.top;
    return top;
};

//Aplicar corrección de posicion de debido a jquery layout
CmsBasePageEIP.prototype.ApplyJQueryLayoutLeftCorrection = function(left) {
    var cvCont = this.getContentViewerContainer();
    var parentOffset = cvCont.offset();
    left = cvCont.scrollLeft() + left - parentOffset.left;
    return left;
};

CmsBasePageEIP.prototype._executeBackofficeMethod = function(serviceName, methodName, methodArguments, onSuccess, onFail, aAsyncRequest) {
    var lUrl = "/pb/Services/" + serviceName + ".asmx/" + methodName + "?pbl=" + Pb.Utils.Url.getPageLang();
    var lAsync = (aAsyncRequest !== false);
    $.ajax({
        async: lAsync,
        type: "POST",
        url: lUrl,
        data: $.compactJSON(methodArguments),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: onSuccess,
        error: onFail ? onFail : function(XMLHttpRequest, textStatus, errorThrown) {
            alert($.evalJSON(XMLHttpRequest.responseText).Message);
        }
    });
    

};
    
